Displaying Text
This page covers how text displaying works. It will cover Span
, Line
, and Text
, and how these
can be created, styled, displayed, altered, and such.
Span
A Span
is a styled segment of text. You can think of it as a substring with its own unique style.
It is the most basic unit of displaying text in ratatui
.
The examples below assume the following imports:
A Span
consists of “content” and a “style” for the content. And a Span
can be created in a few
different ways.
-
using
Span::raw
: -
using
Span::styled
: -
using the
Stylize
trait:
A Span
is the basic building block for any styled text, and can be used anywhere text is
displayed.
Line
The next building block that we are going to talk about is a Line
. A Line
represents a cluster
of graphemes, where each unit in the cluster can have its own style. You can think of an instance of
the Line
struct as essentially a collection of Span
objects, i.e. Vec<Span>
.
Since each Line
struct consists of multiple Span
objects, this allows for varied styling in a
row of words, phrases or sentences.
A Line
can be constructed directly from content, where the content is Into<Cow<'a, &str>>
.
You can even style a full line directly:
And you can use the Stylize
trait on the line directly by using into()
:
Finally, you can also align it using alignment()
or the shorthand methods left_aligned()
,
centered()
and right_aligned()
. Widgets using Line
internally will generally respect this.
Text
Text
is the final building block of outputting text. A Text
object represents a collection of
Line
s.
Most widgets accept content that can be converted to Text
.
Here’s an HTML representation of what you’d get in the terminal:
Often code like the one above can be simplified:
This is because in this case, Rust is able to infer the types and convert them appropriately.
Text
instances can be created using the raw
or styled
constructors too.
Something that you might find yourself doing pretty often for a Paragraph
is wanting to have
multiple lines styled differently. This is one way you might go about that:
hello world 1
hello world 2
hello world 3
We will talk more about styling in the next section.
As with Line
, a Text
can be aligned with alignment()
or the shorthand methods
left_aligned()
, centered()
and right_aligned()
. Widgets using Text
internally will generally
respect this. Note in the example below, you can override the alignment for a particular line.
hello world 1
hello world 2
hello world 3