tview

package module
v0.0.0-...-b0d41c4 Latest Latest
Warning

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

Go to latest
Published: Apr 13, 2024 License: MIT Imports: 18 Imported by: 2,389

README

Rich Interactive Widgets for Terminal UIs

PkgGoDev Go Report

This Go package provides commonly used components for terminal based user interfaces.

Screenshot

Among these components are:

  • Input forms (including text input, selections, checkboxes, and buttons)
  • Navigable multi-color text views
  • Editable multi-line text areas
  • Sophisticated navigable table views
  • Flexible tree views
  • Selectable lists
  • Images
  • Grid, Flexbox and page layouts
  • Modal message windows
  • An application wrapper

They come with lots of customization options and can be easily extended to fit your needs.

Usage

To add this package to your project:

go get github.com/rivo/tview@master

Hello World

This basic example creates a box titled "Hello, World!" and displays it in your terminal:

package main

import (
	"github.com/rivo/tview"
)

func main() {
	box := tview.NewBox().SetBorder(true).SetTitle("Hello, world!")
	if err := tview.NewApplication().SetRoot(box, true).Run(); err != nil {
		panic(err)
	}
}

Check out the GitHub Wiki for more examples along with screenshots. Or try the examples in the "demos" subdirectory.

For a presentation highlighting this package, compile and run the program found in the "demos/presentation" subdirectory.

Projects using tview

Documentation

Refer to https://pkg.go.dev/github.com/rivo/tview for the package's documentation. Also check out the Wiki.

Dependencies

This package is based on github.com/gdamore/tcell (and its dependencies) as well as on github.com/rivo/uniseg.

Sponsor this Project

Become a Sponsor on GitHub to further this project!

Versioning and Backwards-Compatibility

I try really hard to keep this project backwards compatible. Your software should not break when you upgrade tview. But this also means that some of its shortcomings that were present in the initial versions will remain. In addition, at least for the time being, you won't find any version tags in this repo. The newest version should be the one to upgrade to. It has all the bugfixes and latest features. Having said that, backwards compatibility may still break when:

  • a new version of an imported package (most likely tcell) changes in such a way that forces me to make changes in tview as well,
  • I fix something that I consider a bug, rather than a feature, something that does not work as originally intended,
  • I make changes to "internal" interfaces such as Primitive. You shouldn't need these interfaces unless you're writing your own primitives for tview. (Yes, I realize these are public interfaces. This has advantages as well as disadvantages. For the time being, it is what it is.)

Your Feedback

Add your issue here on GitHub. Feel free to get in touch if you have any questions.

Code of Conduct

We follow Golang's Code of Conduct which you can find here.

Documentation

Overview

Package tview implements rich widgets for terminal based user interfaces. The widgets provided with this package are useful for data exploration and data entry.

Widgets

The package implements the following widgets:

  • TextView: A scrollable window that display multi-colored text. Text may also be highlighted.
  • TextArea: An editable multi-line text area.
  • Table: A scrollable display of tabular data. Table cells, rows, or columns may also be highlighted.
  • TreeView: A scrollable display for hierarchical data. Tree nodes can be highlighted, collapsed, expanded, and more.
  • List: A navigable text list with optional keyboard shortcuts.
  • InputField: One-line input fields to enter text.
  • DropDown: Drop-down selection fields.
  • Checkbox: Selectable checkbox for boolean values.
  • Image: Displays images.
  • Button: Buttons which get activated when the user selects them.
  • Form: Forms composed of input fields, drop down selections, checkboxes, and buttons.
  • Modal: A centered window with a text message and one or more buttons.
  • Grid: A grid based layout manager.
  • Flex: A Flexbox based layout manager.
  • Pages: A page based layout manager.

The package also provides Application which is used to poll the event queue and draw widgets on screen.

Hello World

The following is a very basic example showing a box with the title "Hello, world!":

package main

import (
	"github.com/rivo/tview"
)

func main() {
	box := tview.NewBox().SetBorder(true).SetTitle("Hello, world!")
	if err := tview.NewApplication().SetRoot(box, true).Run(); err != nil {
		panic(err)
	}
}

First, we create a box primitive with a border and a title. Then we create an application, set the box as its root primitive, and run the event loop. The application exits when the application's Application.Stop function is called or when Ctrl-C is pressed.

More Demos

You will find more demos in the "demos" subdirectory. It also contains a presentation (written using tview) which gives an overview of the different widgets and how they can be used.

Throughout this package, styles are specified using the tcell.Style type. Styles specify colors with the tcell.Color type. Functions such as tcell.GetColor, tcell.NewHexColor, and tcell.NewRGBColor can be used to create colors from W3C color names or RGB values. The tcell.Style type also allows you to specify text attributes such as "bold" or "underline" or a URL which some terminals use to display hyperlinks.

Almost all strings which are displayed may contain style tags. A style tag's content is always wrapped in square brackets. In its simplest form, a style tag specifies the foreground color of the text. Colors in these tags are W3C color names or six hexadecimal digits following a hash tag. Examples:

This is a [red]warning[white]!
The sky is [#8080ff]blue[#ffffff].

A style tag changes the style of the characters following that style tag. There is no style stack and no nesting of style tags.

Style tags are used in almost everything from box titles, list text, form item labels, to table cells. In a TextView, this functionality has to be switched on explicitly. See the TextView documentation for more information.

A style tag's full format looks like this:

[<foreground>:<background>:<attribute flags>:<url>]

Each of the four fields can be left blank and trailing fields can be omitted. (Empty square brackets "[]", however, are not considered style tags.) Fields that are not specified will be left unchanged. A field with just a dash ("-") means "reset to default".

You can specify the following flags to turn on certain attributes (some flags may not be supported by your terminal):

l: blink
b: bold
i: italic
d: dim
r: reverse (switch foreground and background color)
u: underline
s: strike-through

Use uppercase letters to turn off the corresponding attribute, for example, "B" to turn off bold. Uppercase letters have no effect if the attribute was not previously set.

Setting a URL allows you to turn a piece of text into a hyperlink in some terminals. Specify a dash ("-") to specify the end of the hyperlink. Hyperlinks must only contain single-byte characters (e.g. ASCII) and they may not contain bracket characters ("[" or "]").

Examples:

[yellow]Yellow text
[yellow:red]Yellow text on red background
[:red]Red background, text color unchanged
[yellow::u]Yellow text underlined
[::bl]Bold, blinking text
[::-]Colors unchanged, flags reset
[-]Reset foreground color
[::i]Italic and [::I]not italic
Click [:::https://example.com]here[:::-] for example.com.
Send an email to [:::mailto:her@example.com]her/[:::mail:him@example.com]him/[:::mail:them@example.com]them[:::-].
[-:-:-:-]Reset everything
[:]No effect
[]Not a valid style tag, will print square brackets as they are

In the rare event that you want to display a string such as "[red]" or "[#00ff1a]" without applying its effect, you need to put an opening square bracket before the closing square bracket. Note that the text inside the brackets will be matched less strictly than region or colors tags. I.e. any character that may be used in color or region tags will be recognized. Examples:

[red[]      will be output as [red]
["123"[]    will be output as ["123"]
[#6aff00[[] will be output as [#6aff00[]
[a#"[[[]    will be output as [a#"[[]
[]          will be output as [] (see style tags above)
[[]         will be output as [[] (not an escaped tag)

You can use the Escape() function to insert brackets automatically where needed.

Styles

When primitives are instantiated, they are initialized with colors taken from the global Styles variable. You may change this variable to adapt the look and feel of the primitives to your preferred style.

Note that most terminals will not report information about their color theme. This package therefore does not support using the terminal's color theme. The default style is a dark theme and you must change the Styles variable to switch to a light (or other) theme.

Unicode Support

This package supports all unicode characters supported by your terminal.

Mouse Support

If your terminal supports mouse events, you can enable mouse support for your application by calling Application.EnableMouse. Note that this may interfere with your terminal's default mouse behavior. Mouse support is disabled by default.

Concurrency

Many functions in this package are not thread-safe. For many applications, this is not an issue: If your code makes changes in response to key events, the corresponding callback function will execute in the main goroutine and thus will not cause any race conditions. (Exceptions to this are documented.)

If you access your primitives from other goroutines, however, you will need to synchronize execution. The easiest way to do this is to call Application.QueueUpdate or Application.QueueUpdateDraw (see the function documentation for details):

go func() {
  app.QueueUpdateDraw(func() {
    table.SetCellSimple(0, 0, "Foo bar")
  })
}()

One exception to this is the io.Writer interface implemented by TextView. You can safely write to a TextView from any goroutine. See the TextView documentation for details.

You can also call Application.Draw from any goroutine without having to wrap it in Application.QueueUpdate. And, as mentioned above, key event callbacks are executed in the main goroutine and thus should not use Application.QueueUpdate as that may lead to deadlocks. It is also not necessary to call Application.Draw from such callbacks as it will be called automatically.

Type Hierarchy

All widgets listed above contain the Box type. All of Box's functions are therefore available for all widgets, too. Please note that if you are using the functions of Box on a subclass, they will return a *Box, not the subclass. This is a Golang limitation. So while tview supports method chaining in many places, these chains must be broken when using Box's functions. Example:

// This will cause "textArea" to be an empty Box.
textArea := tview.NewTextArea().
	SetMaxLength(256).
	SetPlaceholder("Enter text here").
	SetBorder(true)

You will need to call Box.SetBorder separately:

textArea := tview.NewTextArea().
	SetMaxLength(256).
	SetPlaceholder("Enter text here")
texArea.SetBorder(true)

All widgets also implement the Primitive interface.

The tview package's rendering is based on version 2 of https://github.com/gdamore/tcell. It uses types and constants from that package (e.g. colors, styles, and keyboard values).

Index

Constants

View Source
const (
	// One item per row.
	FlexRow = 0
	// One item per column.
	FlexColumn = 1
	// As defined in CSS, items distributed along a row.
	FlexRowCSS = 1
	// As defined in CSS, items distributed within a column.
	FlexColumnCSS = 0
)

Flex directions.

View Source
const (
	DitheringNone           = iota // No dithering.
	DitheringFloydSteinberg        // Floyd-Steinberg dithering (the default).
)

Types of dithering applied to images.

View Source
const (
	AutocompletedNavigate = iota // The user navigated the autocomplete list (using the errow keys).
	AutocompletedTab             // The user selected an autocomplete entry using the tab key.
	AutocompletedEnter           // The user selected an autocomplete entry using the enter key.
	AutocompletedClick           // The user selected an autocomplete entry by clicking the mouse button on it.
)
View Source
const (
	// Block: General Punctuation U+2000-U+206F (http://unicode.org/charts/PDF/U2000.pdf)
	SemigraphicsHorizontalEllipsis rune = '\u2026' // …

	// Block: Box Drawing U+2500-U+257F (http://unicode.org/charts/PDF/U2500.pdf)
	BoxDrawingsLightHorizontal                    rune = '\u2500' // ─
	BoxDrawingsHeavyHorizontal                    rune = '\u2501' // ━
	BoxDrawingsLightVertical                      rune = '\u2502' // │
	BoxDrawingsHeavyVertical                      rune = '\u2503' // ┃
	BoxDrawingsLightTripleDashHorizontal          rune = '\u2504' // ┄
	BoxDrawingsHeavyTripleDashHorizontal          rune = '\u2505' // ┅
	BoxDrawingsLightTripleDashVertical            rune = '\u2506' // ┆
	BoxDrawingsHeavyTripleDashVertical            rune = '\u2507' // ┇
	BoxDrawingsLightQuadrupleDashHorizontal       rune = '\u2508' // ┈
	BoxDrawingsHeavyQuadrupleDashHorizontal       rune = '\u2509' // ┉
	BoxDrawingsLightQuadrupleDashVertical         rune = '\u250a' // ┊
	BoxDrawingsHeavyQuadrupleDashVertical         rune = '\u250b' // ┋
	BoxDrawingsLightDownAndRight                  rune = '\u250c' // ┌
	BoxDrawingsDownLightAndRightHeavy             rune = '\u250d' // ┍
	BoxDrawingsDownHeavyAndRightLight             rune = '\u250e' // ┎
	BoxDrawingsHeavyDownAndRight                  rune = '\u250f' // ┏
	BoxDrawingsLightDownAndLeft                   rune = '\u2510' // ┐
	BoxDrawingsDownLightAndLeftHeavy              rune = '\u2511' // ┑
	BoxDrawingsDownHeavyAndLeftLight              rune = '\u2512' // ┒
	BoxDrawingsHeavyDownAndLeft                   rune = '\u2513' // ┓
	BoxDrawingsLightUpAndRight                    rune = '\u2514' // └
	BoxDrawingsUpLightAndRightHeavy               rune = '\u2515' // ┕
	BoxDrawingsUpHeavyAndRightLight               rune = '\u2516' // ┖
	BoxDrawingsHeavyUpAndRight                    rune = '\u2517' // ┗
	BoxDrawingsLightUpAndLeft                     rune = '\u2518' // ┘
	BoxDrawingsUpLightAndLeftHeavy                rune = '\u2519' // ┙
	BoxDrawingsUpHeavyAndLeftLight                rune = '\u251a' // ┚
	BoxDrawingsHeavyUpAndLeft                     rune = '\u251b' // ┛
	BoxDrawingsLightVerticalAndRight              rune = '\u251c' // ├
	BoxDrawingsVerticalLightAndRightHeavy         rune = '\u251d' // ┝
	BoxDrawingsUpHeavyAndRightDownLight           rune = '\u251e' // ┞
	BoxDrawingsDownHeavyAndRightUpLight           rune = '\u251f' // ┟
	BoxDrawingsVerticalHeavyAndRightLight         rune = '\u2520' // ┠
	BoxDrawingsDownLightAndRightUpHeavy           rune = '\u2521' // ┡
	BoxDrawingsUpLightAndRightDownHeavy           rune = '\u2522' // ┢
	BoxDrawingsHeavyVerticalAndRight              rune = '\u2523' // ┣
	BoxDrawingsLightVerticalAndLeft               rune = '\u2524' // ┤
	BoxDrawingsVerticalLightAndLeftHeavy          rune = '\u2525' // ┥
	BoxDrawingsUpHeavyAndLeftDownLight            rune = '\u2526' // ┦
	BoxDrawingsDownHeavyAndLeftUpLight            rune = '\u2527' // ┧
	BoxDrawingsVerticalHeavyAndLeftLight          rune = '\u2528' // ┨
	BoxDrawingsDownLightAndLeftUpHeavy            rune = '\u2529' // ┨
	BoxDrawingsUpLightAndLeftDownHeavy            rune = '\u252a' // ┪
	BoxDrawingsHeavyVerticalAndLeft               rune = '\u252b' // ┫
	BoxDrawingsLightDownAndHorizontal             rune = '\u252c' // ┬
	BoxDrawingsLeftHeavyAndRightDownLight         rune = '\u252d' // ┭
	BoxDrawingsRightHeavyAndLeftDownLight         rune = '\u252e' // ┮
	BoxDrawingsDownLightAndHorizontalHeavy        rune = '\u252f' // ┯
	BoxDrawingsDownHeavyAndHorizontalLight        rune = '\u2530' // ┰
	BoxDrawingsRightLightAndLeftDownHeavy         rune = '\u2531' // ┱
	BoxDrawingsLeftLightAndRightDownHeavy         rune = '\u2532' // ┲
	BoxDrawingsHeavyDownAndHorizontal             rune = '\u2533' // ┳
	BoxDrawingsLightUpAndHorizontal               rune = '\u2534' // ┴
	BoxDrawingsLeftHeavyAndRightUpLight           rune = '\u2535' // ┵
	BoxDrawingsRightHeavyAndLeftUpLight           rune = '\u2536' // ┶
	BoxDrawingsUpLightAndHorizontalHeavy          rune = '\u2537' // ┷
	BoxDrawingsUpHeavyAndHorizontalLight          rune = '\u2538' // ┸
	BoxDrawingsRightLightAndLeftUpHeavy           rune = '\u2539' // ┹
	BoxDrawingsLeftLightAndRightUpHeavy           rune = '\u253a' // ┺
	BoxDrawingsHeavyUpAndHorizontal               rune = '\u253b' // ┻
	BoxDrawingsLightVerticalAndHorizontal         rune = '\u253c' // ┼
	BoxDrawingsLeftHeavyAndRightVerticalLight     rune = '\u253d' // ┽
	BoxDrawingsRightHeavyAndLeftVerticalLight     rune = '\u253e' // ┾
	BoxDrawingsVerticalLightAndHorizontalHeavy    rune = '\u253f' // ┿
	BoxDrawingsUpHeavyAndDownHorizontalLight      rune = '\u2540' // ╀
	BoxDrawingsDownHeavyAndUpHorizontalLight      rune = '\u2541' // ╁
	BoxDrawingsVerticalHeavyAndHorizontalLight    rune = '\u2542' // ╂
	BoxDrawingsLeftUpHeavyAndRightDownLight       rune = '\u2543' // ╃
	BoxDrawingsRightUpHeavyAndLeftDownLight       rune = '\u2544' // ╄
	BoxDrawingsLeftDownHeavyAndRightUpLight       rune = '\u2545' // ╅
	BoxDrawingsRightDownHeavyAndLeftUpLight       rune = '\u2546' // ╆
	BoxDrawingsDownLightAndUpHorizontalHeavy      rune = '\u2547' // ╇
	BoxDrawingsUpLightAndDownHorizontalHeavy      rune = '\u2548' // ╈
	BoxDrawingsRightLightAndLeftVerticalHeavy     rune = '\u2549' // ╉
	BoxDrawingsLeftLightAndRightVerticalHeavy     rune = '\u254a' // ╊
	BoxDrawingsHeavyVerticalAndHorizontal         rune = '\u254b' // ╋
	BoxDrawingsLightDoubleDashHorizontal          rune = '\u254c' // ╌
	BoxDrawingsHeavyDoubleDashHorizontal          rune = '\u254d' // ╍
	BoxDrawingsLightDoubleDashVertical            rune = '\u254e' // ╎
	BoxDrawingsHeavyDoubleDashVertical            rune = '\u254f' // ╏
	BoxDrawingsDoubleHorizontal                   rune = '\u2550' // ═
	BoxDrawingsDoubleVertical                     rune = '\u2551' // ║
	BoxDrawingsDownSingleAndRightDouble           rune = '\u2552' // ╒
	BoxDrawingsDownDoubleAndRightSingle           rune = '\u2553' // ╓
	BoxDrawingsDoubleDownAndRight                 rune = '\u2554' // ╔
	BoxDrawingsDownSingleAndLeftDouble            rune = '\u2555' // ╕
	BoxDrawingsDownDoubleAndLeftSingle            rune = '\u2556' // ╖
	BoxDrawingsDoubleDownAndLeft                  rune = '\u2557' // ╗
	BoxDrawingsUpSingleAndRightDouble             rune = '\u2558' // ╘
	BoxDrawingsUpDoubleAndRightSingle             rune = '\u2559' // ╙
	BoxDrawingsDoubleUpAndRight                   rune = '\u255a' // ╚
	BoxDrawingsUpSingleAndLeftDouble              rune = '\u255b' // ╛
	BoxDrawingsUpDoubleAndLeftSingle              rune = '\u255c' // ╜
	BoxDrawingsDoubleUpAndLeft                    rune = '\u255d' // ╝
	BoxDrawingsVerticalSingleAndRightDouble       rune = '\u255e' // ╞
	BoxDrawingsVerticalDoubleAndRightSingle       rune = '\u255f' // ╟
	BoxDrawingsDoubleVerticalAndRight             rune = '\u2560' // ╠
	BoxDrawingsVerticalSingleAndLeftDouble        rune = '\u2561' // ╡
	BoxDrawingsVerticalDoubleAndLeftSingle        rune = '\u2562' // ╢
	BoxDrawingsDoubleVerticalAndLeft              rune = '\u2563' // ╣
	BoxDrawingsDownSingleAndHorizontalDouble      rune = '\u2564' // ╤
	BoxDrawingsDownDoubleAndHorizontalSingle      rune = '\u2565' // ╥
	BoxDrawingsDoubleDownAndHorizontal            rune = '\u2566' // ╦
	BoxDrawingsUpSingleAndHorizontalDouble        rune = '\u2567' // ╧
	BoxDrawingsUpDoubleAndHorizontalSingle        rune = '\u2568' // ╨
	BoxDrawingsDoubleUpAndHorizontal              rune = '\u2569' // ╩
	BoxDrawingsVerticalSingleAndHorizontalDouble  rune = '\u256a' // ╪
	BoxDrawingsVerticalDoubleAndHorizontalSingle  rune = '\u256b' // ╫
	BoxDrawingsDoubleVerticalAndHorizontal        rune = '\u256c' // ╬
	BoxDrawingsLightArcDownAndRight               rune = '\u256d' // ╭
	BoxDrawingsLightArcDownAndLeft                rune = '\u256e' // ╮
	BoxDrawingsLightArcUpAndLeft                  rune = '\u256f' // ╯
	BoxDrawingsLightArcUpAndRight                 rune = '\u2570' // ╰
	BoxDrawingsLightDiagonalUpperRightToLowerLeft rune = '\u2571' // ╱
	BoxDrawingsLightDiagonalUpperLeftToLowerRight rune = '\u2572' // ╲
	BoxDrawingsLightDiagonalCross                 rune = '\u2573' // ╳
	BoxDrawingsLightLeft                          rune = '\u2574' // ╴
	BoxDrawingsLightUp                            rune = '\u2575' // ╵
	BoxDrawingsLightRight                         rune = '\u2576' // ╶
	BoxDrawingsLightDown                          rune = '\u2577' // ╷
	BoxDrawingsHeavyLeft                          rune = '\u2578' // ╸
	BoxDrawingsHeavyUp                            rune = '\u2579' // ╹
	BoxDrawingsHeavyRight                         rune = '\u257a' // ╺
	BoxDrawingsHeavyDown                          rune = '\u257b' // ╻
	BoxDrawingsLightLeftAndHeavyRight             rune = '\u257c' // ╼
	BoxDrawingsLightUpAndHeavyDown                rune = '\u257d' // ╽
	BoxDrawingsHeavyLeftAndLightRight             rune = '\u257e' // ╾
	BoxDrawingsHeavyUpAndLightDown                rune = '\u257f' // ╿

	// Block Elements.
	BlockUpperHalfBlock                              rune = '\u2580' // ▀
	BlockLowerOneEighthBlock                         rune = '\u2581' // ▁
	BlockLowerOneQuarterBlock                        rune = '\u2582' // ▂
	BlockLowerThreeEighthsBlock                      rune = '\u2583' // ▃
	BlockLowerHalfBlock                              rune = '\u2584' // ▄
	BlockLowerFiveEighthsBlock                       rune = '\u2585' // ▅
	BlockLowerThreeQuartersBlock                     rune = '\u2586' // ▆
	BlockLowerSevenEighthsBlock                      rune = '\u2587' // ▇
	BlockFullBlock                                   rune = '\u2588' // █
	BlockLeftSevenEighthsBlock                       rune = '\u2589' // ▉
	BlockLeftThreeQuartersBlock                      rune = '\u258A' // ▊
	BlockLeftFiveEighthsBlock                        rune = '\u258B' // ▋
	BlockLeftHalfBlock                               rune = '\u258C' // ▌
	BlockLeftThreeEighthsBlock                       rune = '\u258D' // ▍
	BlockLeftOneQuarterBlock                         rune = '\u258E' // ▎
	BlockLeftOneEighthBlock                          rune = '\u258F' // ▏
	BlockRightHalfBlock                              rune = '\u2590' // ▐
	BlockLightShade                                  rune = '\u2591' // ░
	BlockMediumShade                                 rune = '\u2592' // ▒
	BlockDarkShade                                   rune = '\u2593' // ▓
	BlockUpperOneEighthBlock                         rune = '\u2594' // ▔
	BlockRightOneEighthBlock                         rune = '\u2595' // ▕
	BlockQuadrantLowerLeft                           rune = '\u2596' // ▖
	BlockQuadrantLowerRight                          rune = '\u2597' // ▗
	BlockQuadrantUpperLeft                           rune = '\u2598' // ▘
	BlockQuadrantUpperLeftAndLowerLeftAndLowerRight  rune = '\u2599' // ▙
	BlockQuadrantUpperLeftAndLowerRight              rune = '\u259A' // ▚
	BlockQuadrantUpperLeftAndUpperRightAndLowerLeft  rune = '\u259B' // ▛
	BlockQuadrantUpperLeftAndUpperRightAndLowerRight rune = '\u259C' // ▜
	BlockQuadrantUpperRight                          rune = '\u259D' // ▝
	BlockQuadrantUpperRightAndLowerLeft              rune = '\u259E' // ▞
	BlockQuadrantUpperRightAndLowerLeftAndLowerRight rune = '\u259F' // ▟
)

Semigraphics provides an easy way to access unicode characters for drawing.

Named like the unicode characters, 'Semigraphics'-prefix used if unicode block isn't prefixed itself.

View Source
const (
	AlignLeft = iota
	AlignCenter
	AlignRight
	AlignTop    = 0
	AlignBottom = 2
)

Text alignment within a box. Also used to align images.

View Source
const TrueColor = 16777216

The number of colors supported by true color terminals (R*G*B = 256*256*256).

Variables

View Source
var (
	// DefaultFormFieldWidth is the default field screen width of form elements
	// whose field width is flexible (0). This is used in the Form class for
	// horizontal layouts.
	DefaultFormFieldWidth = 10

	// DefaultFormFieldHeight is the default field height of multi-line form
	// elements whose field height is flexible (0).
	DefaultFormFieldHeight = 5
)
View Source
var (
	// InputFieldInteger accepts integers.
	InputFieldInteger = func(text string, ch rune) bool {
		if text == "-" {
			return true
		}
		_, err := strconv.Atoi(text)
		return err == nil
	}

	// InputFieldFloat accepts floating-point numbers.
	InputFieldFloat = func(text string, ch rune) bool {
		if text == "-" || text == "." || text == "-." {
			return true
		}
		_, err := strconv.ParseFloat(text, 64)
		return err == nil
	}

	// InputFieldMaxLength returns an input field accept handler which accepts
	// input strings up to a given length. Use it like this:
	//
	//   inputField.SetAcceptanceFunc(InputFieldMaxLength(10)) // Accept up to 10 characters.
	InputFieldMaxLength = func(maxLength int) func(text string, ch rune) bool {
		return func(text string, ch rune) bool {
			return len([]rune(text)) <= maxLength
		}
	}
)

Predefined InputField acceptance functions.

View Source
var Borders = struct {
	Horizontal  rune
	Vertical    rune
	TopLeft     rune
	TopRight    rune
	BottomLeft  rune
	BottomRight rune

	LeftT   rune
	RightT  rune
	TopT    rune
	BottomT rune
	Cross   rune

	HorizontalFocus  rune
	VerticalFocus    rune
	TopLeftFocus     rune
	TopRightFocus    rune
	BottomLeftFocus  rune
	BottomRightFocus rune
}{
	Horizontal:  BoxDrawingsLightHorizontal,
	Vertical:    BoxDrawingsLightVertical,
	TopLeft:     BoxDrawingsLightDownAndRight,
	TopRight:    BoxDrawingsLightDownAndLeft,
	BottomLeft:  BoxDrawingsLightUpAndRight,
	BottomRight: BoxDrawingsLightUpAndLeft,

	LeftT:   BoxDrawingsLightVerticalAndRight,
	RightT:  BoxDrawingsLightVerticalAndLeft,
	TopT:    BoxDrawingsLightDownAndHorizontal,
	BottomT: BoxDrawingsLightUpAndHorizontal,
	Cross:   BoxDrawingsLightVerticalAndHorizontal,

	HorizontalFocus:  BoxDrawingsDoubleHorizontal,
	VerticalFocus:    BoxDrawingsDoubleVertical,
	TopLeftFocus:     BoxDrawingsDoubleDownAndRight,
	TopRightFocus:    BoxDrawingsDoubleDownAndLeft,
	BottomLeftFocus:  BoxDrawingsDoubleUpAndRight,
	BottomRightFocus: BoxDrawingsDoubleUpAndLeft,
}

Borders defines various borders used when primitives are drawn. These may be changed to accommodate a different look and feel.

View Source
var DoubleClickInterval = 500 * time.Millisecond

DoubleClickInterval specifies the maximum time between clicks to register a double click rather than click.

View Source
var NewLine = "\n"

NewLine is the string sequence to be inserted when hitting the Enter key in a TextArea. The default is "\n" but you may change it to "\r\n" if required.

View Source
var SemigraphicJoints = map[string]rune{

	string([]rune{BoxDrawingsLightHorizontal, BoxDrawingsLightVertical}): BoxDrawingsLightVerticalAndHorizontal,

	string([]rune{BoxDrawingsLightHorizontal, BoxDrawingsLightDownAndRight}): BoxDrawingsLightDownAndHorizontal,

	string([]rune{BoxDrawingsLightHorizontal, BoxDrawingsLightDownAndLeft}): BoxDrawingsLightDownAndHorizontal,

	string([]rune{BoxDrawingsLightHorizontal, BoxDrawingsLightUpAndRight}): BoxDrawingsLightUpAndHorizontal,

	string([]rune{BoxDrawingsLightHorizontal, BoxDrawingsLightUpAndLeft}): BoxDrawingsLightUpAndHorizontal,

	string([]rune{BoxDrawingsLightHorizontal, BoxDrawingsLightVerticalAndRight}): BoxDrawingsLightVerticalAndHorizontal,

	string([]rune{BoxDrawingsLightHorizontal, BoxDrawingsLightVerticalAndLeft}): BoxDrawingsLightVerticalAndHorizontal,

	string([]rune{BoxDrawingsLightHorizontal, BoxDrawingsLightDownAndHorizontal}): BoxDrawingsLightDownAndHorizontal,

	string([]rune{BoxDrawingsLightHorizontal, BoxDrawingsLightUpAndHorizontal}): BoxDrawingsLightUpAndHorizontal,

	string([]rune{BoxDrawingsLightHorizontal, BoxDrawingsLightVerticalAndHorizontal}): BoxDrawingsLightVerticalAndHorizontal,

	string([]rune{BoxDrawingsLightVertical, BoxDrawingsLightDownAndRight}): BoxDrawingsLightVerticalAndRight,

	string([]rune{BoxDrawingsLightVertical, BoxDrawingsLightDownAndLeft}): BoxDrawingsLightVerticalAndLeft,

	string([]rune{BoxDrawingsLightVertical, BoxDrawingsLightUpAndRight}): BoxDrawingsLightVerticalAndRight,

	string([]rune{BoxDrawingsLightVertical, BoxDrawingsLightUpAndLeft}): BoxDrawingsLightVerticalAndLeft,

	string([]rune{BoxDrawingsLightVertical, BoxDrawingsLightVerticalAndRight}): BoxDrawingsLightVerticalAndRight,

	string([]rune{BoxDrawingsLightVertical, BoxDrawingsLightVerticalAndLeft}): BoxDrawingsLightVerticalAndLeft,

	string([]rune{BoxDrawingsLightVertical, BoxDrawingsLightDownAndHorizontal}): BoxDrawingsLightVerticalAndHorizontal,

	string([]rune{BoxDrawingsLightVertical, BoxDrawingsLightUpAndHorizontal}): BoxDrawingsLightVerticalAndHorizontal,

	string([]rune{BoxDrawingsLightVertical, BoxDrawingsLightVerticalAndHorizontal}): BoxDrawingsLightVerticalAndHorizontal,

	string([]rune{BoxDrawingsLightDownAndRight, BoxDrawingsLightDownAndLeft}): BoxDrawingsLightDownAndHorizontal,

	string([]rune{BoxDrawingsLightDownAndRight, BoxDrawingsLightUpAndRight}): BoxDrawingsLightVerticalAndRight,

	string([]rune{BoxDrawingsLightDownAndRight, BoxDrawingsLightUpAndLeft}): BoxDrawingsLightVerticalAndHorizontal,

	string([]rune{BoxDrawingsLightDownAndRight, BoxDrawingsLightVerticalAndRight}): BoxDrawingsLightVerticalAndRight,

	string([]rune{BoxDrawingsLightDownAndRight, BoxDrawingsLightVerticalAndLeft}): BoxDrawingsLightVerticalAndHorizontal,

	string([]rune{BoxDrawingsLightDownAndRight, BoxDrawingsLightDownAndHorizontal}): BoxDrawingsLightDownAndHorizontal,

	string([]rune{BoxDrawingsLightDownAndRight, BoxDrawingsLightUpAndHorizontal}): BoxDrawingsLightVerticalAndHorizontal,

	string([]rune{BoxDrawingsLightDownAndRight, BoxDrawingsLightVerticalAndHorizontal}): BoxDrawingsLightVerticalAndHorizontal,

	string([]rune{BoxDrawingsLightDownAndLeft, BoxDrawingsLightUpAndRight}): BoxDrawingsLightVerticalAndHorizontal,

	string([]rune{BoxDrawingsLightDownAndLeft, BoxDrawingsLightUpAndLeft}): BoxDrawingsLightVerticalAndLeft,

	string([]rune{BoxDrawingsLightDownAndLeft, BoxDrawingsLightVerticalAndRight}): BoxDrawingsLightVerticalAndHorizontal,

	string([]rune{BoxDrawingsLightDownAndLeft, BoxDrawingsLightVerticalAndLeft}): BoxDrawingsLightVerticalAndLeft,

	string([]rune{BoxDrawingsLightDownAndLeft, BoxDrawingsLightDownAndHorizontal}): BoxDrawingsLightDownAndHorizontal,

	string([]rune{BoxDrawingsLightDownAndLeft, BoxDrawingsLightUpAndHorizontal}): BoxDrawingsLightVerticalAndHorizontal,

	string([]rune{BoxDrawingsLightDownAndLeft, BoxDrawingsLightVerticalAndHorizontal}): BoxDrawingsLightVerticalAndHorizontal,

	string([]rune{BoxDrawingsLightUpAndRight, BoxDrawingsLightUpAndLeft}): BoxDrawingsLightUpAndHorizontal,

	string([]rune{BoxDrawingsLightUpAndRight, BoxDrawingsLightVerticalAndRight}): BoxDrawingsLightVerticalAndRight,

	string([]rune{BoxDrawingsLightUpAndRight, BoxDrawingsLightVerticalAndLeft}): BoxDrawingsLightVerticalAndHorizontal,

	string([]rune{BoxDrawingsLightUpAndRight, BoxDrawingsLightDownAndHorizontal}): BoxDrawingsLightVerticalAndHorizontal,

	string([]rune{BoxDrawingsLightUpAndRight, BoxDrawingsLightUpAndHorizontal}): BoxDrawingsLightUpAndHorizontal,

	string([]rune{BoxDrawingsLightUpAndRight, BoxDrawingsLightVerticalAndHorizontal}): BoxDrawingsLightVerticalAndHorizontal,

	string([]rune{BoxDrawingsLightUpAndLeft, BoxDrawingsLightVerticalAndRight}): BoxDrawingsLightVerticalAndHorizontal,

	string([]rune{BoxDrawingsLightUpAndLeft, BoxDrawingsLightVerticalAndLeft}): BoxDrawingsLightVerticalAndLeft,

	string([]rune{BoxDrawingsLightUpAndLeft, BoxDrawingsLightDownAndHorizontal}): BoxDrawingsLightVerticalAndHorizontal,

	string([]rune{BoxDrawingsLightUpAndLeft, BoxDrawingsLightUpAndHorizontal}): BoxDrawingsLightUpAndHorizontal,

	string([]rune{BoxDrawingsLightUpAndLeft, BoxDrawingsLightVerticalAndHorizontal}): BoxDrawingsLightVerticalAndHorizontal,

	string([]rune{BoxDrawingsLightVerticalAndRight, BoxDrawingsLightVerticalAndLeft}): BoxDrawingsLightVerticalAndHorizontal,

	string([]rune{BoxDrawingsLightVerticalAndRight, BoxDrawingsLightDownAndHorizontal}): BoxDrawingsLightVerticalAndHorizontal,

	string([]rune{BoxDrawingsLightVerticalAndRight, BoxDrawingsLightUpAndHorizontal}): BoxDrawingsLightVerticalAndHorizontal,

	string([]rune{BoxDrawingsLightVerticalAndRight, BoxDrawingsLightVerticalAndHorizontal}): BoxDrawingsLightVerticalAndHorizontal,

	string([]rune{BoxDrawingsLightVerticalAndLeft, BoxDrawingsLightDownAndHorizontal}): BoxDrawingsLightVerticalAndHorizontal,

	string([]rune{BoxDrawingsLightVerticalAndLeft, BoxDrawingsLightUpAndHorizontal}): BoxDrawingsLightVerticalAndHorizontal,

	string([]rune{BoxDrawingsLightVerticalAndLeft, BoxDrawingsLightVerticalAndHorizontal}): BoxDrawingsLightVerticalAndHorizontal,

	string([]rune{BoxDrawingsLightDownAndHorizontal, BoxDrawingsLightUpAndHorizontal}): BoxDrawingsLightVerticalAndHorizontal,

	string([]rune{BoxDrawingsLightDownAndHorizontal, BoxDrawingsLightVerticalAndHorizontal}): BoxDrawingsLightVerticalAndHorizontal,

	string([]rune{BoxDrawingsLightUpAndHorizontal, BoxDrawingsLightVerticalAndHorizontal}): BoxDrawingsLightVerticalAndHorizontal,
}

SemigraphicJoints is a map for joining semigraphic (or otherwise) runes. So far only light lines are supported but if you want to change the border styling you need to provide the joints, too. The matching will be sorted ascending by rune value, so you don't need to provide all rune combinations, e.g. (─) + (│) = (┼) will also match (│) + (─) = (┼)

View Source
var Styles = Theme{
	PrimitiveBackgroundColor:    tcell.ColorBlack,
	ContrastBackgroundColor:     tcell.ColorBlue,
	MoreContrastBackgroundColor: tcell.ColorGreen,
	BorderColor:                 tcell.ColorWhite,
	TitleColor:                  tcell.ColorWhite,
	GraphicsColor:               tcell.ColorWhite,
	PrimaryTextColor:            tcell.ColorWhite,
	SecondaryTextColor:          tcell.ColorYellow,
	TertiaryTextColor:           tcell.ColorGreen,
	InverseTextColor:            tcell.ColorBlue,
	ContrastSecondaryTextColor:  tcell.ColorNavy,
}

Styles defines the theme for applications. The default is for a black background and some basic colors: black, white, yellow, green, cyan, and blue.

View Source
var TabSize = 4

TabSize is the number of spaces with which a tab character will be replaced.

Functions

func ANSIWriter

func ANSIWriter(writer io.Writer) io.Writer

ANSIWriter returns an io.Writer which translates any ANSI escape codes written to it into tview style tags. Other escape codes don't have an effect and are simply removed. The translated text is written to the provided writer.

func Escape

func Escape(text string) string

Escape escapes the given text such that color and/or region tags are not recognized and substituted by the print functions of this package. For example, to include a tag-like string in a box title or in a TextView:

box.SetTitle(tview.Escape("[squarebrackets]"))
fmt.Fprint(textView, tview.Escape(`["quoted"]`))

func Print

func Print(screen tcell.Screen, text string, x, y, maxWidth, align int, color tcell.Color) (int, int)

Print prints text onto the screen into the given box at (x,y,maxWidth,1), not exceeding that box. "align" is one of AlignLeft, AlignCenter, or AlignRight. The screen's background color will not be changed.

You can change the colors and text styles mid-text by inserting a style tag. See the package description for details.

Returns the number of actual bytes of the text printed (including style tags) and the actual width used for the printed runes.

func PrintJoinedSemigraphics

func PrintJoinedSemigraphics(screen tcell.Screen, x, y int, ch rune, style tcell.Style)

PrintJoinedSemigraphics prints a semigraphics rune into the screen at the given position with the given style, joining it with any existing semigraphics rune.At this point, only regular single line borders are supported.

func PrintSimple

func PrintSimple(screen tcell.Screen, text string, x, y int)

PrintSimple prints white text to the screen at the given position.

func TaggedStringWidth

func TaggedStringWidth(text string) (width int)

TaggedStringWidth returns the width of the given string needed to print it on screen. The text may contain style tags which are not counted.

func TranslateANSI

func TranslateANSI(text string) string

TranslateANSI replaces ANSI escape sequences found in the provided string with tview's style tags and returns the resulting string.

func WordWrap

func WordWrap(text string, width int) (lines []string)

WordWrap splits a text such that each resulting line does not exceed the given screen width. Split points are determined using the algorithm described in Unicode Standard Annex #14.

This function considers style tags to have no width.

Types

type Application

type Application struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

Application represents the top node of an application.

It is not strictly required to use this class as none of the other classes depend on it. However, it provides useful tools to set up an application and plays nicely with all widgets.

The following command displays a primitive p on the screen until Ctrl-C is pressed:

if err := tview.NewApplication().SetRoot(p, true).Run(); err != nil {
    panic(err)
}

func NewApplication

func NewApplication() *Application

NewApplication creates and returns a new application.

func (*Application) Draw

func (a *Application) Draw() *Application

Draw refreshes the screen (during the next update cycle). It calls the Draw() function of the application's root primitive and then syncs the screen buffer. It is almost never necessary to call this function. It can actually deadlock your application if you call it from the main thread (e.g. in a callback function of a widget). Please see https://github.com/rivo/tview/wiki/Concurrency for details.

func (*Application) EnableMouse

func (a *Application) EnableMouse(enable bool) *Application

EnableMouse enables mouse events or disables them (if "false" is provided).

func (*Application) EnablePaste

func (a *Application) EnablePaste(enable bool) *Application

EnablePaste enables the capturing of paste events or disables them (if "false" is provided). This must be supported by the terminal.

Widgets won't interpret paste events for navigation or selection purposes. Paste events are typically only used to insert a block of text into an InputField or a TextArea.

func (*Application) ForceDraw

func (a *Application) ForceDraw() *Application

ForceDraw refreshes the screen immediately. Use this function with caution as it may lead to race conditions with updates to primitives in other goroutines. It is always preferable to call Application.Draw instead. Never call this function from a goroutine.

It is safe to call this function during queued updates and direct event handling.

func (*Application) GetAfterDrawFunc

func (a *Application) GetAfterDrawFunc() func(screen tcell.Screen)

GetAfterDrawFunc returns the callback function installed with SetAfterDrawFunc() or nil if none has been installed.

func (*Application) GetBeforeDrawFunc

func (a *Application) GetBeforeDrawFunc() func(screen tcell.Screen) bool

GetBeforeDrawFunc returns the callback function installed with SetBeforeDrawFunc() or nil if none has been installed.

func (*Application) GetFocus

func (a *Application) GetFocus() Primitive

GetFocus returns the primitive which has the current focus. If none has it, nil is returned.

func (*Application) GetInputCapture

func (a *Application) GetInputCapture() func(event *tcell.EventKey) *tcell.EventKey

GetInputCapture returns the function installed with SetInputCapture() or nil if no such function has been installed.

func (*Application) GetMouseCapture

func (a *Application) GetMouseCapture() func(event *tcell.EventMouse, action MouseAction) (*tcell.EventMouse, MouseAction)

GetMouseCapture returns the function installed with SetMouseCapture() or nil if no such function has been installed.

func (*Application) QueueEvent

func (a *Application) QueueEvent(event tcell.Event) *Application

QueueEvent sends an event to the Application event loop.

It is not recommended for event to be nil.

func (*Application) QueueUpdate

func (a *Application) QueueUpdate(f func()) *Application

QueueUpdate is used to synchronize access to primitives from non-main goroutines. The provided function will be executed as part of the event loop and thus will not cause race conditions with other such update functions or the Draw() function.

Note that Draw() is not implicitly called after the execution of f as that may not be desirable. You can call Draw() from f if the screen should be refreshed after each update. Alternatively, use QueueUpdateDraw() to follow up with an immediate refresh of the screen.

This function returns after f has executed.

func (*Application) QueueUpdateDraw

func (a *Application) QueueUpdateDraw(f func()) *Application

QueueUpdateDraw works like QueueUpdate() except it refreshes the screen immediately after executing f.

func (*Application) ResizeToFullScreen

func (a *Application) ResizeToFullScreen(p Primitive) *Application

ResizeToFullScreen resizes the given primitive such that it fills the entire screen.

func (*Application) Run

func (a *Application) Run() error

Run starts the application and thus the event loop. This function returns when Stop() was called.

func (*Application) SetAfterDrawFunc

func (a *Application) SetAfterDrawFunc(handler func(screen tcell.Screen)) *Application

SetAfterDrawFunc installs a callback function which is invoked after the root primitive was drawn during screen updates.

Provide nil to uninstall the callback function.

func (*Application) SetBeforeDrawFunc

func (a *Application) SetBeforeDrawFunc(handler func(screen tcell.Screen) bool) *Application

SetBeforeDrawFunc installs a callback function which is invoked just before the root primitive is drawn during screen updates. If the function returns true, drawing will not continue, i.e. the root primitive will not be drawn (and an after-draw-handler will not be called).

Note that the screen is not cleared by the application. To clear the screen, you may call screen.Clear().

Provide nil to uninstall the callback function.

func (*Application) SetFocus

func (a *Application) SetFocus(p Primitive) *Application

SetFocus sets the focus to a new primitive. All key events will be directed down the hierarchy (starting at the root) until a primitive handles them, which per default goes towards the focused primitive.

Blur() will be called on the previously focused primitive. Focus() will be called on the new primitive.

func (*Application) SetInputCapture

func (a *Application) SetInputCapture(capture func(event *tcell.EventKey) *tcell.EventKey) *Application

SetInputCapture sets a function which captures all key events before they are forwarded to the key event handler of the primitive which currently has focus. This function can then choose to forward that key event (or a different one) by returning it or stop the key event processing by returning nil.

The only default global key event is Ctrl-C which stops the application. It requires special handling:

  • If you do not wish to change the default behavior, return the original event object passed to your input capture function.
  • If you wish to block Ctrl-C from any functionality, return nil.
  • If you do not wish Ctrl-C to stop the application but still want to forward the Ctrl-C event to primitives down the hierarchy, return a new key event with the same key and modifiers, e.g. tcell.NewEventKey(tcell.KeyCtrlC, 0, tcell.ModNone).

Pasted key events are not forwarded to the input capture function if pasting is enabled (see Application.EnablePaste).

func (*Application) SetMouseCapture

func (a *Application) SetMouseCapture(capture func(event *tcell.EventMouse, action MouseAction) (*tcell.EventMouse, MouseAction)) *Application

SetMouseCapture sets a function which captures mouse events (consisting of the original tcell mouse event and the semantic mouse action) before they are forwarded to the appropriate mouse event handler. This function can then choose to forward that event (or a different one) by returning it or stop the event processing by returning a nil mouse event.

func (*Application) SetRoot

func (a *Application) SetRoot(root Primitive, fullscreen bool) *Application

SetRoot sets the root primitive for this application. If "fullscreen" is set to true, the root primitive's position will be changed to fill the screen.

This function must be called at least once or nothing will be displayed when the application starts.

It also calls SetFocus() on the primitive.

func (*Application) SetScreen

func (a *Application) SetScreen(screen tcell.Screen) *Application

SetScreen allows you to provide your own tcell.Screen object. For most applications, this is not needed and you should be familiar with tcell.Screen when using this function.

This function is typically called before the first call to Run(). Init() need not be called on the screen.

func (*Application) Stop

func (a *Application) Stop()

Stop stops the application, causing Run() to return.

func (*Application) Suspend

func (a *Application) Suspend(f func()) bool

Suspend temporarily suspends the application by exiting terminal UI mode and invoking the provided function "f". When "f" returns, terminal UI mode is entered again and the application resumes.

A return value of true indicates that the application was suspended and "f" was called. If false is returned, the application was already suspended, terminal UI mode was not exited, and "f" was not called.

func (*Application) Sync

func (a *Application) Sync() *Application

Sync forces a full re-sync of the screen buffer with the actual screen during the next event cycle. This is useful for when the terminal screen is corrupted so you may want to offer your users a keyboard shortcut to refresh the screen.

type Box

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

Box implements the Primitive interface with an empty background and optional elements such as a border and a title. Box itself does not hold any content but serves as the superclass of all other primitives. Subclasses add their own content, typically (but not necessarily) keeping their content within the box's rectangle.

Box provides a number of utility functions available to all primitives.

See https://github.com/rivo/tview/wiki/Box for an example.

func NewBox

func NewBox() *Box

NewBox returns a Box without a border.

func (*Box) Blur

func (b *Box) Blur()

Blur is called when this primitive loses focus.

func (*Box) Draw

func (b *Box) Draw(screen tcell.Screen)

Draw draws this primitive onto the screen.

func (*Box) DrawForSubclass

func (b *Box) DrawForSubclass(screen tcell.Screen, p Primitive)

DrawForSubclass draws this box under the assumption that primitive p is a subclass of this box. This is needed e.g. to draw proper box frames which depend on the subclass's focus.

Only call this function from your own custom primitives. It is not needed in applications that have no custom primitives.

func (*Box) Focus

func (b *Box) Focus(delegate func(p Primitive))

Focus is called when this primitive receives focus.

func (*Box) GetBackgroundColor

func (b *Box) GetBackgroundColor() tcell.Color

GetBackgroundColor returns the box's background color.

func (*Box) GetBorderAttributes

func (b *Box) GetBorderAttributes() tcell.AttrMask

GetBorderAttributes returns the border's style attributes.

func (*Box) GetBorderColor

func (b *Box) GetBorderColor() tcell.Color

GetBorderColor returns the box's border color.

func (*Box) GetDrawFunc

func (b *Box) GetDrawFunc() func(screen tcell.Screen, x, y, width, height int) (int, int, int, int)

GetDrawFunc returns the callback function which was installed with SetDrawFunc() or nil if no such function has been installed.

func (*Box) GetInnerRect

func (b *Box) GetInnerRect() (int, int, int, int)

GetInnerRect returns the position of the inner rectangle (x, y, width, height), without the border and without any padding. Width and height values will clamp to 0 and thus never be negative.

func (*Box) GetInputCapture

func (b *Box) GetInputCapture() func(event *tcell.EventKey) *tcell.EventKey

GetInputCapture returns the function installed with SetInputCapture() or nil if no such function has been installed.

func (*Box) GetMouseCapture

func (b *Box) GetMouseCapture() func(action MouseAction, event *tcell.EventMouse) (MouseAction, *tcell.EventMouse)

GetMouseCapture returns the function installed with SetMouseCapture() or nil if no such function has been installed.

func (*Box) GetRect

func (b *Box) GetRect() (int, int, int, int)

GetRect returns the current position of the rectangle, x, y, width, and height.

func (*Box) GetTitle

func (b *Box) GetTitle() string

GetTitle returns the box's current title.

func (*Box) HasFocus

func (b *Box) HasFocus() bool

HasFocus returns whether or not this primitive has focus.

func (*Box) InInnerRect

func (b *Box) InInnerRect(x, y int) bool

InInnerRect returns true if the given coordinate is within the bounds of the box's inner rectangle (within the border and padding).

func (*Box) InRect

func (b *Box) InRect(x, y int) bool

InRect returns true if the given coordinate is within the bounds of the box's rectangle.

func (*Box) InputHandler

func (b *Box) InputHandler() func(event *tcell.EventKey, setFocus func(p Primitive))

InputHandler returns nil. Box has no default input handling.

func (*Box) MouseHandler

func (b *Box) MouseHandler() func(action MouseAction, event *tcell.EventMouse, setFocus func(p Primitive)) (consumed bool, capture Primitive)

MouseHandler returns nil. Box has no default mouse handling.

func (*Box) PasteHandler

func (b *Box) PasteHandler() func(pastedText string, setFocus func(p Primitive))

PasteHandler returns nil. Box has no default paste handling.

func (*Box) SetBackgroundColor

func (b *Box) SetBackgroundColor(color tcell.Color) *Box

SetBackgroundColor sets the box's background color.

func (*Box) SetBlurFunc

func (b *Box) SetBlurFunc(callback func()) *Box

SetBlurFunc sets a callback function which is invoked when this primitive loses focus. This does not apply to container primitives such as Flex or Grid.

Set to nil to remove the callback function.

func (*Box) SetBorder

func (b *Box) SetBorder(show bool) *Box

SetBorder sets the flag indicating whether or not the box should have a border.

func (*Box) SetBorderAttributes

func (b *Box) SetBorderAttributes(attr tcell.AttrMask) *Box

SetBorderAttributes sets the border's style attributes. You can combine different attributes using bitmask operations:

box.SetBorderAttributes(tcell.AttrUnderline | tcell.AttrBold)

func (*Box) SetBorderColor

func (b *Box) SetBorderColor(color tcell.Color) *Box

SetBorderColor sets the box's border color.

func (*Box) SetBorderPadding

func (b *Box) SetBorderPadding(top, bottom, left, right int) *Box

SetBorderPadding sets the size of the borders around the box content.

func (*Box) SetBorderStyle

func (b *Box) SetBorderStyle(style tcell.Style) *Box

SetBorderStyle sets the box's border style.

func (*Box) SetDrawFunc

func (b *Box) SetDrawFunc(handler func(screen tcell.Screen, x, y, width, height int) (int, int, int, int)) *Box

SetDrawFunc sets a callback function which is invoked after the box primitive has been drawn. This allows you to add a more individual style to the box (and all primitives which extend it).

The function is provided with the box's dimensions (set via SetRect()). It must return the box's inner dimensions (x, y, width, height) which will be returned by GetInnerRect(), used by descendent primitives to draw their own content.

func (*Box) SetFocusFunc

func (b *Box) SetFocusFunc(callback func()) *Box

SetFocusFunc sets a callback function which is invoked when this primitive receives focus. Container primitives such as Flex or Grid may not be notified if one of their descendents receive focus directly.

Set to nil to remove the callback function.

func (*Box) SetInputCapture

func (b *Box) SetInputCapture(capture func(event *tcell.EventKey) *tcell.EventKey) *Box

SetInputCapture installs a function which captures key events before they are forwarded to the primitive's default key event handler. This function can then choose to forward that key event (or a different one) to the default handler by returning it. If nil is returned, the default handler will not be called.

Providing a nil handler will remove a previously existing handler.

This function can also be used on container primitives (like Flex, Grid, or Form) as keyboard events will be handed down until they are handled.

Pasted key events are not forwarded to the input capture function if pasting is enabled (see Application.EnablePaste).

func (*Box) SetMouseCapture

func (b *Box) SetMouseCapture(capture func(action MouseAction, event *tcell.EventMouse) (MouseAction, *tcell.EventMouse)) *Box

SetMouseCapture sets a function which captures mouse events (consisting of the original tcell mouse event and the semantic mouse action) before they are forwarded to the primitive's default mouse event handler. This function can then choose to forward that event (or a different one) by returning it or returning a nil mouse event, in which case the default handler will not be called.

Providing a nil handler will remove a previously existing handler.

Note that mouse events are ignored completely if the application has not been enabled for mouse events (see Application.EnableMouse), which is the default.

func (*Box) SetRect

func (b *Box) SetRect(x, y, width, height int)

SetRect sets a new position of the primitive. Note that this has no effect if this primitive is part of a layout (e.g. Flex, Grid) or if it was added like this:

application.SetRoot(p, true)

func (*Box) SetTitle

func (b *Box) SetTitle(title string) *Box

SetTitle sets the box's title.

func (*Box) SetTitleAlign

func (b *Box) SetTitleAlign(align int) *Box

SetTitleAlign sets the alignment of the title, one of AlignLeft, AlignCenter, or AlignRight.

func (*Box) SetTitleColor

func (b *Box) SetTitleColor(color tcell.Color) *Box

SetTitleColor sets the box's title color.

func (*Box) WrapInputHandler

func (b *Box) WrapInputHandler(inputHandler func(*tcell.EventKey, func(p Primitive))) func(*tcell.EventKey, func(p Primitive))

WrapInputHandler wraps an input handler (see Box.InputHandler) with the functionality to capture input (see Box.SetInputCapture) before passing it on to the provided (default) input handler.

This is only meant to be used by subclassing primitives.

func (*Box) WrapMouseHandler

func (b *Box) WrapMouseHandler(mouseHandler func(MouseAction, *tcell.EventMouse, func(p Primitive)) (bool, Primitive)) func(action MouseAction, event *tcell.EventMouse, setFocus func(p Primitive)) (consumed bool, capture Primitive)

WrapMouseHandler wraps a mouse event handler (see Box.MouseHandler) with the functionality to capture mouse events (see Box.SetMouseCapture) before passing them on to the provided (default) event handler.

This is only meant to be used by subclassing primitives.

func (*Box) WrapPasteHandler

func (b *Box) WrapPasteHandler(pasteHandler func(string, func(p Primitive))) func(string, func(p Primitive))

WrapPasteHandler wraps a paste handler (see Box.PasteHandler).

type Button

type Button struct {
	*Box
	// contains filtered or unexported fields
}

Button is labeled box that triggers an action when selected.

See https://github.com/rivo/tview/wiki/Button for an example.

func NewButton

func NewButton(label string) *Button

NewButton returns a new input field.

func (*Button) Draw

func (b *Button) Draw(screen tcell.Screen)

Draw draws this primitive onto the screen.

func (*Button) GetLabel

func (b *Button) GetLabel() string

GetLabel returns the button text.

func (*Button) InputHandler

func (b *Button) InputHandler() func(event *tcell.EventKey, setFocus func(p Primitive))

InputHandler returns the handler for this primitive.

func (*Button) IsDisabled

func (b *Button) IsDisabled() bool

IsDisabled returns whether or not the button is disabled.

func (*Button) MouseHandler

func (b *Button) MouseHandler() func(action MouseAction, event *tcell.EventMouse, setFocus func(p Primitive)) (consumed bool, capture Primitive)

MouseHandler returns the mouse handler for this primitive.

func (*Button) SetActivatedStyle

func (b *Button) SetActivatedStyle(style tcell.Style) *Button

SetActivatedStyle sets the style of the button used when it is focused.

func (*Button) SetBackgroundColorActivated

func (b *Button) SetBackgroundColorActivated(color tcell.Color) *Button

SetBackgroundColorActivated sets the background color of the button text when the button is in focus.

func (*Button) SetDisabled

func (b *Button) SetDisabled(disabled bool) *Button

SetDisabled sets whether or not the button is disabled. Disabled buttons cannot be activated.

If the button is part of a form, you should set focus to the form itself after calling this function to set focus to the next non-disabled form item.

func (*Button) SetDisabledStyle

func (b *Button) SetDisabledStyle(style tcell.Style) *Button

SetDisabledStyle sets the style of the button used when it is disabled.

func (*Button) SetExitFunc

func (b *Button) SetExitFunc(handler func(key tcell.Key)) *Button

SetExitFunc sets a handler which is called when the user leaves the button. The callback function is provided with the key that was pressed, which is one of the following:

  • KeyEscape: Leaving the button with no specific direction.
  • KeyTab: Move to the next field.
  • KeyBacktab: Move to the previous field.

func (*Button) SetLabel

func (b *Button) SetLabel(label string) *Button

SetLabel sets the button text.

func (*Button) SetLabelColor

func (b *Button) SetLabelColor(color tcell.Color) *Button

SetLabelColor sets the color of the button text.

func (*Button) SetLabelColorActivated

func (b *Button) SetLabelColorActivated(color tcell.Color) *Button

SetLabelColorActivated sets the color of the button text when the button is in focus.

func (*Button) SetSelectedFunc

func (b *Button) SetSelectedFunc(handler func()) *Button

SetSelectedFunc sets a handler which is called when the button was selected.

func (*Button) SetStyle

func (b *Button) SetStyle(style tcell.Style) *Button

SetStyle sets the style of the button used when it is not focused.

type Checkbox

type Checkbox struct {
	*Box
	// contains filtered or unexported fields
}

Checkbox implements a simple box for boolean values which can be checked and unchecked.

See https://github.com/rivo/tview/wiki/Checkbox for an example.

func NewCheckbox

func NewCheckbox() *Checkbox

NewCheckbox returns a new input field.

func (*Checkbox) Draw

func (c *Checkbox) Draw(screen tcell.Screen)

Draw draws this primitive onto the screen.

func (*Checkbox) Focus

func (c *Checkbox) Focus(delegate func(p Primitive))

Focus is called when this primitive receives focus.

func (*Checkbox) GetFieldHeight

func (c *Checkbox) GetFieldHeight() int

GetFieldHeight returns this primitive's field height.

func (*Checkbox) GetFieldWidth

func (c *Checkbox) GetFieldWidth() int

GetFieldWidth returns this primitive's field width.

func (*Checkbox) GetLabel

func (c *Checkbox) GetLabel() string

GetLabel returns the text to be displayed before the input area.

func (*Checkbox) InputHandler

func (c *Checkbox) InputHandler() func(event *tcell.EventKey, setFocus func(p Primitive))

InputHandler returns the handler for this primitive.

func (*Checkbox) IsChecked

func (c *Checkbox) IsChecked() bool

IsChecked returns whether or not the box is checked.

func (*Checkbox) MouseHandler

func (c *Checkbox) MouseHandler() func(action MouseAction, event *tcell.EventMouse, setFocus func(p Primitive)) (consumed bool, capture Primitive)

MouseHandler returns the mouse handler for this primitive.

func (*Checkbox) SetActivatedStyle

func (c *Checkbox) SetActivatedStyle(style tcell.Style) *Checkbox

SetActivatedStyle sets the style of the checkbox when it is currently focused.

func (*Checkbox) SetChangedFunc

func (c *Checkbox) SetChangedFunc(handler func(checked bool)) *Checkbox

SetChangedFunc sets a handler which is called when the checked state of this checkbox was changed. The handler function receives the new state.

func (*Checkbox) SetChecked

func (c *Checkbox) SetChecked(checked bool) *Checkbox

SetChecked sets the state of the checkbox. This also triggers the "changed" callback if the state changes with this call.

func (*Checkbox) SetCheckedString

func (c *Checkbox) SetCheckedString(checked string) *Checkbox

SetCheckedString sets the string to be displayed when the checkbox is checked (defaults to "X"). The string may contain color tags (consider adapting the checkbox's various styles accordingly). See Escape in case you want to display square brackets.

func (*Checkbox) SetCheckedStyle

func (c *Checkbox) SetCheckedStyle(style tcell.Style) *Checkbox

SetCheckedStyle sets the style of the checked checkbox.

func (*Checkbox) SetDisabled

func (c *Checkbox) SetDisabled(disabled bool) FormItem

SetDisabled sets whether or not the item is disabled / read-only.

func (*Checkbox) SetDoneFunc

func (c *Checkbox) SetDoneFunc(handler func(key tcell.Key)) *Checkbox

SetDoneFunc sets a handler which is called when the user is done using the checkbox. The callback function is provided with the key that was pressed, which is one of the following:

  • KeyEscape: Abort text input.
  • KeyTab: Move to the next field.
  • KeyBacktab: Move to the previous field.

func (*Checkbox) SetFieldBackgroundColor

func (c *Checkbox) SetFieldBackgroundColor(color tcell.Color) *Checkbox

SetFieldBackgroundColor sets the background color of the input area.

func (*Checkbox) SetFieldTextColor

func (c *Checkbox) SetFieldTextColor(color tcell.Color) *Checkbox

SetFieldTextColor sets the text color of the input area.

func (*Checkbox) SetFinishedFunc

func (c *Checkbox) SetFinishedFunc(handler func(key tcell.Key)) FormItem

SetFinishedFunc sets a callback invoked when the user leaves this form item.

func (*Checkbox) SetFormAttributes

func (c *Checkbox) SetFormAttributes(labelWidth int, labelColor, bgColor, fieldTextColor, fieldBgColor tcell.Color) FormItem

SetFormAttributes sets attributes shared by all form items.

func (*Checkbox) SetLabel

func (c *Checkbox) SetLabel(label string) *Checkbox

SetLabel sets the text to be displayed before the input area.

func (*Checkbox) SetLabelColor

func (c *Checkbox) SetLabelColor(color tcell.Color) *Checkbox

SetLabelColor sets the color of the label.

func (*Checkbox) SetLabelStyle

func (c *Checkbox) SetLabelStyle(style tcell.Style) *Checkbox

SetLabelStyle sets the style of the label.

func (*Checkbox) SetLabelWidth

func (c *Checkbox) SetLabelWidth(width int) *Checkbox

SetLabelWidth sets the screen width of the label. A value of 0 will cause the primitive to use the width of the label string.

func (*Checkbox) SetUncheckedString

func (c *Checkbox) SetUncheckedString(unchecked string) *Checkbox

SetUncheckedString sets the string to be displayed when the checkbox is not checked (defaults to the empty space " "). The string may contain color tags (consider adapting the checkbox's various styles accordingly). See Escape in case you want to display square brackets.

func (*Checkbox) SetUncheckedStyle

func (c *Checkbox) SetUncheckedStyle(style tcell.Style) *Checkbox

SetUncheckedStyle sets the style of the unchecked checkbox.

type DropDown struct {
	*Box
	// contains filtered or unexported fields
}

DropDown implements a selection widget whose options become visible in a drop-down list when activated.

See https://github.com/rivo/tview/wiki/DropDown for an example.

func NewDropDown

func NewDropDown() *DropDown

NewDropDown returns a new drop-down.

func (d *DropDown) AddOption(text string, selected func()) *DropDown

AddOption adds a new selectable option to this drop-down. The "selected" callback is called when this option was selected. It may be nil.

func (d *DropDown) Draw(screen tcell.Screen)

Draw draws this primitive onto the screen.

func (d *DropDown) Focus(delegate func(p Primitive))

Focus is called by the application when the primitive receives focus.

func (d *DropDown) GetCurrentOption() (int, string)

GetCurrentOption returns the index of the currently selected option as well as its text. If no option was selected, -1 and an empty string is returned.

func (d *DropDown) GetFieldHeight() int

GetFieldHeight returns this primitive's field height.

func (d *DropDown) GetFieldWidth() int

GetFieldWidth returns this primitive's field screen width.

func (d *DropDown) GetLabel() string

GetLabel returns the text to be displayed before the input area.

func (d *DropDown) GetOptionCount() int

GetOptionCount returns the number of options in the drop-down.

func (d *DropDown) HasFocus() bool

HasFocus returns whether or not this primitive has focus.

func (d *DropDown) InputHandler() func(event *tcell.EventKey, setFocus func(p Primitive))

InputHandler returns the handler for this primitive.

func (d *DropDown) IsOpen() bool

IsOpen returns true if the drop-down list is currently open.

func (d *DropDown) MouseHandler() func(action MouseAction, event *tcell.EventMouse, setFocus func(p Primitive)) (consumed bool, capture Primitive)

MouseHandler returns the mouse handler for this primitive.

func (d *DropDown) RemoveOption(index int) *DropDown

RemoveOption removes the specified option from the drop-down. Panics if the index is out of range. If the currently selected option is removed, no option will be selected.

func (d *DropDown) SetCurrentOption(index int) *DropDown

SetCurrentOption sets the index of the currently selected option. This may be a negative value to indicate that no option is currently selected. Calling this function will also trigger the "selected" callback (if there is one).

func (d *DropDown) SetDisabled(disabled bool) FormItem

SetDisabled sets whether or not the item is disabled / read-only.

func (d *DropDown) SetDoneFunc(handler func(key tcell.Key)) *DropDown

SetDoneFunc sets a handler which is called when the user is done selecting options. The callback function is provided with the key that was pressed, which is one of the following:

  • KeyEscape: Abort selection.
  • KeyTab: Move to the next field.
  • KeyBacktab: Move to the previous field.
func (d *DropDown) SetFieldBackgroundColor(color tcell.Color) *DropDown

SetFieldBackgroundColor sets the background color of the options area.

func (d *DropDown) SetFieldTextColor(color tcell.Color) *DropDown

SetFieldTextColor sets the text color of the options area.

func (d *DropDown) SetFieldWidth(width int) *DropDown

SetFieldWidth sets the screen width of the options area. A value of 0 means extend to as long as the longest option text.

func (d *DropDown) SetFinishedFunc(handler func(key tcell.Key)) FormItem

SetFinishedFunc sets a callback invoked when the user leaves this form item.

func (d *DropDown) SetFormAttributes(labelWidth int, labelColor, bgColor, fieldTextColor, fieldBgColor tcell.Color) FormItem

SetFormAttributes sets attributes shared by all form items.

func (d *DropDown) SetLabel(label string) *DropDown

SetLabel sets the text to be displayed before the input area.

func (d *DropDown) SetLabelColor(color tcell.Color) *DropDown

SetLabelColor sets the color of the label.

func (d *DropDown) SetLabelWidth(width int) *DropDown

SetLabelWidth sets the screen width of the label. A value of 0 will cause the primitive to use the width of the label string.

func (d *DropDown) SetListStyles(unselected, selected tcell.Style) *DropDown

SetListStyles sets the styles of the items in the drop-down list (unselected as well as selected items). Style attributes are currently ignored but may be used in the future.

func (d *DropDown) SetOptions(texts []string, selected func(text string, index int)) *DropDown

SetOptions replaces all current options with the ones provided and installs one callback function which is called when one of the options is selected. It will be called with the option's text and its index into the options slice. The "selected" parameter may be nil.

func (d *DropDown) SetPrefixTextColor(color tcell.Color) *DropDown

SetPrefixTextColor sets the color of the prefix string. The prefix string is shown when the user starts typing text, which directly selects the first option that starts with the typed string.

func (d *DropDown) SetSelectedFunc(handler func(text string, index int)) *DropDown

SetSelectedFunc sets a handler which is called when the user changes the drop-down's option. This handler will be called in addition and prior to an option's optional individual handler. The handler is provided with the selected option's text and index. If "no option" was selected, these values are an empty string and -1.

func (d *DropDown) SetTextOptions(prefix, suffix, currentPrefix, currentSuffix, noSelection string) *DropDown

SetTextOptions sets the text to be placed before and after each drop-down option (prefix/suffix), the text placed before and after the currently selected option (currentPrefix/currentSuffix) as well as the text to be displayed when no option is currently selected. Per default, all of these strings are empty.

type Flex

type Flex struct {
	*Box
	// contains filtered or unexported fields
}

Flex is a basic implementation of the Flexbox layout. The contained primitives are arranged horizontally or vertically. The way they are distributed along that dimension depends on their layout settings, which is either a fixed length or a proportional length. See AddItem() for details.

See https://github.com/rivo/tview/wiki/Flex for an example.

func NewFlex

func NewFlex() *Flex

NewFlex returns a new flexbox layout container with no primitives and its direction set to FlexColumn. To add primitives to this layout, see AddItem(). To change the direction, see SetDirection().

Note that Box, the superclass of Flex, will not clear its contents so that any nil flex items will leave their background unchanged. To clear a Flex's background before any items are drawn, set it to a box with the desired color:

flex.Box = NewBox()

func (*Flex) AddItem

func (f *Flex) AddItem(item Primitive, fixedSize, proportion int, focus bool) *Flex

AddItem adds a new item to the container. The "fixedSize" argument is a width or height that may not be changed by the layout algorithm. A value of 0 means that its size is flexible and may be changed. The "proportion" argument defines the relative size of the item compared to other flexible-size items. For example, items with a proportion of 2 will be twice as large as items with a proportion of 1. The proportion must be at least 1 if fixedSize == 0 (ignored otherwise).

If "focus" is set to true, the item will receive focus when the Flex primitive receives focus. If multiple items have the "focus" flag set to true, the first one will receive focus.

You can provide a nil value for the primitive. This will still consume screen space but nothing will be drawn.

func (*Flex) Clear

func (f *Flex) Clear() *Flex

Clear removes all items from the container.

func (*Flex) Draw

func (f *Flex) Draw(screen tcell.Screen)

Draw draws this primitive onto the screen.

func (*Flex) Focus

func (f *Flex) Focus(delegate func(p Primitive))

Focus is called when this primitive receives focus.

func (*Flex) GetItem

func (f *Flex) GetItem(index int) Primitive

GetItem returns the primitive at the given index, starting with 0 for the first primitive in this container.

This function will panic for out of range indices.

func (*Flex) GetItemCount

func (f *Flex) GetItemCount() int

GetItemCount returns the number of items in this container.

func (*Flex) HasFocus

func (f *Flex) HasFocus() bool

HasFocus returns whether or not this primitive has focus.

func (*Flex) InputHandler

func (f *Flex) InputHandler() func(event *tcell.EventKey, setFocus func(p Primitive))

InputHandler returns the handler for this primitive.

func (*Flex) MouseHandler

func (f *Flex) MouseHandler() func(action MouseAction, event *tcell.EventMouse, setFocus func(p Primitive)) (consumed bool, capture Primitive)

MouseHandler returns the mouse handler for this primitive.

func (*Flex) PasteHandler

func (f *Flex) PasteHandler() func(pastedText string, setFocus func(p Primitive))

PasteHandler returns the handler for this primitive.

func (*Flex) RemoveItem

func (f *Flex) RemoveItem(p Primitive) *Flex

RemoveItem removes all items for the given primitive from the container, keeping the order of the remaining items intact.

func (*Flex) ResizeItem

func (f *Flex) ResizeItem(p Primitive, fixedSize, proportion int) *Flex

ResizeItem sets a new size for the item(s) with the given primitive. If there are multiple Flex items with the same primitive, they will all receive the same size. For details regarding the size parameters, see AddItem().

func (*Flex) SetDirection

func (f *Flex) SetDirection(direction int) *Flex

SetDirection sets the direction in which the contained primitives are distributed. This can be either FlexColumn (default) or FlexRow. Note that these are the opposite of what you would expect coming from CSS. You may also use FlexColumnCSS or FlexRowCSS, to remain in line with the CSS definition.

func (*Flex) SetFullScreen

func (f *Flex) SetFullScreen(fullScreen bool) *Flex

SetFullScreen sets the flag which, when true, causes the flex layout to use the entire screen space instead of whatever size it is currently assigned to.

type Form

type Form struct {
	*Box
	// contains filtered or unexported fields
}

Form allows you to combine multiple one-line form elements into a vertical or horizontal layout. Form elements include types such as InputField or Checkbox. These elements can be optionally followed by one or more buttons for which you can define form-wide actions (e.g. Save, Clear, Cancel).

See https://github.com/rivo/tview/wiki/Form for an example.

func NewForm

func NewForm() *Form

NewForm returns a new form.

func (*Form) AddButton

func (f *Form) AddButton(label string, selected func()) *Form

AddButton adds a new button to the form. The "selected" function is called when the user selects this button. It may be nil.

func (*Form) AddCheckbox

func (f *Form) AddCheckbox(label string, checked bool, changed func(checked bool)) *Form

AddCheckbox adds a checkbox to the form. It has a label, an initial state, and an (optional) callback function which is invoked when the state of the checkbox was changed by the user.

func (*Form) AddDropDown

func (f *Form) AddDropDown(label string, options []string, initialOption int, selected func(option string, optionIndex int)) *Form

AddDropDown adds a drop-down element to the form. It has a label, options, and an (optional) callback function which is invoked when an option was selected. The initial option may be a negative value to indicate that no option is currently selected.

func (*Form) AddFormItem

func (f *Form) AddFormItem(item FormItem) *Form

AddFormItem adds a new item to the form. This can be used to add your own objects to the form. Note, however, that the Form class will override some of its attributes to make it work in the form context. Specifically, these are:

  • The label width
  • The label color
  • The background color
  • The field text color
  • The field background color

func (*Form) AddImage

func (f *Form) AddImage(label string, image image.Image, width, height, colors int) *Form

AddImage adds an image to the form. It has a label and the image will fit in the specified width and height (its aspect ratio is preserved). See Image.SetColors for a description of the "colors" parameter. Images are not interactive and are skipped over in a form. The "width" value may be 0 (adjust dynamically) but "height" should generally be a positive value.

func (*Form) AddInputField

func (f *Form) AddInputField(label, value string, fieldWidth int, accept func(textToCheck string, lastChar rune) bool, changed func(text string)) *Form

AddInputField adds an input field to the form. It has a label, an optional initial value, a field width (a value of 0 extends it as far as possible), an optional accept function to validate the item's value (set to nil to accept any text), and an (optional) callback function which is invoked when the input field's text has changed.

func (*Form) AddPasswordField

func (f *Form) AddPasswordField(label, value string, fieldWidth int, mask rune, changed func(text string)) *Form

AddPasswordField adds a password field to the form. This is similar to an input field except that the user's input not shown. Instead, a "mask" character is displayed. The password field has a label, an optional initial value, a field width (a value of 0 extends it as far as possible), and an (optional) callback function which is invoked when the input field's text has changed.

func (*Form) AddTextArea

func (f *Form) AddTextArea(label, text string, fieldWidth, fieldHeight, maxLength int, changed func(text string)) *Form

AddTextArea adds a text area to the form. It has a label, an optional initial text, a size (width and height) referring to the actual input area (a fieldWidth of 0 extends it as far right as possible, a fieldHeight of 0 will cause it to be DefaultFormFieldHeight), and a maximum number of bytes of text allowed (0 means no limit).

The optional callback function is invoked when the content of the text area has changed. Note that especially for larger texts, this is an expensive operation due to technical constraints of the TextArea primitive (every key stroke leads to a new reallocation of the entire text).

func (*Form) AddTextView

func (f *Form) AddTextView(label, text string, fieldWidth, fieldHeight int, dynamicColors, scrollable bool) *Form

AddTextView adds a text view to the form. It has a label and text, a size (width and height) referring to the actual text element (a fieldWidth of 0 extends it as far right as possible, a fieldHeight of 0 will cause it to be DefaultFormFieldHeight), a flag to turn on/off dynamic colors, and a flag to turn on/off scrolling. If scrolling is turned off, the text view will not receive focus.

func (*Form) Clear

func (f *Form) Clear(includeButtons bool) *Form

Clear removes all input elements from the form, including the buttons if specified.

func (*Form) ClearButtons

func (f *Form) ClearButtons() *Form

ClearButtons removes all buttons from the form.

func (*Form) Draw

func (f *Form) Draw(screen tcell.Screen)

Draw draws this primitive onto the screen.

func (*Form) Focus

func (f *Form) Focus(delegate func(p Primitive))

Focus is called by the application when the primitive receives focus.

func (*Form) GetButton

func (f *Form) GetButton(index int) *Button

GetButton returns the button at the specified 0-based index. Note that buttons have been specially prepared for this form and modifying some of their attributes may have unintended side effects.

func (*Form) GetButtonCount

func (f *Form) GetButtonCount() int

GetButtonCount returns the number of buttons in this form.

func (*Form) GetButtonIndex

func (f *Form) GetButtonIndex(label string) int

GetButtonIndex returns the index of the button with the given label, starting with 0 for the button that was added first. If no such label was found, -1 is returned.

func (*Form) GetFocusedItemIndex

func (f *Form) GetFocusedItemIndex() (formItem, button int)

GetFocusedItemIndex returns the indices of the form element or button which currently has focus. If they don't, -1 is returned respectively.

func (*Form) GetFormItem

func (f *Form) GetFormItem(index int) FormItem

GetFormItem returns the form item at the given position, starting with index 0. Elements are referenced in the order they were added. Buttons are not included.

func (*Form) GetFormItemByLabel

func (f *Form) GetFormItemByLabel(label string) FormItem

GetFormItemByLabel returns the first form element with the given label. If no such element is found, nil is returned. Buttons are not searched and will therefore not be returned.

func (*Form) GetFormItemCount

func (f *Form) GetFormItemCount() int

GetFormItemCount returns the number of items in the form (not including the buttons).

func (*Form) GetFormItemIndex

func (f *Form) GetFormItemIndex(label string) int

GetFormItemIndex returns the index of the first form element with the given label. If no such element is found, -1 is returned. Buttons are not searched and will therefore not be returned.

func (*Form) HasFocus

func (f *Form) HasFocus() bool

HasFocus returns whether or not this primitive has focus.

func (*Form) InputHandler

func (f *Form) InputHandler() func(event *tcell.EventKey, setFocus func(p Primitive))

InputHandler returns the handler for this primitive.

func (*Form) MouseHandler

func (f *Form) MouseHandler() func(action MouseAction, event *tcell.EventMouse, setFocus func(p Primitive)) (consumed bool, capture Primitive)

MouseHandler returns the mouse handler for this primitive.

func (*Form) PasteHandler

func (f *Form) PasteHandler() func(pastedText string, setFocus func(p Primitive))

PasteHandler returns the handler for this primitive.

func (*Form) RemoveButton

func (f *Form) RemoveButton(index int) *Form

RemoveButton removes the button at the specified position, starting with 0 for the button that was added first.

func (*Form) RemoveFormItem

func (f *Form) RemoveFormItem(index int) *Form

RemoveFormItem removes the form element at the given position, starting with index 0. Elements are referenced in the order they were added. Buttons are not included.

func (*Form) SetButtonActivatedStyle

func (f *Form) SetButtonActivatedStyle(style tcell.Style) *Form

SetButtonActivatedStyle sets the style of the buttons when they are focused.

func (*Form) SetButtonBackgroundColor

func (f *Form) SetButtonBackgroundColor(color tcell.Color) *Form

SetButtonBackgroundColor sets the background color of the buttons. This is also the text color of the buttons when they are focused.

func (*Form) SetButtonDisabledStyle

func (f *Form) SetButtonDisabledStyle(style tcell.Style) *Form

SetButtonDisabledStyle sets the style of the buttons when they are disabled.

func (*Form) SetButtonStyle

func (f *Form) SetButtonStyle(style tcell.Style) *Form

SetButtonStyle sets the style of the buttons when they are not focused.

func (*Form) SetButtonTextColor

func (f *Form) SetButtonTextColor(color tcell.Color) *Form

SetButtonTextColor sets the color of the button texts. This is also the background of the buttons when they are focused.

func (*Form) SetButtonsAlign

func (f *Form) SetButtonsAlign(align int) *Form

SetButtonsAlign sets how the buttons align horizontally, one of AlignLeft (the default), AlignCenter, and AlignRight. This is only

func (*Form) SetCancelFunc

func (f *Form) SetCancelFunc(callback func()) *Form

SetCancelFunc sets a handler which is called when the user hits the Escape key.

func (*Form) SetFieldBackgroundColor

func (f *Form) SetFieldBackgroundColor(color tcell.Color) *Form

SetFieldBackgroundColor sets the background color of the input areas.

func (*Form) SetFieldTextColor

func (f *Form) SetFieldTextColor(color tcell.Color) *Form

SetFieldTextColor sets the text color of the input areas.

func (*Form) SetFocus

func (f *Form) SetFocus(index int) *Form

SetFocus shifts the focus to the form element with the given index, counting non-button items first and buttons last. Note that this index is only used when the form itself receives focus.

func (*Form) SetHorizontal

func (f *Form) SetHorizontal(horizontal bool) *Form

SetHorizontal sets the direction the form elements are laid out. If set to true, instead of positioning them from top to bottom (the default), they are positioned from left to right, moving into the next row if there is not enough space.

func (*Form) SetItemPadding

func (f *Form) SetItemPadding(padding int) *Form

SetItemPadding sets the number of empty rows between form items for vertical layouts and the number of empty cells between form items for horizontal layouts.

func (*Form) SetLabelColor

func (f *Form) SetLabelColor(color tcell.Color) *Form

SetLabelColor sets the color of the labels.

type FormItem

type FormItem interface {
	Primitive

	// GetLabel returns the item's label text.
	GetLabel() string

	// SetFormAttributes sets a number of item attributes at once.
	SetFormAttributes(labelWidth int, labelColor, bgColor, fieldTextColor, fieldBgColor tcell.Color) FormItem

	// GetFieldWidth returns the width of the form item's field (the area which
	// is manipulated by the user) in number of screen cells. A value of 0
	// indicates the field width is flexible and may use as much space as
	// required.
	GetFieldWidth() int

	// GetFieldHeight returns the height of the form item's field (the area which
	// is manipulated by the user). This value must be greater than 0.
	GetFieldHeight() int

	// SetFinishedFunc sets the handler function for when the user finished
	// entering data into the item. The handler may receive events for the
	// Enter key (we're done), the Escape key (cancel input), the Tab key (move
	// to next field), the Backtab key (move to previous field), or a negative
	// value, indicating that the action for the last known key should be
	// repeated.
	SetFinishedFunc(handler func(key tcell.Key)) FormItem

	// SetDisabled sets whether or not the item is disabled / read-only. A form
	// must have at least one item that is not disabled.
	SetDisabled(disabled bool) FormItem
}

FormItem is the interface all form items must implement to be able to be included in a form.

type Frame

type Frame struct {
	*Box
	// contains filtered or unexported fields
}

Frame is a wrapper which adds space around another primitive. In addition, the top area (header) and the bottom area (footer) may also contain text.

See https://github.com/rivo/tview/wiki/Frame for an example.

func NewFrame

func NewFrame(primitive Primitive) *Frame

NewFrame returns a new frame around the given primitive. The primitive's size will be changed to fit within this frame. The primitive may be nil, in which case no other primitive is embedded in the frame.

func (*Frame) AddText

func (f *Frame) AddText(text string, header bool, align int, color tcell.Color) *Frame

AddText adds text to the frame. Set "header" to true if the text is to appear in the header, above the contained primitive. Set it to false for it to appear in the footer, below the contained primitive. "align" must be one of the Align constants. Rows in the header are printed top to bottom, rows in the footer are printed bottom to top. Note that long text can overlap as different alignments will be placed on the same row.

func (*Frame) Clear

func (f *Frame) Clear() *Frame

Clear removes all text from the frame.

func (*Frame) Draw

func (f *Frame) Draw(screen tcell.Screen)

Draw draws this primitive onto the screen.

func (*Frame) Focus

func (f *Frame) Focus(delegate func(p Primitive))

Focus is called when this primitive receives focus.

func (*Frame) GetPrimitive

func (f *Frame) GetPrimitive() Primitive

GetPrimitive returns the primitive contained in this frame.

func (*Frame) HasFocus

func (f *Frame) HasFocus() bool

HasFocus returns whether or not this primitive has focus.

func (*Frame) InputHandler

func (f *Frame) InputHandler() func(event *tcell.EventKey, setFocus func(p Primitive))

InputHandler returns the handler for this primitive.

func (*Frame) MouseHandler

func (f *Frame) MouseHandler() func(action MouseAction, event *tcell.EventMouse, setFocus func(p Primitive)) (consumed bool, capture Primitive)

MouseHandler returns the mouse handler for this primitive.

func (*Frame) PasteHandler

func (f *Frame) PasteHandler() func(pastedText string, setFocus func(p Primitive))

PasteHandler returns the handler for this primitive.

func (*Frame) SetBorders

func (f *Frame) SetBorders(top, bottom, header, footer, left, right int) *Frame

SetBorders sets the width of the frame borders as well as "header" and "footer", the vertical space between the header and footer text and the contained primitive (does not apply if there is no text).

func (*Frame) SetPrimitive

func (f *Frame) SetPrimitive(p Primitive) *Frame

SetPrimitive replaces the contained primitive with the given one. To remove a primitive, set it to nil.

type Grid

type Grid struct {
	*Box
	// contains filtered or unexported fields
}

Grid is an implementation of a grid-based layout. It works by defining the size of the rows and columns, then placing primitives into the grid.

Some settings can lead to the grid exceeding its available space. SetOffset() can then be used to scroll in steps of rows and columns. These offset values can also be controlled with the arrow keys (or the "g","G", "j", "k", "h", and "l" keys) while the grid has focus and none of its contained primitives do.

See https://github.com/rivo/tview/wiki/Grid for an example.

func NewGrid

func NewGrid() *Grid

NewGrid returns a new grid-based layout container with no initial primitives.

Note that Box, the superclass of Grid, will be transparent so that any grid areas not covered by any primitives will leave their background unchanged. To clear a Grid's background before any items are drawn, reset its Box to one with the desired color:

grid.Box = NewBox()

func (*Grid) AddItem

func (g *Grid) AddItem(p Primitive, row, column, rowSpan, colSpan, minGridHeight, minGridWidth int, focus bool) *Grid

AddItem adds a primitive and its position to the grid. The top-left corner of the primitive will be located in the top-left corner of the grid cell at the given row and column and will span "rowSpan" rows and "colSpan" columns. For example, for a primitive to occupy rows 2, 3, and 4 and columns 5 and 6:

grid.AddItem(p, 2, 5, 3, 2, 0, 0, true)

If rowSpan or colSpan is 0, the primitive will not be drawn.

You can add the same primitive multiple times with different grid positions. The minGridWidth and minGridHeight values will then determine which of those positions will be used. This is similar to CSS media queries. These minimum values refer to the overall size of the grid. If multiple items for the same primitive apply, the one with the highest minimum value (width or height, whatever is higher) will be used, or the primitive added last if those values are the same. Example:

grid.AddItem(p, 0, 0, 0, 0, 0, 0, true). // Hide in small grids.
  AddItem(p, 0, 0, 1, 2, 100, 0, true).  // One-column layout for medium grids.
  AddItem(p, 1, 1, 3, 2, 300, 0, true)   // Multi-column layout for large grids.

To use the same grid layout for all sizes, simply set minGridWidth and minGridHeight to 0.

If the item's focus is set to true, it will receive focus when the grid receives focus. If there are multiple items with a true focus flag, the last visible one that was added will receive focus.

func (*Grid) Clear

func (g *Grid) Clear() *Grid

Clear removes all items from the grid.

func (*Grid) Draw

func (g *Grid) Draw(screen tcell.Screen)

Draw draws this primitive onto the screen.

func (*Grid) Focus

func (g *Grid) Focus(delegate func(p Primitive))

Focus is called when this primitive receives focus.

func (*Grid) GetOffset

func (g *Grid) GetOffset() (rows, columns int)

GetOffset returns the current row and column offset (see SetOffset() for details).

func (*Grid) HasFocus

func (g *Grid) HasFocus() bool

HasFocus returns whether or not this primitive has focus.

func (*Grid) InputHandler

func (g *Grid) InputHandler() func(event *tcell.EventKey, setFocus func(p Primitive))

InputHandler returns the handler for this primitive.

func (*Grid) MouseHandler

func (g *Grid) MouseHandler() func(action MouseAction, event *tcell.EventMouse, setFocus func(p Primitive)) (consumed bool, capture Primitive)

MouseHandler returns the mouse handler for this primitive.

func (*Grid) PasteHandler

func (g *Grid) PasteHandler() func(pastedText string, setFocus func(p Primitive))

PasteHandler returns the handler for this primitive.

func (*Grid) RemoveItem

func (g *Grid) RemoveItem(p Primitive) *Grid

RemoveItem removes all items for the given primitive from the grid, keeping the order of the remaining items intact.

func (*Grid) SetBorders

func (g *Grid) SetBorders(borders bool) *Grid

SetBorders sets whether or not borders are drawn around grid items. Setting this value to true will cause the gap values (see SetGap()) to be ignored and automatically assumed to be 1 where the border graphics are drawn.

func (*Grid) SetBordersColor

func (g *Grid) SetBordersColor(color tcell.Color) *Grid

SetBordersColor sets the color of the item borders.

func (*Grid) SetColumns

func (g *Grid) SetColumns(columns ...int) *Grid

SetColumns defines how the columns of the grid are distributed. Each value defines the size of one column, starting with the leftmost column. Values greater than 0 represent absolute column widths (gaps not included). Values less than or equal to 0 represent proportional column widths or fractions of the remaining free space, where 0 is treated the same as -1. That is, a column with a value of -3 will have three times the width of a column with a value of -1 (or 0). The minimum width set with SetMinSize() is always observed.

Primitives may extend beyond the columns defined explicitly with this function. A value of 0 is assumed for any undefined column. In fact, if you never call this function, all columns occupied by primitives will have the same width. On the other hand, unoccupied columns defined with this function will always take their place.

Assuming a total width of the grid of 100 cells and a minimum width of 0, the following call will result in columns with widths of 30, 10, 15, 15, and 30 cells:

grid.SetColumns(30, 10, -1, -1, -2)

If a primitive were then placed in the 6th and 7th column, the resulting widths would be: 30, 10, 10, 10, 20, 10, and 10 cells.

If you then called SetMinSize() as follows:

grid.SetMinSize(15, 20)

The resulting widths would be: 30, 15, 15, 15, 20, 15, and 15 cells, a total of 125 cells, 25 cells wider than the available grid width.

func (*Grid) SetGap

func (g *Grid) SetGap(row, column int) *Grid

SetGap sets the size of the gaps between neighboring primitives on the grid. If borders are drawn (see SetBorders()), these values are ignored and a gap of 1 is assumed. Panics if negative values are provided.

func (*Grid) SetMinSize

func (g *Grid) SetMinSize(row, column int) *Grid

SetMinSize sets an absolute minimum width for rows and an absolute minimum height for columns. Panics if negative values are provided.

func (*Grid) SetOffset

func (g *Grid) SetOffset(rows, columns int) *Grid

SetOffset sets the number of rows and columns which are skipped before drawing the first grid cell in the top-left corner. As the grid will never completely move off the screen, these values may be adjusted the next time the grid is drawn. The actual position of the grid may also be adjusted such that contained primitives that have focus remain visible.

func (*Grid) SetRows

func (g *Grid) SetRows(rows ...int) *Grid

SetRows defines how the rows of the grid are distributed. These values behave the same as the column values provided with Grid.SetColumns, see there for a definition and examples.

The provided values correspond to row heights, the first value defining the height of the topmost row.

func (*Grid) SetSize

func (g *Grid) SetSize(numRows, numColumns, rowSize, columnSize int) *Grid

SetSize is a shortcut for Grid.SetRows and Grid.SetColumns where all row and column values are set to the given size values. See Grid.SetColumns for details on sizes.

type Image

type Image struct {
	*Box
	// contains filtered or unexported fields
}

Image implements a widget that displays one image. The original image (specified with Image.SetImage) is resized according to the specified size (see Image.SetSize), using the specified number of colors (see Image.SetColors), while applying dithering if necessary (see Image.SetDithering).

Images are approximated by graphical characters in the terminal. The resolution is therefore limited by the number and type of characters that can be drawn in the terminal and the colors available in the terminal. The quality of the final image also depends on the terminal's font and spacing settings, none of which are under the control of this package. Results may vary.

func NewImage

func NewImage() *Image

NewImage returns a new image widget with an empty image (use Image.SetImage to specify the image to be displayed). The image will use the widget's entire available space. The dithering algorithm is set to Floyd-Steinberg dithering. The terminal's cell aspect ratio defaults to 0.5.

func (*Image) Draw

func (i *Image) Draw(screen tcell.Screen)

Draw draws this primitive onto the screen.

func (*Image) Focus

func (i *Image) Focus(delegate func(p Primitive))

Focus is called when this primitive receives focus.

func (*Image) GetColors

func (i *Image) GetColors() int

GetColors returns the number of colors that will be used while drawing the image. This is one of the values listed in Image.SetColors, except 0 which will be replaced by the actual number of colors used.

func (*Image) GetFieldHeight

func (i *Image) GetFieldHeight() int

GetFieldHeight returns this primitive's field height. This is the image's height or 8 if the height is 0 or less.

func (*Image) GetFieldWidth

func (i *Image) GetFieldWidth() int

GetFieldWidth returns this primitive's field width. This is the image's width or, if the width is 0 or less, the proportional width of the image based on its height as returned by Image.GetFieldHeight. If there is no image, 0 is returned.

func (*Image) GetLabel

func (i *Image) GetLabel() string

GetLabel returns the text to be displayed before the image.

func (*Image) GetLabelStyle

func (i *Image) GetLabelStyle() tcell.Style

GetLabelStyle returns the style of the label.

func (*Image) SetAlign

func (i *Image) SetAlign(vertical, horizontal int) *Image

SetAlign sets the vertical and horizontal alignment of the image within the widget's space. The possible values are AlignTop, AlignCenter, and AlignBottom for vertical alignment and AlignLeft, AlignCenter, and AlignRight for horizontal alignment. The default is AlignCenter for both (or AlignTop and AlignLeft if the image is part of a Form).

func (*Image) SetAspectRatio

func (i *Image) SetAspectRatio(aspectRatio float64) *Image

SetAspectRatio sets the width of a terminal's cell divided by its height. You may change the default of 0.5 if your terminal / font has a different aspect ratio. This is used to calculate the size of the image if the specified width or height is 0. The function will panic if the aspect ratio is 0 or less.

func (*Image) SetColors

func (i *Image) SetColors(colors int) *Image

SetColors sets the number of colors to use. This should be the number of colors supported by the terminal. If 0, the number of colors is chosen based on the TERM environment variable (which may or may not be reliable).

Only the values 0, 2, 8, 256, and 16777216 (TrueColor) are supported. Other values will be rounded up to the next supported value, to a maximum of 16777216.

The effect of using more colors than supported by the terminal is undefined.

func (*Image) SetDisabled

func (i *Image) SetDisabled(disabled bool) FormItem

SetDisabled sets whether or not the item is disabled / read-only.

func (*Image) SetDithering

func (i *Image) SetDithering(dithering int) *Image

SetDithering sets the dithering algorithm to use, one of the constants starting with "Dithering", for example DitheringFloydSteinberg (the default). Dithering is not applied when rendering in true-color.

func (*Image) SetFinishedFunc

func (i *Image) SetFinishedFunc(handler func(key tcell.Key)) FormItem

SetFinishedFunc sets a callback invoked when the user leaves this form item.

func (*Image) SetFormAttributes

func (i *Image) SetFormAttributes(labelWidth int, labelColor, bgColor, fieldTextColor, fieldBgColor tcell.Color) FormItem

SetFormAttributes sets attributes shared by all form items.

func (*Image) SetImage

func (i *Image) SetImage(image image.Image) *Image

SetImage sets the image to be displayed. If nil, the widget will be empty.

func (*Image) SetLabel

func (i *Image) SetLabel(label string) *Image

SetLabel sets the text to be displayed before the image.

func (*Image) SetLabelStyle

func (i *Image) SetLabelStyle(style tcell.Style) *Image

SetLabelStyle sets the style of the label.

func (*Image) SetLabelWidth

func (i *Image) SetLabelWidth(width int) *Image

SetLabelWidth sets the screen width of the label. A value of 0 will cause the primitive to use the width of the label string.

func (*Image) SetSize

func (i *Image) SetSize(rows, columns int) *Image

SetSize sets the size of the image. Positive values refer to cells in the terminal. Negative values refer to a percentage of the available space (e.g. -50 means 50%). A value of 0 means that the corresponding size is chosen automatically based on the other size while preserving the image's aspect ratio. If both are 0, the image uses as much space as possible while still preserving the aspect ratio.

type InputField

type InputField struct {
	*Box
	// contains filtered or unexported fields
}

InputField is a one-line box into which the user can enter text. Use InputField.SetAcceptanceFunc to accept or reject input, InputField.SetChangedFunc to listen for changes, and InputField.SetMaskCharacter to hide input from onlookers (e.g. for password input).

The input field also has an optional autocomplete feature. It is initialized by the InputField.SetAutocompleteFunc function. For more control over the autocomplete drop-down's behavior, you can also set the InputField.SetAutocompletedFunc.

Navigation and editing is the same as for a TextArea, with the following exceptions:

  • Tab, BackTab, Enter, Escape: Finish editing.

Note that while pressing Tab or Enter is intercepted by the input field, it is possible to paste such characters into the input field, possibly resulting in multi-line input. You can use InputField.SetAcceptanceFunc to prevent this.

If autocomplete functionality is configured:

  • Down arrow: Open the autocomplete drop-down.
  • Tab, Enter: Select the current autocomplete entry.

See https://github.com/rivo/tview/wiki/InputField for an example.

func NewInputField

func NewInputField() *InputField

NewInputField returns a new input field.

func (*InputField) Autocomplete

func (i *InputField) Autocomplete() *InputField

Autocomplete invokes the autocomplete callback (if there is one, see InputField.SetAutocompleteFunc). If the length of the returned autocomplete entries slice is greater than 0, the input field will present the user with a corresponding drop-down list the next time the input field is drawn.

It is safe to call this function from any goroutine. Note that the input field is not redrawn automatically unless called from the main goroutine (e.g. in response to events).

func (*InputField) Blur

func (i *InputField) Blur()

Blur is called when this primitive loses focus.

func (*InputField) Draw

func (i *InputField) Draw(screen tcell.Screen)

Draw draws this primitive onto the screen.

func (*InputField) Focus

func (i *InputField) Focus(delegate func(p Primitive))

Focus is called when this primitive receives focus.

func (*InputField) GetFieldHeight

func (i *InputField) GetFieldHeight() int

GetFieldHeight returns this primitive's field height.

func (*InputField) GetFieldStyle

func (i *InputField) GetFieldStyle() tcell.Style

GetFieldStyle returns the style of the input area (when no placeholder is shown).

func (*InputField) GetFieldWidth

func (i *InputField) GetFieldWidth() int

GetFieldWidth returns this primitive's field width.

func (*InputField) GetLabel

func (i *InputField) GetLabel() string

GetLabel returns the text to be displayed before the input area.

func (*InputField) GetLabelStyle

func (i *InputField) GetLabelStyle() tcell.Style

GetLabelStyle returns the style of the label.

func (*InputField) GetPlaceholderStyle

func (i *InputField) GetPlaceholderStyle() tcell.Style

GetPlaceholderStyle returns the style of the input area (when a placeholder is shown).

func (*InputField) GetText

func (i *InputField) GetText() string

GetText returns the current text of the input field.

func (*InputField) HasFocus

func (i *InputField) HasFocus() bool

HasFocus returns whether or not this primitive has focus.

func (*InputField) InputHandler

func (i *InputField) InputHandler() func(event *tcell.EventKey, setFocus func(p Primitive))

InputHandler returns the handler for this primitive.

func (*InputField) MouseHandler

func (i *InputField) MouseHandler() func(action MouseAction, event *tcell.EventMouse, setFocus func(p Primitive)) (consumed bool, capture Primitive)

MouseHandler returns the mouse handler for this primitive.

func (*InputField) PasteHandler

func (i *InputField) PasteHandler() func(pastedText string, setFocus func(p Primitive))

PasteHandler returns the handler for this primitive.

func (*InputField) SetAcceptanceFunc

func (i *InputField) SetAcceptanceFunc(handler func(textToCheck string, lastChar rune) bool) *InputField

SetAcceptanceFunc sets a handler which may reject the last character that was entered, by returning false. The handler receives the text as it would be after the change and the last character entered. If the handler is nil, all input is accepted. The function is only called when a single rune is inserted at the current cursor position.

This package defines a number of variables prefixed with InputField which may be used for common input (e.g. numbers, maximum text length). See for example InputFieldInteger.

When text is pasted, lastChar is 0.

func (*InputField) SetAutocompleteFunc

func (i *InputField) SetAutocompleteFunc(callback func(currentText string) (entries []string)) *InputField

SetAutocompleteFunc sets an autocomplete callback function which may return strings to be selected from a drop-down based on the current text of the input field. The drop-down appears only if len(entries) > 0. The callback is invoked in this function and whenever the current text changes or when InputField.Autocomplete is called. Entries are cleared when the user selects an entry or presses Escape.

func (*InputField) SetAutocompleteStyles

func (i *InputField) SetAutocompleteStyles(background tcell.Color, main, selected tcell.Style) *InputField

SetAutocompleteStyles sets the colors and style of the autocomplete entries. For details, see List.SetMainTextStyle, List.SetSelectedStyle, and Box.SetBackgroundColor.

func (*InputField) SetAutocompletedFunc

func (i *InputField) SetAutocompletedFunc(autocompleted func(text string, index int, source int) bool) *InputField

SetAutocompletedFunc sets a callback function which is invoked when the user selects an entry from the autocomplete drop-down list. The function is passed the text of the selected entry (stripped of any style tags), the index of the entry, and the user action that caused the selection, for example AutocompletedNavigate. It returns true if the autocomplete drop-down should be closed after the callback returns or false if it should remain open, in which case InputField.Autocomplete is called to update the drop-down's contents.

If no such callback is set (or nil is provided), the input field will be updated with the selection any time the user navigates the autocomplete drop-down list. So this function essentially gives you more control over the autocomplete functionality.

func (*InputField) SetChangedFunc

func (i *InputField) SetChangedFunc(handler func(text string)) *InputField

SetChangedFunc sets a handler which is called whenever the text of the input field has changed. It receives the current text (after the change).

func (*InputField) SetDisabled

func (i *InputField) SetDisabled(disabled bool) FormItem

SetDisabled sets whether or not the item is disabled / read-only.

func (*InputField) SetDoneFunc

func (i *InputField) SetDoneFunc(handler func(key tcell.Key)) *InputField

SetDoneFunc sets a handler which is called when the user is done entering text. The callback function is provided with the key that was pressed, which is one of the following:

  • KeyEnter: Done entering text.
  • KeyEscape: Abort text input.
  • KeyTab: Move to the next field.
  • KeyBacktab: Move to the previous field.

func (*InputField) SetFieldBackgroundColor

func (i *InputField) SetFieldBackgroundColor(color tcell.Color) *InputField

SetFieldBackgroundColor sets the background color of the input area.

func (*InputField) SetFieldStyle

func (i *InputField) SetFieldStyle(style tcell.Style) *InputField

SetFieldStyle sets the style of the input area (when no placeholder is shown).

func (*InputField) SetFieldTextColor

func (i *InputField) SetFieldTextColor(color tcell.Color) *InputField

SetFieldTextColor sets the text color of the input area.

func (*InputField) SetFieldWidth

func (i *InputField) SetFieldWidth(width int) *InputField

SetFieldWidth sets the screen width of the input area. A value of 0 means extend as much as possible.

func (*InputField) SetFinishedFunc

func (i *InputField) SetFinishedFunc(handler func(key tcell.Key)) FormItem

SetFinishedFunc sets a callback invoked when the user leaves this form item.

func (*InputField) SetFormAttributes

func (i *InputField) SetFormAttributes(labelWidth int, labelColor, bgColor, fieldTextColor, fieldBgColor tcell.Color) FormItem

SetFormAttributes sets attributes shared by all form items.

func (*InputField) SetLabel

func (i *InputField) SetLabel(label string) *InputField

SetLabel sets the text to be displayed before the input area.

func (*InputField) SetLabelColor

func (i *InputField) SetLabelColor(color tcell.Color) *InputField

SetLabelColor sets the text color of the label.

func (*InputField) SetLabelStyle

func (i *InputField) SetLabelStyle(style tcell.Style) *InputField

SetLabelStyle sets the style of the label.

func (*InputField) SetLabelWidth

func (i *InputField) SetLabelWidth(width int) *InputField

SetLabelWidth sets the screen width of the label. A value of 0 will cause the primitive to use the width of the label string.

func (*InputField) SetMaskCharacter

func (i *InputField) SetMaskCharacter(mask rune) *InputField

SetMaskCharacter sets a character that masks user input on a screen. A value of 0 disables masking.

func (*InputField) SetPlaceholder

func (i *InputField) SetPlaceholder(text string) *InputField

SetPlaceholder sets the text to be displayed when the input text is empty.

func (*InputField) SetPlaceholderStyle

func (i *InputField) SetPlaceholderStyle(style tcell.Style) *InputField

SetPlaceholderStyle sets the style of the input area (when a placeholder is shown).

func (*InputField) SetPlaceholderTextColor

func (i *InputField) SetPlaceholderTextColor(color tcell.Color) *InputField

SetPlaceholderTextColor sets the text color of placeholder text.

func (*InputField) SetText

func (i *InputField) SetText(text string) *InputField

SetText sets the current text of the input field. This can be undone by the user. Calling this function will also trigger a "changed" event.

type List

type List struct {
	*Box
	// contains filtered or unexported fields
}

List displays rows of items, each of which can be selected. List items can be shown as a single line or as two lines. They can be selected by pressing their assigned shortcut key, navigating to them and pressing Enter, or clicking on them with the mouse. The following key binds are available:

  • Down arrow / tab: Move down one item.
  • Up arrow / backtab: Move up one item.
  • Home: Move to the first item.
  • End: Move to the last item.
  • Page down: Move down one page.
  • Page up: Move up one page.
  • Enter / Space: Select the current item.
  • Right / left: Scroll horizontally. Only if the list is wider than the available space.

See List.SetChangedFunc for a way to be notified when the user navigates to a list item. See List.SetSelectedFunc for a way to be notified when a list item was selected.

See https://github.com/rivo/tview/wiki/List for an example.

func NewList

func NewList() *List

NewList returns a new list.

func (*List) AddItem

func (l *List) AddItem(mainText, secondaryText string, shortcut rune, selected func()) *List

AddItem calls InsertItem() with an index of -1.

func (*List) Clear

func (l *List) Clear() *List

Clear removes all items from the list.

func (*List) Draw

func (l *List) Draw(screen tcell.Screen)

Draw draws this primitive onto the screen.

func (*List) FindItems

func (l *List) FindItems(mainSearch, secondarySearch string, mustContainBoth, ignoreCase bool) (indices []int)

FindItems searches the main and secondary texts for the given strings and returns a list of item indices in which those strings are found. One of the two search strings may be empty, it will then be ignored. Indices are always returned in ascending order.

If mustContainBoth is set to true, mainSearch must be contained in the main text AND secondarySearch must be contained in the secondary text. If it is false, only one of the two search strings must be contained.

Set ignoreCase to true for case-insensitive search.

func (*List) GetCurrentItem

func (l *List) GetCurrentItem() int

GetCurrentItem returns the index of the currently selected list item, starting at 0 for the first item.

func (*List) GetItemCount

func (l *List) GetItemCount() int

GetItemCount returns the number of items in the list.

func (*List) GetItemText

func (l *List) GetItemText(index int) (main, secondary string)

GetItemText returns an item's texts (main and secondary). Panics if the index is out of range.

func (*List) GetOffset

func (l *List) GetOffset() (int, int)

GetOffset returns the number of items skipped while drawing, as well as the number of cells item text is moved to the left. See also SetOffset() for more information on these values.

func (*List) InputHandler

func (l *List) InputHandler() func(event *tcell.EventKey, setFocus func(p Primitive))

InputHandler returns the handler for this primitive.

func (*List) InsertItem

func (l *List) InsertItem(index int, mainText, secondaryText string, shortcut rune, selected func()) *List

InsertItem adds a new item to the list at the specified index. An index of 0 will insert the item at the beginning, an index of 1 before the second item, and so on. An index of GetItemCount() or higher will insert the item at the end of the list. Negative indices are also allowed: An index of -1 will insert the item at the end of the list, an index of -2 before the last item, and so on. An index of -GetItemCount()-1 or lower will insert the item at the beginning.

An item has a main text which will be highlighted when selected. It also has a secondary text which is shown underneath the main text (if it is set to visible) but which may remain empty.

The shortcut is a key binding. If the specified rune is entered, the item is selected immediately. Set to 0 for no binding.

The "selected" callback will be invoked when the user selects the item. You may provide nil if no such callback is needed or if all events are handled through the selected callback set with SetSelectedFunc().

The currently selected item will shift its position accordingly. If the list was previously empty, a "changed" event is fired because the new item becomes selected.

func (*List) MouseHandler

func (l *List) MouseHandler() func(action MouseAction, event *tcell.EventMouse, setFocus func(p Primitive)) (consumed bool, capture Primitive)

MouseHandler returns the mouse handler for this primitive.

func (*List) RemoveItem

func (l *List) RemoveItem(index int) *List

RemoveItem removes the item with the given index (starting at 0) from the list. If a negative index is provided, items are referred to from the back (-1 = last item, -2 = second-to-last item, and so on). Out of range indices are clamped to the beginning/end, i.e. unless the list is empty, an item is always removed.

The currently selected item is shifted accordingly. If it is the one that is removed, a "changed" event is fired, unless no items are left.

func (*List) SetChangedFunc

func (l *List) SetChangedFunc(handler func(index int, mainText string, secondaryText string, shortcut rune)) *List

SetChangedFunc sets the function which is called when the user navigates to a list item. The function receives the item's index in the list of items (starting with 0), its main text, secondary text, and its shortcut rune.

This function is also called when the first item is added or when SetCurrentItem() is called.

func (*List) SetCurrentItem

func (l *List) SetCurrentItem(index int) *List

SetCurrentItem sets the currently selected item by its index, starting at 0 for the first item. If a negative index is provided, items are referred to from the back (-1 = last item, -2 = second-to-last item, and so on). Out of range indices are clamped to the beginning/end.

Calling this function triggers a "changed" event if the selection changes.

func (*List) SetDoneFunc

func (l *List) SetDoneFunc(handler func()) *List

SetDoneFunc sets a function which is called when the user presses the Escape key.

func (*List) SetHighlightFullLine

func (l *List) SetHighlightFullLine(highlight bool) *List

SetHighlightFullLine sets a flag which determines whether the colored background of selected items spans the entire width of the view. If set to true, the highlight spans the entire view. If set to false, only the text of the selected item from beginning to end is highlighted.

func (*List) SetItemText

func (l *List) SetItemText(index int, main, secondary string) *List

SetItemText sets an item's main and secondary text. Panics if the index is out of range.

func (*List) SetMainTextColor

func (l *List) SetMainTextColor(color tcell.Color) *List

SetMainTextColor sets the color of the items' main text.

func (*List) SetMainTextStyle

func (l *List) SetMainTextStyle(style tcell.Style) *List

SetMainTextStyle sets the style of the items' main text. Note that the background color is ignored in order not to override the background color of the list itself.

func (*List) SetOffset

func (l *List) SetOffset(items, horizontal int) *List

SetOffset sets the number of items to be skipped (vertically) as well as the number of cells skipped horizontally when the list is drawn. Note that one item corresponds to two rows when there are secondary texts. Shortcuts are always drawn.

These values may change when the list is drawn to ensure the currently selected item is visible and item texts move out of view. Users can also modify these values by interacting with the list.

func (*List) SetSecondaryTextColor

func (l *List) SetSecondaryTextColor(color tcell.Color) *List

SetSecondaryTextColor sets the color of the items' secondary text.

func (*List) SetSecondaryTextStyle

func (l *List) SetSecondaryTextStyle(style tcell.Style) *List

SetSecondaryTextStyle sets the style of the items' secondary text. Note that the background color is ignored in order not to override the background color of the list itself.

func (*List) SetSelectedBackgroundColor

func (l *List) SetSelectedBackgroundColor(color tcell.Color) *List

SetSelectedBackgroundColor sets the background color of selected items.

func (*List) SetSelectedFocusOnly

func (l *List) SetSelectedFocusOnly(focusOnly bool) *List

SetSelectedFocusOnly sets a flag which determines when the currently selected list item is highlighted. If set to true, selected items are only highlighted when the list has focus. If set to false, they are always highlighted.

func (*List) SetSelectedFunc

func (l *List) SetSelectedFunc(handler func(int, string, string, rune)) *List

SetSelectedFunc sets the function which is called when the user selects a list item by pressing Enter on the current selection. The function receives the item's index in the list of items (starting with 0), its main text, secondary text, and its shortcut rune.

func (*List) SetSelectedStyle

func (l *List) SetSelectedStyle(style tcell.Style) *List

SetSelectedStyle sets the style of the selected items. Note that the color of main text characters that are different from the main text color (e.g. color tags) is maintained.

func (*List) SetSelectedTextColor

func (l *List) SetSelectedTextColor(color tcell.Color) *List

SetSelectedTextColor sets the text color of selected items. Note that the color of main text characters that are different from the main text color (e.g. style tags) is maintained.

func (*List) SetShortcutColor

func (l *List) SetShortcutColor(color tcell.Color) *List

SetShortcutColor sets the color of the items' shortcut.

func (*List) SetShortcutStyle

func (l *List) SetShortcutStyle(style tcell.Style) *List

SetShortcutStyle sets the style of the items' shortcut. Note that the background color is ignored in order not to override the background color of the list itself.

func (*List) SetWrapAround

func (l *List) SetWrapAround(wrapAround bool) *List

SetWrapAround sets the flag that determines whether navigating the list will wrap around. That is, navigating downwards on the last item will move the selection to the first item (similarly in the other direction). If set to false, the selection won't change when navigating downwards on the last item or navigating upwards on the first item.

func (*List) ShowSecondaryText

func (l *List) ShowSecondaryText(show bool) *List

ShowSecondaryText determines whether or not to show secondary item texts.

type Modal struct {
	*Box
	// contains filtered or unexported fields
}

Modal is a centered message window used to inform the user or prompt them for an immediate decision. It needs to have at least one button (added via Modal.AddButtons) or it will never disappear.

See https://github.com/rivo/tview/wiki/Modal for an example.

func NewModal

func NewModal() *Modal

NewModal returns a new modal message window.

func (*Modal) AddButtons

func (m *Modal) AddButtons(labels []string) *Modal

AddButtons adds buttons to the window. There must be at least one button and a "done" handler so the window can be closed again.

func (*Modal) ClearButtons

func (m *Modal) ClearButtons() *Modal

ClearButtons removes all buttons from the window.

func (*Modal) Draw

func (m *Modal) Draw(screen tcell.Screen)

Draw draws this primitive onto the screen.

func (*Modal) Focus

func (m *Modal) Focus(delegate func(p Primitive))

Focus is called when this primitive receives focus.

func (*Modal) HasFocus

func (m *Modal) HasFocus() bool

HasFocus returns whether or not this primitive has focus.

func (*Modal) InputHandler

func (m *Modal) InputHandler() func(event *tcell.EventKey, setFocus func(p Primitive))

InputHandler returns the handler for this primitive.

func (*Modal) MouseHandler

func (m *Modal) MouseHandler() func(action MouseAction, event *tcell.EventMouse, setFocus func(p Primitive)) (consumed bool, capture Primitive)

MouseHandler returns the mouse handler for this primitive.

func (*Modal) SetBackgroundColor

func (m *Modal) SetBackgroundColor(color tcell.Color) *Modal

SetBackgroundColor sets the color of the modal frame background.

func (*Modal) SetButtonActivatedStyle

func (m *Modal) SetButtonActivatedStyle(style tcell.Style) *Modal

SetButtonActivatedStyle sets the style of the buttons when they are focused.

func (*Modal) SetButtonBackgroundColor

func (m *Modal) SetButtonBackgroundColor(color tcell.Color) *Modal

SetButtonBackgroundColor sets the background color of the buttons.

func (*Modal) SetButtonStyle

func (m *Modal) SetButtonStyle(style tcell.Style) *Modal

SetButtonStyle sets the style of the buttons when they are not focused.

func (*Modal) SetButtonTextColor

func (m *Modal) SetButtonTextColor(color tcell.Color) *Modal

SetButtonTextColor sets the color of the button texts.

func (*Modal) SetDoneFunc

func (m *Modal) SetDoneFunc(handler func(buttonIndex int, buttonLabel string)) *Modal

SetDoneFunc sets a handler which is called when one of the buttons was pressed. It receives the index of the button as well as its label text. The handler is also called when the user presses the Escape key. The index will then be negative and the label text an empty string.

func (*Modal) SetFocus

func (m *Modal) SetFocus(index int) *Modal

SetFocus shifts the focus to the button with the given index.

func (*Modal) SetText

func (m *Modal) SetText(text string) *Modal

SetText sets the message text of the window. The text may contain line breaks but style tag states will not transfer to following lines. Note that words are wrapped, too, based on the final size of the window.

func (*Modal) SetTextColor

func (m *Modal) SetTextColor(color tcell.Color) *Modal

SetTextColor sets the color of the message text.

type MouseAction

type MouseAction int16

MouseAction indicates one of the actions the mouse is logically doing.

const (
	MouseMove MouseAction = iota
	MouseLeftDown
	MouseLeftUp
	MouseLeftClick
	MouseLeftDoubleClick
	MouseMiddleDown
	MouseMiddleUp
	MouseMiddleClick
	MouseMiddleDoubleClick
	MouseRightDown
	MouseRightUp
	MouseRightClick
	MouseRightDoubleClick
	MouseScrollUp
	MouseScrollDown
	MouseScrollLeft
	MouseScrollRight
)

Available mouse actions.

type Pages

type Pages struct {
	*Box
	// contains filtered or unexported fields
}

Pages is a container for other primitives laid out on top of each other, overlapping or not. It is often used as the application's root primitive. It allows to easily switch the visibility of the contained primitives.

See https://github.com/rivo/tview/wiki/Pages for an example.

func NewPages

func NewPages() *Pages

NewPages returns a new Pages object.

func (*Pages) AddAndSwitchToPage

func (p *Pages) AddAndSwitchToPage(name string, item Primitive, resize bool) *Pages

AddAndSwitchToPage calls AddPage(), then SwitchToPage() on that newly added page.

func (*Pages) AddPage

func (p *Pages) AddPage(name string, item Primitive, resize, visible bool) *Pages

AddPage adds a new page with the given name and primitive. If there was previously a page with the same name, it is overwritten. Leaving the name empty may cause conflicts in other functions so always specify a non-empty name.

Visible pages will be drawn in the order they were added (unless that order was changed in one of the other functions). If "resize" is set to true, the primitive will be set to the size available to the Pages primitive whenever the pages are drawn.

func (*Pages) Draw

func (p *Pages) Draw(screen tcell.Screen)

Draw draws this primitive onto the screen.

func (*Pages) Focus

func (p *Pages) Focus(delegate func(p Primitive))

Focus is called by the application when the primitive receives focus.

func (*Pages) GetFrontPage

func (p *Pages) GetFrontPage() (name string, item Primitive)

GetFrontPage returns the front-most visible page. If there are no visible pages, ("", nil) is returned.

func (*Pages) GetPageCount

func (p *Pages) GetPageCount() int

GetPageCount returns the number of pages currently stored in this object.

func (*Pages) HasFocus

func (p *Pages) HasFocus() bool

HasFocus returns whether or not this primitive has focus.

func (*Pages) HasPage

func (p *Pages) HasPage(name string) bool

HasPage returns true if a page with the given name exists in this object.

func (*Pages) HidePage

func (p *Pages) HidePage(name string) *Pages

HidePage sets a page's visibility to "false".

func (*Pages) InputHandler

func (p *Pages) InputHandler() func(event *tcell.EventKey, setFocus func(p Primitive))

InputHandler returns the handler for this primitive.

func (*Pages) MouseHandler

func (p *Pages) MouseHandler() func(action MouseAction, event *tcell.EventMouse, setFocus func(p Primitive)) (consumed bool, capture Primitive)

MouseHandler returns the mouse handler for this primitive.

func (*Pages) PasteHandler

func (p *Pages) PasteHandler() func(pastedText string, setFocus func(p Primitive))

PasteHandler returns the handler for this primitive.

func (*Pages) RemovePage

func (p *Pages) RemovePage(name string) *Pages

RemovePage removes the page with the given name. If that page was the only visible page, visibility is assigned to the last page.

func (*Pages) SendToBack

func (p *Pages) SendToBack(name string) *Pages

SendToBack changes the order of the pages such that the page with the given name comes first, causing it to be drawn first with the next update (if visible).

func (*Pages) SendToFront

func (p *Pages) SendToFront(name string) *Pages

SendToFront changes the order of the pages such that the page with the given name comes last, causing it to be drawn last with the next update (if visible).

func (*Pages) SetChangedFunc

func (p *Pages) SetChangedFunc(handler func()) *Pages

SetChangedFunc sets a handler which is called whenever the visibility or the order of any visible pages changes. This can be used to redraw the pages.

func (*Pages) ShowPage

func (p *Pages) ShowPage(name string) *Pages

ShowPage sets a page's visibility to "true" (in addition to any other pages which are already visible).

func (*Pages) SwitchToPage

func (p *Pages) SwitchToPage(name string) *Pages

SwitchToPage sets a page's visibility to "true" and all other pages' visibility to "false".

type Primitive

type Primitive interface {
	// Draw draws this primitive onto the screen. Implementers can call the
	// screen's ShowCursor() function but should only do so when they have focus.
	// (They will need to keep track of this themselves.)
	Draw(screen tcell.Screen)

	// GetRect returns the current position of the primitive, x, y, width, and
	// height.
	GetRect() (int, int, int, int)

	// SetRect sets a new position of the primitive.
	SetRect(x, y, width, height int)

	// InputHandler returns a handler which receives key events when it has focus.
	// It is called by the Application class.
	//
	// A value of nil may also be returned, in which case this primitive cannot
	// receive focus and will not process any key events.
	//
	// The handler will receive the key event and a function that allows it to
	// set the focus to a different primitive, so that future key events are sent
	// to that primitive.
	//
	// The Application's Draw() function will be called automatically after the
	// handler returns.
	//
	// The Box class provides functionality to intercept keyboard input. If you
	// subclass from Box, it is recommended that you wrap your handler using
	// Box.WrapInputHandler() so you inherit that functionality.
	InputHandler() func(event *tcell.EventKey, setFocus func(p Primitive))

	// Focus is called by the application when the primitive receives focus.
	// Implementers may call delegate() to pass the focus on to another primitive.
	Focus(delegate func(p Primitive))

	// HasFocus determines if the primitive has focus. This function must return
	// true also if one of this primitive's child elements has focus.
	HasFocus() bool

	// Blur is called by the application when the primitive loses focus.
	Blur()

	// MouseHandler returns a handler which receives mouse events.
	// It is called by the Application class.
	//
	// A value of nil may also be returned to stop the downward propagation of
	// mouse events.
	//
	// The Box class provides functionality to intercept mouse events. If you
	// subclass from Box, it is recommended that you wrap your handler using
	// Box.WrapMouseHandler() so you inherit that functionality.
	MouseHandler() func(action MouseAction, event *tcell.EventMouse, setFocus func(p Primitive)) (consumed bool, capture Primitive)

	// PasteHandler returns a handler which receives pasted text.
	// It is called by the Application class.
	//
	// A value of nil may also be returned to stop the downward propagation of
	// paste events.
	//
	// The Box class may provide functionality to intercept paste events in the
	// future. If you subclass from Box, it is recommended that you wrap your
	// handler using Box.WrapPasteHandler() so you inherit that functionality.
	PasteHandler() func(text string, setFocus func(p Primitive))
}

Primitive is the top-most interface for all graphical primitives.

type Table

type Table struct {
	*Box
	// contains filtered or unexported fields
}

Table visualizes two-dimensional data consisting of rows and columns. Each Table cell is defined via SetCell() by the TableCell type. They can be added dynamically to the table and changed any time.

The most compact display of a table is without borders. Each row will then occupy one row on screen and columns are separated by the rune defined via SetSeparator() (a space character by default).

When borders are turned on (via SetBorders()), each table cell is surrounded by lines. Therefore one table row will require two rows on screen.

Columns will use as much horizontal space as they need. You can constrain their size with the MaxWidth parameter of the TableCell type.

Fixed Columns

You can define fixed rows and rolumns via SetFixed(). They will always stay in their place, even when the table is scrolled. Fixed rows are always the top rows. Fixed columns are always the leftmost columns.

Selections

You can call SetSelectable() to set columns and/or rows to "selectable". If the flag is set only for columns, entire columns can be selected by the user. If it is set only for rows, entire rows can be selected. If both flags are set, individual cells can be selected. The "selected" handler set via SetSelectedFunc() is invoked when the user presses Enter on a selection.

Navigation

If the table extends beyond the available space, it can be navigated with key bindings similar to Vim:

  • h, left arrow: Move left by one column.
  • l, right arrow: Move right by one column.
  • j, down arrow: Move down by one row.
  • k, up arrow: Move up by one row.
  • g, home: Move to the top.
  • G, end: Move to the bottom.
  • Ctrl-F, page down: Move down by one page.
  • Ctrl-B, page up: Move up by one page.

When there is no selection, this affects the entire table (except for fixed rows and columns). When there is a selection, the user moves the selection. The class will attempt to keep the selection from moving out of the screen.

Use SetInputCapture() to override or modify keyboard input.

See https://github.com/rivo/tview/wiki/Table for an example.

func NewTable

func NewTable() *Table

NewTable returns a new table.

func (*Table) CellAt

func (t *Table) CellAt(x, y int) (row, column int)

CellAt returns the row and column located at the given screen coordinates. Each returned value may be negative if there is no row and/or cell. This function will also process coordinates outside the table's inner rectangle so callers will need to check for bounds themselves.

The layout of the table when it was last drawn is used so if anything has changed in the meantime, the results may not be reliable.

func (*Table) Clear

func (t *Table) Clear() *Table

Clear removes all table data.

func (*Table) Draw

func (t *Table) Draw(screen tcell.Screen)

Draw draws this primitive onto the screen.

func (*Table) GetCell

func (t *Table) GetCell(row, column int) *TableCell

GetCell returns the contents of the cell at the specified position. A valid TableCell object is always returned but it will be uninitialized if the cell was not previously set. Such an uninitialized object will not automatically be inserted. Therefore, repeated calls to this function may return different pointers for uninitialized cells.

func (*Table) GetColumnCount

func (t *Table) GetColumnCount() int

GetColumnCount returns the (maximum) number of columns in the table.

func (*Table) GetOffset

func (t *Table) GetOffset() (row, column int)

GetOffset returns the current row and column offset. This indicates how many rows and columns the table is scrolled down and to the right.

func (*Table) GetRowCount

func (t *Table) GetRowCount() int

GetRowCount returns the number of rows in the table.

func (*Table) GetSelectable

func (t *Table) GetSelectable() (rows, columns bool)

GetSelectable returns what can be selected in a table. Refer to SetSelectable() for details.

func (*Table) GetSelection

func (t *Table) GetSelection() (row, column int)

GetSelection returns the position of the current selection. If entire rows are selected, the column index is undefined. Likewise for entire columns.

func (*Table) InputHandler

func (t *Table) InputHandler() func(event *tcell.EventKey, setFocus func(p Primitive))

InputHandler returns the handler for this primitive.

func (*Table) InsertColumn

func (t *Table) InsertColumn(column int) *Table

InsertColumn inserts a column before the column with the given index. Cells in the given column and to its right will be shifted to the right by one column. Rows that have fewer initialized cells than "column" will remain unchanged.

func (*Table) InsertRow

func (t *Table) InsertRow(row int) *Table

InsertRow inserts a row before the row with the given index. Cells on the given row and below will be shifted to the bottom by one row. If "row" is equal or larger than the current number of rows, this function has no effect.

func (*Table) MouseHandler

func (t *Table) MouseHandler() func(action MouseAction, event *tcell.EventMouse, setFocus func(p Primitive)) (consumed bool, capture Primitive)

MouseHandler returns the mouse handler for this primitive.

func (*Table) RemoveColumn

func (t *Table) RemoveColumn(column int) *Table

RemoveColumn removes the column at the given position from the table. If there is no such column, this has no effect.

func (*Table) RemoveRow

func (t *Table) RemoveRow(row int) *Table

RemoveRow removes the row at the given position from the table. If there is no such row, this has no effect.

func (*Table) ScrollToBeginning

func (t *Table) ScrollToBeginning() *Table

ScrollToBeginning scrolls the table to the beginning to that the top left corner of the table is shown. Note that this position may be corrected if there is a selection.

func (*Table) ScrollToEnd

func (t *Table) ScrollToEnd() *Table

ScrollToEnd scrolls the table to the beginning to that the bottom left corner of the table is shown. Adding more rows to the table will cause it to automatically scroll with the new data. Note that this position may be corrected if there is a selection.

func (*Table) Select

func (t *Table) Select(row, column int) *Table

Select sets the selected cell. Depending on the selection settings specified via SetSelectable(), this may be an entire row or column, or even ignored completely. The "selection changed" event is fired if such a callback is available (even if the selection ends up being the same as before and even if cells are not selectable).

func (*Table) SetBorders

func (t *Table) SetBorders(show bool) *Table

SetBorders sets whether or not each cell in the table is surrounded by a border.

func (*Table) SetBordersColor

func (t *Table) SetBordersColor(color tcell.Color) *Table

SetBordersColor sets the color of the cell borders.

func (*Table) SetCell

func (t *Table) SetCell(row, column int, cell *TableCell) *Table

SetCell sets the content of a cell the specified position. It is ok to directly instantiate a TableCell object. If the cell has content, at least the Text and Color fields should be set.

Note that setting cells in previously unknown rows and columns will automatically extend the internal table representation with empty TableCell objects, e.g. starting with a row of 100,000 will immediately create 100,000 empty rows.

To avoid unnecessary garbage collection, fill columns from left to right.

func (*Table) SetCellSimple

func (t *Table) SetCellSimple(row, column int, text string) *Table

SetCellSimple calls SetCell() with the given text, left-aligned, in white.

func (*Table) SetContent

func (t *Table) SetContent(content TableContent) *Table

SetContent sets a new content type for this table. This allows you to back the table by a data structure of your own, for example one that cannot be fully held in memory. For details, see the TableContent interface documentation.

A value of nil will return the table to its default implementation where all of its table cells are kept in memory.

func (*Table) SetDoneFunc

func (t *Table) SetDoneFunc(handler func(key tcell.Key)) *Table

SetDoneFunc sets a handler which is called whenever the user presses the Escape, Tab, or Backtab key. If nothing is selected, it is also called when user presses the Enter key (because pressing Enter on a selection triggers the "selected" handler set via SetSelectedFunc()).

func (*Table) SetEvaluateAllRows

func (t *Table) SetEvaluateAllRows(all bool) *Table

SetEvaluateAllRows sets a flag which determines the rows to be evaluated when calculating the widths of the table's columns. When false, only visible rows are evaluated. When true, all rows in the table are evaluated.

Set this flag to true to avoid shifting column widths when the table is scrolled. (May come with a performance penalty for large tables.)

Use with caution on very large tables, especially those not backed by the default TableContent data structure.

func (*Table) SetFixed

func (t *Table) SetFixed(rows, columns int) *Table

SetFixed sets the number of fixed rows and columns which are always visible even when the rest of the cells are scrolled out of view. Rows are always the top-most ones. Columns are always the left-most ones.

func (*Table) SetOffset

func (t *Table) SetOffset(row, column int) *Table

SetOffset sets how many rows and columns should be skipped when drawing the table. This is useful for large tables that do not fit on the screen. Navigating a selection can change these values.

Fixed rows and columns are never skipped.

func (*Table) SetSelectable

func (t *Table) SetSelectable(rows, columns bool) *Table

SetSelectable sets the flags which determine what can be selected in a table. There are three selection modi:

  • rows = false, columns = false: Nothing can be selected.
  • rows = true, columns = false: Rows can be selected.
  • rows = false, columns = true: Columns can be selected.
  • rows = true, columns = true: Individual cells can be selected.

func (*Table) SetSelectedFunc

func (t *Table) SetSelectedFunc(handler func(row, column int)) *Table

SetSelectedFunc sets a handler which is called whenever the user presses the Enter key on a selected cell/row/column. The handler receives the position of the selection and its cell contents. If entire rows are selected, the column index is undefined. Likewise for entire columns.

func (*Table) SetSelectedStyle

func (t *Table) SetSelectedStyle(style tcell.Style) *Table

SetSelectedStyle sets a specific style for selected cells. If no such style is set, the cell's background and text color are swapped. If a cell defines its own selected style, that will be used instead.

To reset a previous setting to its default, make the following call:

table.SetSelectedStyle(tcell.StyleDefault)

func (*Table) SetSelectionChangedFunc

func (t *Table) SetSelectionChangedFunc(handler func(row, column int)) *Table

SetSelectionChangedFunc sets a handler which is called whenever the current selection changes. The handler receives the position of the new selection. If entire rows are selected, the column index is undefined. Likewise for entire columns.

func (*Table) SetSeparator

func (t *Table) SetSeparator(separator rune) *Table

SetSeparator sets the character used to fill the space between two neighboring cells. This is a space character ' ' per default but you may want to set it to Borders.Vertical (or any other rune) if the column separation should be more visible. If cell borders are activated, this is ignored.

Separators have the same color as borders.

func (*Table) SetWrapSelection

func (t *Table) SetWrapSelection(vertical, horizontal bool) *Table

SetWrapSelection determines whether a selection wraps vertically or horizontally when moved. Vertically wrapping selections will jump from the last selectable row to the first selectable row and vice versa. Horizontally wrapping selections will jump from the last selectable column to the first selectable column (on the next selectable row) or from the first selectable column to the last selectable column (on the previous selectable row). If set to false, the selection is not moved when it is already on the first/last selectable row/column.

The default is for both values to be false.

type TableCell

type TableCell struct {
	// The reference object.
	Reference interface{}

	// The text to be displayed in the table cell.
	Text string

	// The alignment of the cell text. One of AlignLeft (default), AlignCenter,
	// or AlignRight.
	Align int

	// The maximum width of the cell in screen space. This is used to give a
	// column a maximum width. Any cell text whose screen width exceeds this width
	// is cut off. Set to 0 if there is no maximum width.
	MaxWidth int

	// If the total table width is less than the available width, this value is
	// used to add extra width to a column. See SetExpansion() for details.
	Expansion int

	// The color of the cell text. You should not use this anymore, it is only
	// here for backwards compatibility. Use the Style field instead.
	Color tcell.Color

	// The background color of the cell. You should not use this anymore, it is
	// only here for backwards compatibility. Use the Style field instead.
	BackgroundColor tcell.Color

	// The style attributes of the cell. You should not use this anymore, it is
	// only here for backwards compatibility. Use the Style field instead.
	Attributes tcell.AttrMask

	// The style of the cell. If this is uninitialized (tcell.StyleDefault), the
	// Color and BackgroundColor fields are used instead.
	Style tcell.Style

	// The style of the cell when it is selected. If this is uninitialized
	// (tcell.StyleDefault), the table's selected style is used instead. If that
	// is uninitialized as well, the cell's background and text color are
	// swapped.
	SelectedStyle tcell.Style

	// If set to true, the BackgroundColor is not used and the cell will have
	// the background color of the table.
	Transparent bool

	// If set to true, this cell cannot be selected.
	NotSelectable bool

	// An optional handler for mouse clicks. This also fires if the cell is not
	// selectable. If true is returned, no additional "selected" event is fired
	// on selectable cells.
	Clicked func() bool
	// contains filtered or unexported fields
}

TableCell represents one cell inside a Table. You can instantiate this type directly but all colors (background and text) will be set to their default which is black.

func NewTableCell

func NewTableCell(text string) *TableCell

NewTableCell returns a new table cell with sensible defaults. That is, left aligned text with the primary text color (see Styles) and a transparent background (using the background of the Table).

func (*TableCell) GetLastPosition

func (c *TableCell) GetLastPosition() (x, y, width int)

GetLastPosition returns the position of the table cell the last time it was drawn on screen. If the cell is not on screen, the return values are undefined.

Because the Table class will attempt to keep selected cells on screen, this function is most useful in response to a "selected" event (see SetSelectedFunc()) or a "selectionChanged" event (see SetSelectionChangedFunc()).

func (*TableCell) GetReference

func (c *TableCell) GetReference() interface{}

GetReference returns this cell's reference object.

func (*TableCell) SetAlign

func (c *TableCell) SetAlign(align int) *TableCell

SetAlign sets the cell's text alignment, one of AlignLeft, AlignCenter, or AlignRight.

func (*TableCell) SetAttributes

func (c *TableCell) SetAttributes(attr tcell.AttrMask) *TableCell

SetAttributes sets the cell's text attributes. You can combine different attributes using bitmask operations:

cell.SetAttributes(tcell.AttrUnderline | tcell.AttrBold)

func (*TableCell) SetBackgroundColor

func (c *TableCell) SetBackgroundColor(color tcell.Color) *TableCell

SetBackgroundColor sets the cell's background color. This will also cause the cell's Transparent flag to be set to "false".

func (*TableCell) SetClickedFunc

func (c *TableCell) SetClickedFunc(clicked func() bool) *TableCell

SetClickedFunc sets a handler which fires when this cell is clicked. This is independent of whether the cell is selectable or not. But for selectable cells, if the function returns "true", the "selected" event is not fired.

func (*TableCell) SetExpansion

func (c *TableCell) SetExpansion(expansion int) *TableCell

SetExpansion sets the value by which the column of this cell expands if the available width for the table is more than the table width (prior to applying this expansion value). This is a proportional value. The amount of unused horizontal space is divided into widths to be added to each column. How much extra width a column receives depends on the expansion value: A value of 0 (the default) will not cause the column to increase in width. Other values are proportional, e.g. a value of 2 will cause a column to grow by twice the amount of a column with a value of 1.

Since this value affects an entire column, the maximum over all visible cells in that column is used.

This function panics if a negative value is provided.

func (*TableCell) SetMaxWidth

func (c *TableCell) SetMaxWidth(maxWidth int) *TableCell

SetMaxWidth sets maximum width of the cell in screen space. This is used to give a column a maximum width. Any cell text whose screen width exceeds this width is cut off. Set to 0 if there is no maximum width.

func (*TableCell) SetReference

func (c *TableCell) SetReference(reference interface{}) *TableCell

SetReference allows you to store a reference of any type in this cell. This will allow you to establish a mapping between the cell and your actual data.

func (*TableCell) SetSelectable

func (c *TableCell) SetSelectable(selectable bool) *TableCell

SetSelectable sets whether or not this cell can be selected by the user.

func (*TableCell) SetSelectedStyle

func (c *TableCell) SetSelectedStyle(style tcell.Style) *TableCell

SetSelectedStyle sets the cell's style when it is selected. If this is uninitialized (tcell.StyleDefault), the table's selected style is used instead. If that is uninitialized as well, the cell's background and text color are swapped.

func (*TableCell) SetStyle

func (c *TableCell) SetStyle(style tcell.Style) *TableCell

SetStyle sets the cell's style (foreground color, background color, and attributes) all at once.

func (*TableCell) SetText

func (c *TableCell) SetText(text string) *TableCell

SetText sets the cell's text.

func (*TableCell) SetTextColor

func (c *TableCell) SetTextColor(color tcell.Color) *TableCell

SetTextColor sets the cell's text color.

func (*TableCell) SetTransparency

func (c *TableCell) SetTransparency(transparent bool) *TableCell

SetTransparency sets the background transparency of this cell. A value of "true" will cause the cell to use the table's background color. A value of "false" will cause it to use its own background color.

type TableContent

type TableContent interface {
	// Return the cell at the given position or nil if there is no cell. The
	// row and column arguments start at 0 and end at what GetRowCount() and
	// GetColumnCount() return, minus 1.
	GetCell(row, column int) *TableCell

	// Return the total number of rows in the table.
	GetRowCount() int

	// Return the total number of columns in the table.
	GetColumnCount() int

	// Set the cell at the given position to the provided cell.
	SetCell(row, column int, cell *TableCell)

	// Remove the row at the given position by shifting all following rows up
	// by one. Out of range positions may be ignored.
	RemoveRow(row int)

	// Remove the column at the given position by shifting all following columns
	// left by one. Out of range positions may be ignored.
	RemoveColumn(column int)

	// Insert a new empty row at the given position by shifting all rows at that
	// position and below down by one. Implementers may decide what to do with
	// out of range positions.
	InsertRow(row int)

	// Insert a new empty column at the given position by shifting all columns
	// at that position and to the right by one to the right. Implementers may
	// decide what to do with out of range positions.
	InsertColumn(column int)

	// Remove all table data.
	Clear()
}

TableContent defines a Table's data. You may replace a Table's default implementation with your own using the Table.SetContent() function. This will allow you to turn Table into a view of your own data structure. The Table.Draw() function, which is called when the screen is updated, will then use the (read-only) functions of this interface to update the table. The write functions are only called when the corresponding functions of Table are called.

The interface's read-only functions are not called concurrently by the package (provided that users of the package don't call Table.Draw() in a separate goroutine, which would be uncommon and is not encouraged).

type TableContentReadOnly

type TableContentReadOnly struct{}

TableContentReadOnly is an empty struct which implements the write operations of the TableContent interface. None of the implemented functions do anything. You can embed this struct into your own structs to free yourself from having to implement the empty write functions of TableContent. See demos/table/virtualtable for an example.

func (TableContentReadOnly) Clear

func (t TableContentReadOnly) Clear()

Clear does not do anything.

func (TableContentReadOnly) InsertColumn

func (t TableContentReadOnly) InsertColumn(column int)

InsertColumn does not do anything.

func (TableContentReadOnly) InsertRow

func (t TableContentReadOnly) InsertRow(row int)

InsertRow does not do anything.

func (TableContentReadOnly) RemoveColumn

func (t TableContentReadOnly) RemoveColumn(column int)

RemoveColumn does not do anything.

func (TableContentReadOnly) RemoveRow

func (t TableContentReadOnly) RemoveRow(row int)

RemoveRow does not do anything.

func (TableContentReadOnly) SetCell

func (t TableContentReadOnly) SetCell(row, column int, cell *TableCell)

SetCell does not do anything.

type TextArea

type TextArea struct {
	*Box
	// contains filtered or unexported fields
}

TextArea implements a simple text editor for multi-line text. Multi-color text is not supported. Word-wrapping is enabled by default but can be turned off or be changed to character-wrapping.

At this point, a text area cannot be added to a Form. This will be added in the future.

Navigation and Editing

A text area is always in editing mode and no other mode exists. The following keys can be used to move the cursor (subject to what the user's terminal supports and how it is configured):

  • Left arrow: Move left.
  • Right arrow: Move right.
  • Down arrow: Move down.
  • Up arrow: Move up.
  • Ctrl-A, Home: Move to the beginning of the current line.
  • Ctrl-E, End: Move to the end of the current line.
  • Ctrl-F, page down: Move down by one page.
  • Ctrl-B, page up: Move up by one page.
  • Alt-Up arrow: Scroll the page up, leaving the cursor in its position.
  • Alt-Down arrow: Scroll the page down, leaving the cursor in its position.
  • Alt-Left arrow: Scroll the page to the left, leaving the cursor in its position. Ignored if wrapping is enabled.
  • Alt-Right arrow: Scroll the page to the right, leaving the cursor in its position. Ignored if wrapping is enabled.
  • Alt-B, Ctrl-Left arrow: Jump to the beginning of the current or previous word.
  • Alt-F, Ctrl-Right arrow: Jump to the end of the current or next word.

Words are defined according to Unicode Standard Annex #29. We skip any words that contain only spaces or punctuation.

Entering a character will insert it at the current cursor location. Subsequent characters are shifted accordingly. If the cursor is outside the visible area, any changes to the text will move it into the visible area. The following keys can also be used to modify the text:

  • Enter: Insert a newline character (see NewLine).
  • Tab: Insert a tab character (\t). It will be rendered like TabSize spaces. (This may eventually be changed to behave like regular tabs.)
  • Ctrl-H, Backspace: Delete one character to the left of the cursor.
  • Ctrl-D, Delete: Delete the character under the cursor (or the first character on the next line if the cursor is at the end of a line).
  • Alt-Backspace: Delete the word to the left of the cursor.
  • Ctrl-K: Delete everything under and to the right of the cursor until the next newline character.
  • Ctrl-W: Delete from the start of the current word to the left of the cursor.
  • Ctrl-U: Delete the current line, i.e. everything after the last newline character before the cursor up until the next newline character. This may span multiple visible rows if wrapping is enabled.

Text can be selected by moving the cursor while holding the Shift key, to the extent that this is supported by the user's terminal. The Ctrl-L key can be used to select the entire text. (Ctrl-A already binds to the "Home" key.)

When text is selected:

  • Entering a character will replace the selected text with the new character.
  • Backspace, delete, Ctrl-H, Ctrl-D: Delete the selected text.
  • Ctrl-Q: Copy the selected text into the clipboard, unselect the text.
  • Ctrl-X: Copy the selected text into the clipboard and delete it.
  • Ctrl-V: Replace the selected text with the clipboard text. If no text is selected, the clipboard text will be inserted at the cursor location.

The Ctrl-Q key was chosen for the "copy" function because the Ctrl-C key is the default key to stop the application. If your application frees up the global Ctrl-C key and you want to bind it to the "copy to clipboard" function, you may use Box.SetInputCapture to override the Ctrl-Q key to implement copying to the clipboard. Note that using your terminal's / operating system's key bindings for copy+paste functionality may not have the expected effect as tview will not be able to handle these keys. Pasting text using your operating system's or terminal's own methods may be very slow as each character will be pasted individually. However, some terminals support pasting text blocks which is supported by the text area, see Application.EnablePaste for details.

The default clipboard is an internal text buffer local to this text area instance, i.e. the operating system's clipboard is not used. If you want to implement your own clipboard (or make use of your operating system's clipboard), you can use TextArea.SetClipboard which provides all the functionality needed to implement your own clipboard.

The text area also supports Undo:

  • Ctrl-Z: Undo the last change.
  • Ctrl-Y: Redo the last Undo change.

Undo does not affect the clipboard.

If the mouse is enabled, the following actions are available:

  • Left click: Move the cursor to the clicked position or to the end of the line if past the last character.
  • Left double-click: Select the word under the cursor.
  • Left click while holding the Shift key: Select text.
  • Scroll wheel: Scroll the text.

func NewTextArea

func NewTextArea() *TextArea

NewTextArea returns a new text area. Use TextArea.SetText to set the initial text.

func (*TextArea) Draw

func (t *TextArea) Draw(screen tcell.Screen)

Draw draws this primitive onto the screen.

func (*TextArea) Focus

func (t *TextArea) Focus(delegate func(p Primitive))

Focus is called when this primitive receives focus.

func (*TextArea) GetClipboardText

func (t *TextArea) GetClipboardText() string

GetClipboardText returns the current text of the clipboard by calling the pasteFromClipboard function set with TextArea.SetClipboard.

func (*TextArea) GetCursor

func (t *TextArea) GetCursor() (fromRow, fromColumn, toRow, toColumn int)

GetCursor returns the current cursor position where the first character of the entire text is in row 0, column 0. If the user has selected text, the "from" values will refer to the beginning of the selection and the "to" values to the end of the selection (exclusive). They are the same if there is no selection.

func (*TextArea) GetDisabled

func (t *TextArea) GetDisabled() bool

GetDisabled returns whether or not the item is disabled / read-only.

func (*TextArea) GetFieldHeight

func (t *TextArea) GetFieldHeight() int

GetFieldHeight returns this primitive's field height.

func (*TextArea) GetFieldWidth

func (t *TextArea) GetFieldWidth() int

GetFieldWidth returns this primitive's field width.

func (*TextArea) GetLabel

func (t *TextArea) GetLabel() string

GetLabel returns the text to be displayed before the text area.

func (*TextArea) GetLabelStyle

func (t *TextArea) GetLabelStyle() tcell.Style

GetLabelStyle returns the style of the label.

func (*TextArea) GetLabelWidth

func (t *TextArea) GetLabelWidth() int

GetLabelWidth returns the screen width of the label.

func (*TextArea) GetOffset

func (t *TextArea) GetOffset() (row, column int)

GetOffset returns the text's offset, that is, the number of rows and columns skipped during drawing at the top or on the left, respectively. Note that the column offset is ignored if wrapping is enabled.

func (*TextArea) GetPlaceholderStyle

func (t *TextArea) GetPlaceholderStyle() tcell.Style

GetPlaceholderStyle returns the style of the placeholder text.

func (*TextArea) GetSelection

func (t *TextArea) GetSelection() (text string, start int, end int)

GetSelection returns the currently selected text and its start and end positions within the entire text as a half-open interval. If the returned text is an empty string, the start and end positions are the same and can be interpreted as the cursor position.

Calling this function will result in string allocations as well as a search for text positions. This is expensive if the text has been edited extensively already. Use TextArea.HasSelection first if you are only interested in selected text.

func (*TextArea) GetText

func (t *TextArea) GetText() string

GetText returns the entire text of the text area. Note that this will newly allocate the entire text.

func (*TextArea) GetTextLength

func (t *TextArea) GetTextLength() int

GetTextLength returns the string length of the text in the text area.

func (*TextArea) GetTextStyle

func (t *TextArea) GetTextStyle() tcell.Style

GetTextStyle returns the style of the text.

func (*TextArea) HasSelection

func (t *TextArea) HasSelection() bool

HasSelection returns whether the selected text is non-empty.

func (*TextArea) InputHandler

func (t *TextArea) InputHandler() func(event *tcell.EventKey, setFocus func(p Primitive))

InputHandler returns the handler for this primitive.

func (*TextArea) MouseHandler

func (t *TextArea) MouseHandler() func(action MouseAction, event *tcell.EventMouse, setFocus func(p Primitive)) (consumed bool, capture Primitive)

MouseHandler returns the mouse handler for this primitive.

func (*TextArea) PasteHandler

func (t *TextArea) PasteHandler() func(pastedText string, setFocus func(p Primitive))

PasteHandler returns the handler for this primitive.

func (*TextArea) Replace

func (t *TextArea) Replace(start, end int, text string) *TextArea

Replace replaces a section of the text with new text. The start and end positions refer to index positions within the entire text string (as a half-open interval). They may be the same, in which case text is inserted at the given position. If the text is an empty string, text between start and end is deleted. Index positions will be shifted to line up with character boundaries. A "changed" event will be triggered.

Previous selections are cleared. The cursor will be located at the end of the replaced text. Scroll offsets will not be changed. A "moved" event will be triggered.

The effects of this function can be undone (and redone) by the user.

func (*TextArea) Select

func (t *TextArea) Select(start, end int) *TextArea

Select selects a section of the text. The start and end positions refer to index positions within the entire text string (as a half-open interval). They may be the same, in which case the cursor is placed at the given position. Any previous selection is removed. Scroll offsets will be preserved.

Index positions will be shifted to line up with character boundaries.

func (*TextArea) SetChangedFunc

func (t *TextArea) SetChangedFunc(handler func()) *TextArea

SetChangedFunc sets a handler which is called whenever the text of the text area has changed.

func (*TextArea) SetClipboard

func (t *TextArea) SetClipboard(copyToClipboard func(string), pasteFromClipboard func() string) *TextArea

SetClipboard allows you to implement your own clipboard by providing a function that is called when the user wishes to store text in the clipboard (copyToClipboard) and a function that is called when the user wishes to retrieve text from the clipboard (pasteFromClipboard).

Providing nil values will cause the default clipboard implementation to be used. Note that the default clipboard is local to this text area instance. Copying text to other widgets will not work.

func (*TextArea) SetDisabled

func (t *TextArea) SetDisabled(disabled bool) FormItem

SetDisabled sets whether or not the item is disabled / read-only.

func (*TextArea) SetFinishedFunc

func (t *TextArea) SetFinishedFunc(handler func(key tcell.Key)) FormItem

SetFinishedFunc sets a callback invoked when the user leaves this form item.

func (*TextArea) SetFormAttributes

func (t *TextArea) SetFormAttributes(labelWidth int, labelColor, bgColor, fieldTextColor, fieldBgColor tcell.Color) FormItem

SetFormAttributes sets attributes shared by all form items.

func (*TextArea) SetLabel

func (t *TextArea) SetLabel(label string) *TextArea

SetLabel sets the text to be displayed before the text area.

func (*TextArea) SetLabelStyle

func (t *TextArea) SetLabelStyle(style tcell.Style) *TextArea

SetLabelStyle sets the style of the label.

func (*TextArea) SetLabelWidth

func (t *TextArea) SetLabelWidth(width int) *TextArea

SetLabelWidth sets the screen width of the label. A value of 0 will cause the primitive to use the width of the label string.

func (*TextArea) SetMaxLength

func (t *TextArea) SetMaxLength(maxLength int) *TextArea

SetMaxLength sets the maximum number of bytes allowed in the text area. A value of 0 means there is no limit. If the text area currently contains more bytes than this, it may violate this constraint.

func (*TextArea) SetMovedFunc

func (t *TextArea) SetMovedFunc(handler func()) *TextArea

SetMovedFunc sets a handler which is called whenever the cursor position or the text selection has changed.

func (*TextArea) SetOffset

func (t *TextArea) SetOffset(row, column int) *TextArea

SetOffset sets the text's offset, that is, the number of rows and columns skipped during drawing at the top or on the left, respectively. If wrapping is enabled, the column offset is ignored. These values may get adjusted automatically to ensure that some text is always visible.

func (*TextArea) SetPlaceholder

func (t *TextArea) SetPlaceholder(placeholder string) *TextArea

SetPlaceholder sets the text to be displayed when the text area is empty.

func (*TextArea) SetPlaceholderStyle

func (t *TextArea) SetPlaceholderStyle(style tcell.Style) *TextArea

SetPlaceholderStyle sets the style of the placeholder text.

func (*TextArea) SetSelectedStyle

func (t *TextArea) SetSelectedStyle(style tcell.Style) *TextArea

SetSelectedStyle sets the style of the selected text.

func (*TextArea) SetSize

func (t *TextArea) SetSize(rows, columns int) *TextArea

SetSize sets the screen size of the input element of the text area. The input element is always located next to the label which is always located in the top left corner. If any of the values are 0 or larger than the available space, the available space will be used.

func (*TextArea) SetText

func (t *TextArea) SetText(text string, cursorAtTheEnd bool) *TextArea

SetText sets the text of the text area. All existing text is deleted and replaced with the new text. Any edits are discarded, no undos are available. This function is typically only used to initialize the text area with a text after it has been created. To clear the text area's text (again, no undos), provide an empty string.

If cursorAtTheEnd is false, the cursor is placed at the start of the text. If it is true, it is placed at the end of the text. For very long texts, placing the cursor at the end can be an expensive operation because the entire text needs to be parsed and laid out.

If you want to set text and preserve undo functionality, use TextArea.Replace instead.

func (*TextArea) SetTextStyle

func (t *TextArea) SetTextStyle(style tcell.Style) *TextArea

SetTextStyle sets the style of the text.

func (*TextArea) SetWordWrap

func (t *TextArea) SetWordWrap(wrapOnWords bool) *TextArea

SetWordWrap sets the flag that causes lines that are longer than the available width to be wrapped onto the next line at spaces or after punctuation marks (according to Unicode Standard Annex #14). This flag is ignored if the flag set with TextArea.SetWrap is false. The text area's default is word-wrapping.

func (*TextArea) SetWrap

func (t *TextArea) SetWrap(wrap bool) *TextArea

SetWrap sets the flag that, if true, leads to lines that are longer than the available width being wrapped onto the next line. If false, any characters beyond the available width are not displayed.

type TextView

type TextView struct {
	sync.Mutex
	*Box
	// contains filtered or unexported fields
}

TextView is a component to display read-only text. While the text to be displayed can be changed or appended to, there is no functionality that allows the user to edit it. For that, TextArea should be used.

TextView implements the io.Writer interface so you can stream text to it, appending to the existing text. This does not trigger a redraw automatically but if a handler is installed via TextView.SetChangedFunc, you can cause it to be redrawn. (See TextView.SetChangedFunc for more details.)

Tab characters advance the text to the next tab stop at every TabSize screen columns, but only if the text is left-aligned. If the text is centered or right-aligned, tab characters are simply replaced with TabSize spaces.

Word wrapping is enabled by default. Use TextView.SetWrap and TextView.SetWordWrap to change this.

Navigation

If the text view is set to be scrollable (which is the default), text is kept in a buffer which may be larger than the screen and can be navigated with Vim-like key binds:

  • h, left arrow: Move left.
  • l, right arrow: Move right.
  • j, down arrow: Move down.
  • k, up arrow: Move up.
  • g, home: Move to the top.
  • G, end: Move to the bottom.
  • Ctrl-F, page down: Move down by one page.
  • Ctrl-B, page up: Move up by one page.

If the text is not scrollable, any text above the top visible line is discarded. This can be useful when you want to continuously stream text to the text view and only keep the latest lines.

Use Box.SetInputCapture to override or modify keyboard input.

Styles / Colors

If dynamic colors are enabled via TextView.SetDynamicColors, text style can be changed dynamically by embedding color strings in square brackets. This works the same way as anywhere else. See the package documentation for more information.

Regions and Highlights

If regions are enabled via TextView.SetRegions, you can define text regions within the text and assign region IDs to them. Text regions start with region tags. Region tags are square brackets that contain a region ID in double quotes, for example:

We define a ["rg"]region[""] here.

A text region ends with the next region tag. Tags with no region ID ([""]) don't start new regions. They can therefore be used to mark the end of a region. Region IDs must satisfy the following regular expression:

[a-zA-Z0-9_,;: \-\.]+

Regions can be highlighted by calling the TextView.Highlight function with one or more region IDs. This can be used to display search results, for example.

The TextView.ScrollToHighlight function can be used to jump to the currently highlighted region once when the text view is drawn the next time.

Large Texts

The text view can handle reasonably large texts. It will parse the text as needed. For optimal performance, it is best to access or display parts of the text very far down only if really needed. For example, call TextView.ScrollToBeginning before adding the text to the text view, to avoid scrolling the text all the way to the bottom, forcing a full-text parse.

For even larger texts or "infinite" streams of text such as log files, you should consider using TextView.SetMaxLines to limit the number of lines in the text view buffer. Or disable the text view's scrollability altogether (using TextView.SetScrollable). This will cause the text view to discard lines moving out of the visible area at the top.

See https://github.com/rivo/tview/wiki/TextView for an example.

func NewTextView

func NewTextView() *TextView

NewTextView returns a new text view.

func (*TextView) BatchWriter

func (t *TextView) BatchWriter() TextViewWriter

BatchWriter returns a new writer that can be used to write into the buffer but without Locking/Unlocking the buffer on every write, as TextView.Write and TextView.Clear do. The lock will be acquired once when BatchWriter is called, and will be released when the returned writer is closed. Example:

tv := tview.NewTextView()
w := tv.BatchWriter()
defer w.Close()
w.Clear()
fmt.Fprintln(w, "To sit in solemn silence")
fmt.Fprintln(w, "on a dull, dark, dock")
fmt.Println(tv.GetText(false))

Note that using the batch writer requires you to manage any issues that may arise from concurrency yourself. See package description for details on dealing with concurrency.

func (*TextView) Clear

func (t *TextView) Clear() *TextView

Clear removes all text from the buffer. This triggers the "changed" callback.

func (*TextView) Draw

func (t *TextView) Draw(screen tcell.Screen)

Draw draws this primitive onto the screen.

func (*TextView) Focus

func (t *TextView) Focus(delegate func(p Primitive))

Focus is called when this primitive receives focus.

func (*TextView) GetFieldHeight

func (t *TextView) GetFieldHeight() int

GetFieldHeight returns this primitive's field height.

func (*TextView) GetFieldWidth

func (t *TextView) GetFieldWidth() int

GetFieldWidth returns this primitive's field width.

func (*TextView) GetHighlights

func (t *TextView) GetHighlights() (regionIDs []string)

GetHighlights returns the IDs of all currently highlighted regions.

func (*TextView) GetLabel

func (t *TextView) GetLabel() string

GetLabel returns the text to be displayed before the text view.

func (*TextView) GetOriginalLineCount

func (t *TextView) GetOriginalLineCount() int

GetOriginalLineCount returns the number of lines in the original text buffer, without applying any wrapping. This is an expensive call as it needs to iterate over the entire text.

func (*TextView) GetRegionText

func (t *TextView) GetRegionText(regionID string) string

GetRegionText returns the text of the first region with the given ID. If dynamic colors are enabled, style tags are stripped from the text.

If the region does not exist or if regions are turned off, an empty string is returned.

This function can be expensive if the specified region is way beyond the visible area of the text view as the text needs to be parsed until the region can be found, or if the region does not contain any text.

func (*TextView) GetScrollOffset

func (t *TextView) GetScrollOffset() (row, column int)

GetScrollOffset returns the number of rows and columns that are skipped at the top left corner when the text view has been scrolled.

func (*TextView) GetText

func (t *TextView) GetText(stripAllTags bool) string

GetText returns the current text of this text view. If "stripAllTags" is set to true, any region/style tags are stripped from the text.

func (*TextView) HasFocus

func (t *TextView) HasFocus() bool

HasFocus returns whether or not this primitive has focus.

func (*TextView) Highlight

func (t *TextView) Highlight(regionIDs ...string) *TextView

Highlight specifies which regions should be highlighted. If highlight toggling is set to true (see TextView.SetToggleHighlights), the highlight of the provided regions is toggled (i.e. highlighted regions are un-highlighted and vice versa). If toggling is set to false, the provided regions are highlighted and all other regions will not be highlighted (you may also provide nil to turn off all highlights).

For more information on regions, see class description. Empty region strings or regions not contained in the text are ignored.

Text in highlighted regions will be drawn inverted, i.e. with their background and foreground colors swapped.

If toggling is set to false, clicking outside of any region will remove all highlights.

This function is expensive if a specified region is in a part of the text that has not yet been parsed.

func (*TextView) InputHandler

func (t *TextView) InputHandler() func(event *tcell.EventKey, setFocus func(p Primitive))

InputHandler returns the handler for this primitive.

func (*TextView) MouseHandler

func (t *TextView) MouseHandler() func(action MouseAction, event *tcell.EventMouse, setFocus func(p Primitive)) (consumed bool, capture Primitive)

MouseHandler returns the mouse handler for this primitive.

func (*TextView) ScrollTo

func (t *TextView) ScrollTo(row, column int) *TextView

ScrollTo scrolls to the specified row and column (both starting with 0).

func (*TextView) ScrollToBeginning

func (t *TextView) ScrollToBeginning() *TextView

ScrollToBeginning scrolls to the top left corner of the text if the text view is scrollable.

func (*TextView) ScrollToEnd

func (t *TextView) ScrollToEnd() *TextView

ScrollToEnd scrolls to the bottom left corner of the text if the text view is scrollable. Adding new rows to the end of the text view will cause it to scroll with the new data.

func (*TextView) ScrollToHighlight

func (t *TextView) ScrollToHighlight() *TextView

ScrollToHighlight will cause the visible area to be scrolled so that the highlighted regions appear in the visible area of the text view. This repositioning happens the next time the text view is drawn. It happens only once so you will need to call this function repeatedly to always keep highlighted regions in view.

Nothing happens if there are no highlighted regions or if the text view is not scrollable.

func (*TextView) SetBackgroundColor

func (t *TextView) SetBackgroundColor(color tcell.Color) *Box

SetBackgroundColor overrides its implementation in Box to set the background color of this primitive. For backwards compatibility reasons, it also sets the background color of the main text element.

func (*TextView) SetChangedFunc

func (t *TextView) SetChangedFunc(handler func()) *TextView

SetChangedFunc sets a handler function which is called when the text of the text view has changed. This is useful when text is written to this io.Writer in a separate goroutine. Doing so does not automatically cause the screen to be refreshed so you may want to use the "changed" handler to redraw the screen.

Note that to avoid race conditions or deadlocks, there are a few rules you should follow:

See package description for details on dealing with concurrency.

func (*TextView) SetDisabled

func (t *TextView) SetDisabled(disabled bool) FormItem

SetDisabled sets whether or not the item is disabled / read-only.

func (*TextView) SetDoneFunc

func (t *TextView) SetDoneFunc(handler func(key tcell.Key)) *TextView

SetDoneFunc sets a handler which is called when the user presses on the following keys: Escape, Enter, Tab, Backtab. The key is passed to the handler.

func (*TextView) SetDynamicColors

func (t *TextView) SetDynamicColors(dynamic bool) *TextView

SetDynamicColors sets the flag that allows the text color to be changed dynamically with style tags. See class description for details.

func (*TextView) SetFinishedFunc

func (t *TextView) SetFinishedFunc(handler func(key tcell.Key)) FormItem

SetFinishedFunc sets a callback invoked when the user leaves this form item.

func (*TextView) SetFormAttributes

func (t *TextView) SetFormAttributes(labelWidth int, labelColor, bgColor, fieldTextColor, fieldBgColor tcell.Color) FormItem

SetFormAttributes sets attributes shared by all form items.

func (*TextView) SetHighlightedFunc

func (t *TextView) SetHighlightedFunc(handler func(added, removed, remaining []string)) *TextView

SetHighlightedFunc sets a handler which is called when the list of currently highlighted regions change. It receives a list of region IDs which were newly highlighted, those that are not highlighted anymore, and those that remain highlighted.

Note that because regions are only determined when drawing the text view, this function can only fire for regions that have existed when the text view was last drawn.

func (*TextView) SetLabel

func (t *TextView) SetLabel(label string) *TextView

SetLabel sets the text to be displayed before the text view.

func (*TextView) SetLabelWidth

func (t *TextView) SetLabelWidth(width int) *TextView

SetLabelWidth sets the screen width of the label. A value of 0 will cause the primitive to use the width of the label string.

func (*TextView) SetMaxLines

func (t *TextView) SetMaxLines(maxLines int) *TextView

SetMaxLines sets the maximum number of lines for this text view. Lines at the beginning of the text will be discarded when the text view is drawn, so as to remain below this value. Only lines above the first visible line are removed.

Broken-over lines via word/character wrapping are counted individually.

Note that TextView.GetText will return the shortened text.

A value of 0 (the default) will keep all lines in place.

func (*TextView) SetRegions

func (t *TextView) SetRegions(regions bool) *TextView

SetRegions sets the flag that allows to define regions in the text. See class description for details.

func (*TextView) SetScrollable

func (t *TextView) SetScrollable(scrollable bool) *TextView

SetScrollable sets the flag that decides whether or not the text view is scrollable. If false, text that moves above the text view's top row will be permanently deleted.

func (*TextView) SetSize

func (t *TextView) SetSize(rows, columns int) *TextView

SetSize sets the screen size of the main text element of the text view. This element is always located next to the label which is always located in the top left corner. If any of the values are 0 or larger than the available space, the available space will be used.

func (*TextView) SetText

func (t *TextView) SetText(text string) *TextView

SetText sets the text of this text view to the provided string. Previously contained text will be removed. As with writing to the text view io.Writer interface directly, this does not trigger an automatic redraw but it will trigger the "changed" callback if one is set.

func (*TextView) SetTextAlign

func (t *TextView) SetTextAlign(align int) *TextView

SetTextAlign sets the text alignment within the text view. This must be either AlignLeft, AlignCenter, or AlignRight.

func (*TextView) SetTextColor

func (t *TextView) SetTextColor(color tcell.Color) *TextView

SetTextColor sets the initial color of the text.

func (*TextView) SetTextStyle

func (t *TextView) SetTextStyle(style tcell.Style) *TextView

SetTextStyle sets the initial style of the text. This style's background color also determines the background color of the main text element.

func (*TextView) SetToggleHighlights

func (t *TextView) SetToggleHighlights(toggle bool) *TextView

SetToggleHighlights sets a flag to determine how regions are highlighted. When set to true, the TextView.Highlight function (or a mouse click) will toggle the provided/selected regions. When set to false, TextView.Highlight (or a mouse click) will simply highlight the provided regions.

func (*TextView) SetWordWrap

func (t *TextView) SetWordWrap(wrapOnWords bool) *TextView

SetWordWrap sets the flag that, if true and if the "wrap" flag is also true (see TextView.SetWrap), wraps according to [Unicode Standard Annex #14].

This flag is ignored if the "wrap" flag is false.

func (*TextView) SetWrap

func (t *TextView) SetWrap(wrap bool) *TextView

SetWrap sets the flag that, if true, leads to lines that are longer than the available width being wrapped onto the next line. If false, any characters beyond the available width are not displayed.

func (*TextView) Write

func (t *TextView) Write(p []byte) (n int, err error)

Write lets us implement the io.Writer interface.

type TextViewWriter

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

TextViewWriter is a writer that can be used to write to and clear a TextView in batches, i.e. multiple writes with the lock only being acquired once. Don't instantiated this class directly but use the TextView's BatchWriter method instead.

func (TextViewWriter) Clear

func (w TextViewWriter) Clear()

Clear removes all text from the buffer.

func (TextViewWriter) Close

func (w TextViewWriter) Close() error

Close implements io.Closer for the writer by unlocking the original TextView.

func (TextViewWriter) HasFocus

func (w TextViewWriter) HasFocus() bool

HasFocus returns whether the underlying TextView has focus.

func (TextViewWriter) Write

func (w TextViewWriter) Write(p []byte) (n int, err error)

Write implements the io.Writer interface. It behaves like the TextView's Write() method except that it does not acquire the lock.

type Theme

type Theme struct {
	PrimitiveBackgroundColor    tcell.Color // Main background color for primitives.
	ContrastBackgroundColor     tcell.Color // Background color for contrasting elements.
	MoreContrastBackgroundColor tcell.Color // Background color for even more contrasting elements.
	BorderColor                 tcell.Color // Box borders.
	TitleColor                  tcell.Color // Box titles.
	GraphicsColor               tcell.Color // Graphics.
	PrimaryTextColor            tcell.Color // Primary text.
	SecondaryTextColor          tcell.Color // Secondary text (e.g. labels).
	TertiaryTextColor           tcell.Color // Tertiary text (e.g. subtitles, notes).
	InverseTextColor            tcell.Color // Text on primary-colored backgrounds.
	ContrastSecondaryTextColor  tcell.Color // Secondary text on ContrastBackgroundColor-colored backgrounds.
}

Theme defines the colors used when primitives are initialized.

type TreeNode

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

TreeNode represents one node in a tree view.

func NewTreeNode

func NewTreeNode(text string) *TreeNode

NewTreeNode returns a new tree node.

func (*TreeNode) AddChild

func (n *TreeNode) AddChild(node *TreeNode) *TreeNode

AddChild adds a new child node to this node.

func (*TreeNode) ClearChildren

func (n *TreeNode) ClearChildren() *TreeNode

ClearChildren removes all child nodes from this node.

func (*TreeNode) Collapse

func (n *TreeNode) Collapse() *TreeNode

Collapse makes the child nodes of this node disappear.

func (*TreeNode) CollapseAll

func (n *TreeNode) CollapseAll() *TreeNode

CollapseAll collapses this node and all descendent nodes.

func (*TreeNode) Expand

func (n *TreeNode) Expand() *TreeNode

Expand makes the child nodes of this node appear.

func (*TreeNode) ExpandAll

func (n *TreeNode) ExpandAll() *TreeNode

ExpandAll expands this node and all descendent nodes.

func (*TreeNode) GetChildren

func (n *TreeNode) GetChildren() []*TreeNode

GetChildren returns this node's children.

func (*TreeNode) GetColor

func (n *TreeNode) GetColor() tcell.Color

GetColor returns the node's color.

func (*TreeNode) GetLevel

func (n *TreeNode) GetLevel() int

GetLevel returns the node's level within the hierarchy, where 0 corresponds to the root node, 1 corresponds to its children, and so on. This is only guaranteed to be up to date immediately after the tree that contains this node is drawn.

func (*TreeNode) GetReference

func (n *TreeNode) GetReference() interface{}

GetReference returns this node's reference object.

func (*TreeNode) GetText

func (n *TreeNode) GetText() string

GetText returns this node's text.

func (*TreeNode) IsExpanded

func (n *TreeNode) IsExpanded() bool

IsExpanded returns whether the child nodes of this node are visible.

func (*TreeNode) RemoveChild

func (n *TreeNode) RemoveChild(node *TreeNode) *TreeNode

RemoveChild removes a child node from this node. If the child node cannot be found, nothing happens.

func (*TreeNode) SetChildren

func (n *TreeNode) SetChildren(childNodes []*TreeNode) *TreeNode

SetChildren sets this node's child nodes.

func (*TreeNode) SetColor

func (n *TreeNode) SetColor(color tcell.Color) *TreeNode

SetColor sets the node's text color.

func (*TreeNode) SetExpanded

func (n *TreeNode) SetExpanded(expanded bool) *TreeNode

SetExpanded sets whether or not this node's child nodes should be displayed.

func (*TreeNode) SetIndent

func (n *TreeNode) SetIndent(indent int) *TreeNode

SetIndent sets an additional indentation for this node's text. A value of 0 keeps the text as far left as possible with a minimum of line graphics. Any value greater than that moves the text to the right.

func (*TreeNode) SetReference

func (n *TreeNode) SetReference(reference interface{}) *TreeNode

SetReference allows you to store a reference of any type in this node. This will allow you to establish a mapping between the TreeView hierarchy and your internal tree structure.

func (*TreeNode) SetSelectable

func (n *TreeNode) SetSelectable(selectable bool) *TreeNode

SetSelectable sets a flag indicating whether this node can be selected by the user.

func (*TreeNode) SetSelectedFunc

func (n *TreeNode) SetSelectedFunc(handler func()) *TreeNode

SetSelectedFunc sets a function which is called when the user selects this node by hitting Enter when it is selected.

func (*TreeNode) SetText

func (n *TreeNode) SetText(text string) *TreeNode

SetText sets the node's text which is displayed.

func (*TreeNode) Walk

func (n *TreeNode) Walk(callback func(node, parent *TreeNode) bool) *TreeNode

Walk traverses this node's subtree in depth-first, pre-order (NLR) order and calls the provided callback function on each traversed node (which includes this node) with the traversed node and its parent node (nil for this node). The callback returns whether traversal should continue with the traversed node's child nodes (true) or not recurse any deeper (false).

type TreeView

type TreeView struct {
	*Box
	// contains filtered or unexported fields
}

TreeView displays tree structures. A tree consists of nodes (TreeNode objects) where each node has zero or more child nodes and exactly one parent node (except for the root node which has no parent node).

The SetRoot() function is used to specify the root of the tree. Other nodes are added locally to the root node or any of its descendents. See the TreeNode documentation for details on node attributes. (You can use SetReference() to store a reference to nodes of your own tree structure.)

Nodes can be selected by calling SetCurrentNode(). The user can navigate the selection or the tree by using the following keys:

  • j, down arrow, right arrow: Move (the selection) down by one node.
  • k, up arrow, left arrow: Move (the selection) up by one node.
  • g, home: Move (the selection) to the top.
  • G, end: Move (the selection) to the bottom.
  • J: Move (the selection) up one level (if that node is selectable).
  • K: Move (the selection) to the last node one level down (if any).
  • Ctrl-F, page down: Move (the selection) down by one page.
  • Ctrl-B, page up: Move (the selection) up by one page.

Selected nodes can trigger the "selected" callback when the user hits Enter.

The root node corresponds to level 0, its children correspond to level 1, their children to level 2, and so on. Per default, the first level that is displayed is 0, i.e. the root node. You can call SetTopLevel() to hide levels.

If graphics are turned on (see SetGraphics()), lines indicate the tree's hierarchy. Alternative (or additionally), you can set different prefixes using SetPrefixes() for different levels, for example to display hierarchical bullet point lists.

See https://github.com/rivo/tview/wiki/TreeView for an example.

func NewTreeView

func NewTreeView() *TreeView

NewTreeView returns a new tree view.

func (*TreeView) Draw

func (t *TreeView) Draw(screen tcell.Screen)

Draw draws this primitive onto the screen.

func (*TreeView) GetCurrentNode

func (t *TreeView) GetCurrentNode() *TreeNode

GetCurrentNode returns the currently selected node or nil of no node is currently selected.

func (*TreeView) GetPath

func (t *TreeView) GetPath(node *TreeNode) []*TreeNode

GetPath returns all nodes located on the path from the root to the given node, including the root and the node itself. If there is no root node, nil is returned. If there are multiple paths to the node, a random one is chosen and returned.

func (*TreeView) GetRoot

func (t *TreeView) GetRoot() *TreeNode

GetRoot returns the root node of the tree. If no such node was previously set, nil is returned.

func (*TreeView) GetRowCount

func (t *TreeView) GetRowCount() int

GetRowCount returns the number of "visible" nodes. This includes nodes which fall outside the tree view's box but notably does not include the children of collapsed nodes. Note that this value is only up to date after the tree view has been drawn.

func (*TreeView) GetScrollOffset

func (t *TreeView) GetScrollOffset() int

GetScrollOffset returns the number of node rows that were skipped at the top of the tree view. Note that when the user navigates the tree view, this value is only updated after the tree view has been redrawn.

func (*TreeView) InputHandler

func (t *TreeView) InputHandler() func(event *tcell.EventKey, setFocus func(p Primitive))

InputHandler returns the handler for this primitive.

func (*TreeView) MouseHandler

func (t *TreeView) MouseHandler() func(action MouseAction, event *tcell.EventMouse, setFocus func(p Primitive)) (consumed bool, capture Primitive)

MouseHandler returns the mouse handler for this primitive.

func (*TreeView) Move

func (t *TreeView) Move(offset int) *TreeView

Move moves the selection (if a node is currently selected) or scrolls the tree view (if there is no selection), by the given offset (positive values to move/scroll down, negative values to move/scroll up). For selection changes, the offset refers to the number selectable, visible nodes. For scrolling, the offset refers to the number of visible nodes.

If the offset is 0, nothing happens.

func (*TreeView) SetAlign

func (t *TreeView) SetAlign(align bool) *TreeView

SetAlign controls the horizontal alignment of the node texts. If set to true, all texts except that of top-level nodes will be placed in the same column. If set to false, they will indent with the hierarchy.

func (*TreeView) SetChangedFunc

func (t *TreeView) SetChangedFunc(handler func(node *TreeNode)) *TreeView

SetChangedFunc sets the function which is called when the currently selected node changes, for example when the user navigates to a new tree node.

func (*TreeView) SetCurrentNode

func (t *TreeView) SetCurrentNode(node *TreeNode) *TreeView

SetCurrentNode sets the currently selected node. Provide nil to clear all selections. Selected nodes must be visible and selectable, or else the selection will be changed to the top-most selectable and visible node.

This function does NOT trigger the "changed" callback because the actual node that will be selected is not known until the tree is drawn. Triggering the "changed" callback is thus deferred until the next call to TreeView.Draw.

func (*TreeView) SetDoneFunc

func (t *TreeView) SetDoneFunc(handler func(key tcell.Key)) *TreeView

SetDoneFunc sets a handler which is called whenever the user presses the Escape, Tab, or Backtab key.

func (*TreeView) SetGraphics

func (t *TreeView) SetGraphics(showGraphics bool) *TreeView

SetGraphics sets a flag which determines whether or not line graphics are drawn to illustrate the tree's hierarchy.

func (*TreeView) SetGraphicsColor

func (t *TreeView) SetGraphicsColor(color tcell.Color) *TreeView

SetGraphicsColor sets the colors of the lines used to draw the tree structure.

func (*TreeView) SetPrefixes

func (t *TreeView) SetPrefixes(prefixes []string) *TreeView

SetPrefixes defines the strings drawn before the nodes' texts. This is a slice of strings where each element corresponds to a node's hierarchy level, i.e. 0 for the root, 1 for the root's children, and so on (levels will cycle).

For example, to display a hierarchical list with bullet points:

treeView.SetGraphics(false).
  SetPrefixes([]string{"* ", "- ", "x "})

Deeper levels will cycle through the prefixes.

func (*TreeView) SetRoot

func (t *TreeView) SetRoot(root *TreeNode) *TreeView

SetRoot sets the root node of the tree.

func (*TreeView) SetSelectedFunc

func (t *TreeView) SetSelectedFunc(handler func(node *TreeNode)) *TreeView

SetSelectedFunc sets the function which is called when the user selects a node by pressing Enter on the current selection.

func (*TreeView) SetTopLevel

func (t *TreeView) SetTopLevel(topLevel int) *TreeView

SetTopLevel sets the first tree level that is visible with 0 referring to the root, 1 to the root's child nodes, and so on. Nodes above the top level are not displayed.

Directories

Path Synopsis
demos
box
Demo code for the Box primitive.
Demo code for the Box primitive.
button
Demo code for the Button primitive.
Demo code for the Button primitive.
checkbox
Demo code for the Checkbox primitive.
Demo code for the Checkbox primitive.
dropdown
Demo code for the DropDown primitive.
Demo code for the DropDown primitive.
flex
Demo code for the Flex primitive.
Demo code for the Flex primitive.
form
Demo code for the Form primitive.
Demo code for the Form primitive.
frame
Demo code for the Frame primitive.
Demo code for the Frame primitive.
grid
Demo code for the Grid primitive.
Demo code for the Grid primitive.
image
Demo code for the Image primitive.
Demo code for the Image primitive.
inputfield
Demo code for the InputField primitive.
Demo code for the InputField primitive.
list
Demo code for the List primitive.
Demo code for the List primitive.
modal
Demo code for the Modal primitive.
Demo code for the Modal primitive.
pages
Demo code for the Pages primitive.
Demo code for the Pages primitive.
presentation
A presentation of the tview package, implemented with tview.
A presentation of the tview package, implemented with tview.
primitive
Demo code which illustrates how to implement your own primitive.
Demo code which illustrates how to implement your own primitive.
table
Demo code for the Table primitive.
Demo code for the Table primitive.
textarea
Demo code for the TextArea primitive.
Demo code for the TextArea primitive.
textview
Demo code for the TextView primitive.
Demo code for the TextView primitive.
treeview
Demo code for the TreeView primitive.
Demo code for the TreeView primitive.
unicode
Demo code for unicode support (demonstrates wide Chinese characters).
Demo code for unicode support (demonstrates wide Chinese characters).

Jump to

Keyboard shortcuts

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