chore(rustfmt): enable format_code_in_doc_comments (#695)

This enables more consistently formatted code in doc comments,
especially since ratatui heavily uses fluent setters.

See https://rust-lang.github.io/rustfmt/?version=v1.6.0#format_code_in_doc_comments
This commit is contained in:
Valentin271 2023-12-16 13:01:07 +01:00 committed by GitHub
parent b282a06932
commit 910ad00059
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
24 changed files with 285 additions and 173 deletions

View file

@ -3,3 +3,4 @@ group_imports = "StdExternalCrate"
imports_granularity = "Crate"
wrap_comments = true
comment_width = 100
format_code_in_doc_comments = true

View file

@ -26,6 +26,7 @@
//!
//! ```rust,no_run
//! use std::io::stdout;
//!
//! use ratatui::prelude::*;
//!
//! let backend = CrosstermBackend::new(stdout());

View file

@ -43,7 +43,8 @@ use crate::{
/// # Example
///
/// ```rust,no_run
/// use std::io::{stdout, stderr};
/// use std::io::{stderr, stdout};
///
/// use crossterm::{
/// terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
/// ExecutableCommand,

View file

@ -36,7 +36,8 @@ use crate::{
/// # Example
///
/// ```rust,no_run
/// use std::io::{stdout, stderr};
/// use std::io::{stderr, stdout};
///
/// use ratatui::prelude::*;
/// use termion::{raw::IntoRawMode, screen::IntoAlternateScreen};
///

View file

@ -140,13 +140,23 @@ impl Default for Cell {
/// # Examples:
///
/// ```
/// use ratatui::{prelude::*, buffer::Cell};
/// use ratatui::{buffer::Cell, prelude::*};
///
/// let mut buf = Buffer::empty(Rect{x: 0, y: 0, width: 10, height: 5});
/// let mut buf = Buffer::empty(Rect {
/// x: 0,
/// y: 0,
/// width: 10,
/// height: 5,
/// });
/// buf.get_mut(0, 2).set_symbol("x");
/// assert_eq!(buf.get(0, 2).symbol(), "x");
///
/// buf.set_string(3, 0, "string", Style::default().fg(Color::Red).bg(Color::White));
/// buf.set_string(
/// 3,
/// 0,
/// "string",
/// Style::default().fg(Color::Red).bg(Color::White),
/// );
/// let cell = buf.get_mut(5, 0);
/// assert_eq!(cell.symbol(), "r");
/// assert_eq!(cell.fg, Color::Red);

View file

@ -268,7 +268,7 @@ impl Layout {
///
/// let layout = Layout::new(
/// Direction::Vertical,
/// [1,2,3].iter().map(|&c| Constraint::Length(c)),
/// [1, 2, 3].iter().map(|&c| Constraint::Length(c)),
/// );
/// ```
pub fn new<I>(direction: Direction, constraints: I) -> Layout
@ -353,19 +353,22 @@ impl Layout {
/// Constraint::Max(2),
/// ])
/// .split(Rect::new(0, 0, 10, 10));
/// assert_eq!(layout[..], [
/// assert_eq!(
/// layout[..],
/// [
/// Rect::new(0, 0, 10, 2),
/// Rect::new(0, 2, 10, 2),
/// Rect::new(0, 4, 10, 2),
/// Rect::new(0, 6, 10, 2),
/// Rect::new(0, 8, 10, 2),
/// ]);
/// ]
/// );
///
/// let layout = Layout::default().constraints([Constraint::Min(0)]);
/// let layout = Layout::default().constraints(&[Constraint::Min(0)]);
/// let layout = Layout::default().constraints(vec![Constraint::Min(0)]);
/// let layout = Layout::default().constraints([Constraint::Min(0)].iter().filter(|_| true));
/// let layout = Layout::default().constraints([1,2,3].iter().map(|&c| Constraint::Length(c)));
/// let layout = Layout::default().constraints([1, 2, 3].iter().map(|&c| Constraint::Length(c)));
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
pub fn constraints<I>(mut self, constraints: I) -> Layout
@ -660,9 +663,7 @@ impl Constraint {
/// # use ratatui::prelude::*;
/// # let area = Rect::default();
/// let constraints = Constraint::from_lengths([1, 2, 3]);
/// let layout = Layout::default()
/// .constraints(constraints)
/// .split(area);
/// let layout = Layout::default().constraints(constraints).split(area);
/// ```
pub fn from_lengths<T>(lengths: T) -> Vec<Constraint>
where
@ -679,9 +680,7 @@ impl Constraint {
/// # use ratatui::prelude::*;
/// # let area = Rect::default();
/// let constraints = Constraint::from_ratios([(1, 4), (1, 2), (1, 4)]);
/// let layout = Layout::default()
/// .constraints(constraints)
/// .split(area);
/// let layout = Layout::default().constraints(constraints).split(area);
/// ```
pub fn from_ratios<T>(ratios: T) -> Vec<Constraint>
where
@ -701,9 +700,7 @@ impl Constraint {
/// # use ratatui::prelude::*;
/// # let area = Rect::default();
/// let constraints = Constraint::from_percentages([25, 50, 25]);
/// let layout = Layout::default()
/// .constraints(constraints)
/// .split(area);
/// let layout = Layout::default().constraints(constraints).split(area);
/// ```
pub fn from_percentages<T>(percentages: T) -> Vec<Constraint>
where
@ -723,9 +720,7 @@ impl Constraint {
/// # use ratatui::prelude::*;
/// # let area = Rect::default();
/// let constraints = Constraint::from_maxes([1, 2, 3]);
/// let layout = Layout::default()
/// .constraints(constraints)
/// .split(area);
/// let layout = Layout::default().constraints(constraints).split(area);
/// ```
pub fn from_maxes<T>(maxes: T) -> Vec<Constraint>
where
@ -742,9 +737,7 @@ impl Constraint {
/// # use ratatui::prelude::*;
/// # let area = Rect::default();
/// let constraints = Constraint::from_mins([1, 2, 3]);
/// let layout = Layout::default()
/// .constraints(constraints)
/// .split(area);
/// let layout = Layout::default().constraints(constraints).split(area);
/// ```
pub fn from_mins<T>(mins: T) -> Vec<Constraint>
where

View file

@ -110,10 +110,11 @@
//!
//! ```rust,no_run
//! use std::io::{self, stdout};
//!
//! use crossterm::{
//! event::{self, Event, KeyCode},
//! terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
//! ExecutableCommand,
//! terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen}
//! };
//! use ratatui::{prelude::*, widgets::*};
//!
@ -174,7 +175,7 @@
//! Constraint::Length(1),
//! Constraint::Min(0),
//! Constraint::Length(1),
//! ]
//! ],
//! )
//! .split(frame.size());
//! frame.render_widget(
@ -188,7 +189,7 @@
//!
//! let inner_layout = Layout::new(
//! Direction::Horizontal,
//! [Constraint::Percentage(50), Constraint::Percentage(50)]
//! [Constraint::Percentage(50), Constraint::Percentage(50)],
//! )
//! .split(main_layout[1]);
//! frame.render_widget(
@ -230,7 +231,7 @@
//! Constraint::Length(1),
//! Constraint::Length(1),
//! Constraint::Min(0),
//! ]
//! ],
//! )
//! .split(frame.size());
//!

View file

@ -47,13 +47,21 @@
//! "hello".red().on_blue().bold(),
//! Span::styled(
//! "hello",
//! Style::default().fg(Color::Red).bg(Color::Blue).add_modifier(Modifier::BOLD))
//! Style::default()
//! .fg(Color::Red)
//! .bg(Color::Blue)
//! .add_modifier(Modifier::BOLD)
//! )
//! );
//!
//! assert_eq!(
//! Paragraph::new("hello").red().on_blue().bold(),
//! Paragraph::new("hello")
//! .style(Style::default().fg(Color::Red).bg(Color::Blue).add_modifier(Modifier::BOLD))
//! Paragraph::new("hello").style(
//! Style::default()
//! .fg(Color::Red)
//! .bg(Color::Blue)
//! .add_modifier(Modifier::BOLD)
//! )
//! );
//! ```
//!
@ -113,7 +121,7 @@ impl fmt::Debug for Modifier {
/// Style lets you control the main characteristics of the displayed elements.
///
/// ```rust
/// use ratatui::{prelude::*};
/// use ratatui::prelude::*;
///
/// Style::default()
/// .fg(Color::Black)
@ -135,14 +143,20 @@ impl fmt::Debug for Modifier {
/// just S3.
///
/// ```rust
/// use ratatui::{prelude::*};
/// use ratatui::prelude::*;
///
/// let styles = [
/// Style::default().fg(Color::Blue).add_modifier(Modifier::BOLD | Modifier::ITALIC),
/// Style::default().bg(Color::Red).add_modifier(Modifier::UNDERLINED),
/// Style::default()
/// .fg(Color::Blue)
/// .add_modifier(Modifier::BOLD | Modifier::ITALIC),
/// Style::default()
/// .bg(Color::Red)
/// .add_modifier(Modifier::UNDERLINED),
/// #[cfg(feature = "underline-color")]
/// Style::default().underline_color(Color::Green),
/// Style::default().fg(Color::Yellow).remove_modifier(Modifier::ITALIC),
/// Style::default()
/// .fg(Color::Yellow)
/// .remove_modifier(Modifier::ITALIC),
/// ];
/// let mut buffer = Buffer::empty(Rect::new(0, 0, 1, 1));
/// for style in &styles {
@ -165,10 +179,12 @@ impl fmt::Debug for Modifier {
/// reset all properties until that point use [`Style::reset`].
///
/// ```
/// use ratatui::{prelude::*};
/// use ratatui::prelude::*;
///
/// let styles = [
/// Style::default().fg(Color::Blue).add_modifier(Modifier::BOLD | Modifier::ITALIC),
/// Style::default()
/// .fg(Color::Blue)
/// .add_modifier(Modifier::BOLD | Modifier::ITALIC),
/// Style::reset().fg(Color::Yellow),
/// ];
/// let mut buffer = Buffer::empty(Rect::new(0, 0, 1, 1));
@ -285,9 +301,18 @@ impl Style {
///
/// ```rust
/// # use ratatui::prelude::*;
/// let style = Style::default().underline_color(Color::Blue).add_modifier(Modifier::UNDERLINED);
/// let diff = Style::default().underline_color(Color::Red).add_modifier(Modifier::UNDERLINED);
/// assert_eq!(style.patch(diff), Style::default().underline_color(Color::Red).add_modifier(Modifier::UNDERLINED));
/// let style = Style::default()
/// .underline_color(Color::Blue)
/// .add_modifier(Modifier::UNDERLINED);
/// let diff = Style::default()
/// .underline_color(Color::Red)
/// .add_modifier(Modifier::UNDERLINED);
/// assert_eq!(
/// style.patch(diff),
/// Style::default()
/// .underline_color(Color::Red)
/// .add_modifier(Modifier::UNDERLINED)
/// );
/// ```
#[cfg(feature = "underline-color")]
#[must_use = "`underline_color` returns the modified style without modifying the original"]
@ -349,7 +374,8 @@ impl Style {
/// let combined = style_1.patch(style_2);
/// assert_eq!(
/// Style::default().patch(style_1).patch(style_2),
/// Style::default().patch(combined));
/// Style::default().patch(combined)
/// );
/// ```
#[must_use = "`patch` returns the modified style without modifying the original"]
pub fn patch(mut self, other: Style) -> Style {

View file

@ -39,6 +39,7 @@ use std::{
///
/// ```
/// use std::str::FromStr;
///
/// use ratatui::prelude::*;
///
/// assert_eq!(Color::from_str("red"), Ok(Color::Red));
@ -147,6 +148,7 @@ impl std::error::Error for ParseColorError {}
///
/// ```
/// use std::str::FromStr;
///
/// use ratatui::prelude::*;
///
/// let color: Color = Color::from_str("blue").unwrap();

View file

@ -127,7 +127,11 @@ macro_rules! modifier {
/// "world".green().on_yellow().not_bold(),
/// ]);
/// let paragraph = Paragraph::new(line).italic().underlined();
/// let block = Block::default().title("Title").borders(Borders::ALL).on_white().bold();
/// let block = Block::default()
/// .title("Title")
/// .borders(Borders::ALL)
/// .on_white()
/// .bold();
/// ```
pub trait Stylize<'a, T>: Sized {
#[must_use = "`bg` returns the modified style without modifying the original"]

View file

@ -12,6 +12,7 @@
//!
//! ```rust,no_run
//! use std::io::stdout;
//!
//! use ratatui::{prelude::*, widgets::Paragraph};
//!
//! let backend = CrosstermBackend::new(stdout());
@ -108,6 +109,7 @@ pub struct TerminalOptions {
///
/// ```rust,no_run
/// use std::io::stdout;
///
/// use ratatui::{prelude::*, widgets::Paragraph};
///
/// let backend = CrosstermBackend::new(stdout());
@ -198,10 +200,7 @@ where
/// # use ratatui::{prelude::*, backend::TestBackend};
/// let backend = CrosstermBackend::new(stdout());
/// let viewport = Viewport::Fixed(Rect::new(0, 0, 10, 10));
/// let terminal = Terminal::with_options(
/// backend,
/// TerminalOptions { viewport },
/// )?;
/// let terminal = Terminal::with_options(backend, TerminalOptions { viewport })?;
/// # std::io::Result::Ok(())
/// ```
pub fn with_options(mut backend: B, options: TerminalOptions) -> io::Result<Terminal<B>> {
@ -459,8 +458,9 @@ where
/// Paragraph::new(Line::from(vec![
/// Span::raw("This line will be added "),
/// Span::styled("before", Style::default().fg(Color::Blue)),
/// Span::raw(" the current viewport")
/// ])).render(buf.area, buf);
/// Span::raw(" the current viewport"),
/// ]))
/// .render(buf.area, buf);
/// });
/// ```
pub fn insert_before<F>(&mut self, height: u16, draw_fn: F) -> io::Result<()>
@ -628,10 +628,7 @@ impl Frame<'_> {
/// # let mut terminal = Terminal::new(backend).unwrap();
/// # let mut frame = terminal.get_frame();
/// let mut state = ListState::default().with_selected(Some(1));
/// let list = List::new(vec![
/// ListItem::new("Item 1"),
/// ListItem::new("Item 2"),
/// ]);
/// let list = List::new(vec![ListItem::new("Item 1"), ListItem::new("Item 2")]);
/// let area = Rect::new(0, 0, 5, 5);
/// frame.render_stateful_widget(list, area, &mut state);
/// ```

View file

@ -31,9 +31,8 @@
//! // Converted to Line(vec![
//! // Span { content: Cow::Borrowed("My title"), style: Style { fg: Some(Color::Yellow), .. }
//! // ])
//! let block = Block::default().title(
//! Span::styled("My title", Style::default().fg(Color::Yellow))
//! );
//! let block =
//! Block::default().title(Span::styled("My title", Style::default().fg(Color::Yellow)));
//!
//! // A string with multiple styles.
//! // Converted to Line(vec![

View file

@ -39,7 +39,9 @@ impl<'a> Line<'a> {
///
/// ```rust
/// # use ratatui::prelude::*;
/// let style = Style::default().fg(Color::Yellow).add_modifier(Modifier::ITALIC);
/// let style = Style::default()
/// .fg(Color::Yellow)
/// .add_modifier(Modifier::ITALIC);
/// Line::styled("My text", style);
/// Line::styled(String::from("My text"), style);
/// ```
@ -75,12 +77,14 @@ impl<'a> Line<'a> {
///
/// ```rust
/// use std::iter::Iterator;
///
/// use ratatui::{prelude::*, text::StyledGrapheme};
///
/// let line = Line::styled("Text", Style::default().fg(Color::Yellow));
/// let style = Style::default().fg(Color::Green).bg(Color::Black);
/// assert_eq!(
/// line.styled_graphemes(style).collect::<Vec<StyledGrapheme>>(),
/// line.styled_graphemes(style)
/// .collect::<Vec<StyledGrapheme>>(),
/// vec![
/// StyledGrapheme::new("T", Style::default().fg(Color::Yellow).bg(Color::Black)),
/// StyledGrapheme::new("e", Style::default().fg(Color::Yellow).bg(Color::Black)),
@ -104,11 +108,10 @@ impl<'a> Line<'a> {
///
/// ```rust
/// # use ratatui::prelude::*;
/// let style = Style::default().fg(Color::Yellow).add_modifier(Modifier::ITALIC);
/// let mut raw_line = Line::from(vec![
/// Span::raw("My"),
/// Span::raw(" text"),
/// ]);
/// let style = Style::default()
/// .fg(Color::Yellow)
/// .add_modifier(Modifier::ITALIC);
/// let mut raw_line = Line::from(vec![Span::raw("My"), Span::raw(" text")]);
/// let mut styled_line = Line::from(vec![
/// Span::styled("My", style),
/// Span::styled(" text", style),
@ -156,7 +159,10 @@ impl<'a> Line<'a> {
/// # use ratatui::prelude::*;
/// let mut line = Line::from("Hi, what's up?");
/// assert_eq!(None, line.alignment);
/// assert_eq!(Some(Alignment::Right), line.alignment(Alignment::Right).alignment)
/// assert_eq!(
/// Some(Alignment::Right),
/// line.alignment(Alignment::Right).alignment
/// )
/// ```
pub fn alignment(self, alignment: Alignment) -> Self {
Self {

View file

@ -68,7 +68,10 @@ use crate::style::{Style, Styled};
/// use ratatui::prelude::*;
///
/// let span = Span::raw("test content").green().on_yellow().italic();
/// let span = Span::raw(String::from("test content")).green().on_yellow().italic();
/// let span = Span::raw(String::from("test content"))
/// .green()
/// .on_yellow()
/// .italic();
/// ```
///
/// [`Line`]: crate::text::Line
@ -212,12 +215,14 @@ impl<'a> Span<'a> {
///
/// ```rust
/// use std::iter::Iterator;
///
/// use ratatui::{prelude::*, text::StyledGrapheme};
///
/// let span = Span::styled("Test", Style::new().green().italic());
/// let style = Style::new().red().on_yellow();
/// assert_eq!(
/// span.styled_graphemes(style).collect::<Vec<StyledGrapheme>>(),
/// span.styled_graphemes(style)
/// .collect::<Vec<StyledGrapheme>>(),
/// vec![
/// StyledGrapheme::new("T", Style::new().green().on_yellow().italic()),
/// StyledGrapheme::new("e", Style::new().green().on_yellow().italic()),

View file

@ -13,7 +13,9 @@ use crate::style::Style;
/// ```rust
/// use ratatui::prelude::*;
///
/// let style = Style::default().fg(Color::Yellow).add_modifier(Modifier::ITALIC);
/// let style = Style::default()
/// .fg(Color::Yellow)
/// .add_modifier(Modifier::ITALIC);
///
/// // An initial two lines of `Text` built from a `&str`
/// let mut text = Text::from("The first line\nThe second line");
@ -62,7 +64,9 @@ impl<'a> Text<'a> {
///
/// ```rust
/// # use ratatui::prelude::*;
/// let style = Style::default().fg(Color::Yellow).add_modifier(Modifier::ITALIC);
/// let style = Style::default()
/// .fg(Color::Yellow)
/// .add_modifier(Modifier::ITALIC);
/// Text::styled("The first line\nThe second line", style);
/// Text::styled(String::from("The first line\nThe second line"), style);
/// ```
@ -107,7 +111,9 @@ impl<'a> Text<'a> {
///
/// ```rust
/// # use ratatui::prelude::*;
/// let style = Style::default().fg(Color::Yellow).add_modifier(Modifier::ITALIC);
/// let style = Style::default()
/// .fg(Color::Yellow)
/// .add_modifier(Modifier::ITALIC);
/// let mut raw_text = Text::raw("The first line\nThe second line");
/// let styled_text = Text::styled(String::from("The first line\nThe second line"), style);
/// assert_ne!(raw_text, styled_text);
@ -128,7 +134,9 @@ impl<'a> Text<'a> {
///
/// ```rust
/// # use ratatui::prelude::*;
/// let style = Style::default().fg(Color::Yellow).add_modifier(Modifier::ITALIC);
/// let style = Style::default()
/// .fg(Color::Yellow)
/// .add_modifier(Modifier::ITALIC);
/// let mut text = Text::styled("The first line\nThe second line", style);
///
/// text.reset_style();

View file

@ -29,14 +29,15 @@ use crate::{layout::Alignment, text::Line};
/// ```
/// use ratatui::{prelude::*, widgets::block::*};
///
/// Title::from(
/// Line::from(vec!["Q".white().underlined(), "uit".gray()])
/// );
/// Title::from(Line::from(vec!["Q".white().underlined(), "uit".gray()]));
/// ```
///
/// Complete example
/// ```
/// use ratatui::{prelude::*, widgets::{*, block::*}};
/// use ratatui::{
/// prelude::*,
/// widgets::{block::*, *},
/// };
///
/// Title::from("Title")
/// .position(Position::Top)
@ -69,11 +70,9 @@ pub struct Title<'a> {
/// # Example
///
/// ```
/// use ratatui::widgets::{*, block::*};
/// use ratatui::widgets::{block::*, *};
///
/// Block::new().title(
/// Title::from("title").position(Position::Bottom)
/// );
/// Block::new().title(Title::from("title").position(Position::Bottom));
/// ```
#[derive(Debug, Default, Display, EnumString, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Position {

View file

@ -130,6 +130,7 @@ pub trait Widget {
///
/// ```rust,no_run
/// use std::io;
///
/// use ratatui::{backend::TestBackend, prelude::*, widgets::*};
///
/// // Let's say we have some events to display.
@ -139,7 +140,7 @@ pub trait Widget {
/// // `state` is the state that can be modified by the UI. It stores the index of the selected
/// // item as well as the offset computed during the previous draw call (used to implement
/// // natural scrolling).
/// state: ListState
/// state: ListState,
/// }
///
/// impl Events {
@ -199,16 +200,17 @@ pub trait Widget {
/// # let backend = TestBackend::new(5, 5);
/// # let mut terminal = Terminal::new(backend).unwrap();
///
/// let mut events = Events::new(vec![
/// String::from("Item 1"),
/// String::from("Item 2")
/// ]);
/// let mut events = Events::new(vec![String::from("Item 1"), String::from("Item 2")]);
///
/// loop {
/// terminal.draw(|f| {
/// // The items managed by the application are transformed to something
/// // that is understood by ratatui.
/// let items: Vec<ListItem>= events.items.iter().map(|i| ListItem::new(i.as_str())).collect();
/// let items: Vec<ListItem> = events
/// .items
/// .iter()
/// .map(|i| ListItem::new(i.as_str()))
/// .collect();
/// // The `List` widget is then built with those items.
/// let list = List::new(items);
/// // Finally the widget is rendered using the associated state. `events.state` is

View file

@ -220,7 +220,10 @@ impl Padding {
///
/// You may also use multiple titles like in the following:
/// ```
/// use ratatui::{prelude::*, widgets::{*, block::*}};
/// use ratatui::{
/// prelude::*,
/// widgets::{block::*, *},
/// };
///
/// Block::default()
/// .title("Title 1")
@ -301,7 +304,10 @@ impl<'a> Block<'a> {
/// the leftover space)
/// - Two titles with the same alignment (notice the left titles are separated)
/// ```
/// use ratatui::{prelude::*, widgets::{*, block::*}};
/// use ratatui::{
/// prelude::*,
/// widgets::{block::*, *},
/// };
///
/// Block::default()
/// .title("Title") // By default in the top left corner
@ -344,7 +350,10 @@ impl<'a> Block<'a> {
/// This example aligns all titles in the center except the "right" title which explicitly sets
/// [`Alignment::Right`].
/// ```
/// use ratatui::{prelude::*, widgets::{*, block::*}};
/// use ratatui::{
/// prelude::*,
/// widgets::{block::*, *},
/// };
///
/// Block::default()
/// // This title won't be aligned in the center
@ -374,7 +383,10 @@ impl<'a> Block<'a> {
/// This example positions all titles on the bottom except the "top" title which explicitly sets
/// [`Position::Top`].
/// ```
/// use ratatui::{prelude::*, widgets::{*, block::*}};
/// use ratatui::{
/// prelude::*,
/// widgets::{block::*, *},
/// };
///
/// Block::default()
/// // This title won't be aligned in the center
@ -455,7 +467,10 @@ impl<'a> Block<'a> {
///
/// ```
/// # use ratatui::{prelude::*, widgets::*};
/// Block::default().title("Block").borders(Borders::ALL).border_type(BorderType::Rounded);
/// Block::default()
/// .title("Block")
/// .borders(Borders::ALL)
/// .border_type(BorderType::Rounded);
/// // Renders
/// // ╭Block╮
/// // │ │

View file

@ -457,7 +457,13 @@ impl<'a> Context<'a> {
/// ```
/// use ratatui::{prelude::*, widgets::canvas::*};
///
/// let ctx = Context::new(100, 100, [-180.0, 180.0], [-90.0, 90.0], symbols::Marker::Braille);
/// let ctx = Context::new(
/// 100,
/// 100,
/// [-180.0, 180.0],
/// [-90.0, 90.0],
/// symbols::Marker::Braille,
/// );
/// ```
pub fn new(
width: u16,
@ -554,7 +560,10 @@ impl<'a> Context<'a> {
/// # Examples
///
/// ```
/// use ratatui::{style::Color, widgets::{*, canvas::*}};
/// use ratatui::{
/// style::Color,
/// widgets::{canvas::*, *},
/// };
///
/// Canvas::default()
/// .block(Block::default().title("Canvas").borders(Borders::ALL))
@ -563,7 +572,7 @@ impl<'a> Context<'a> {
/// .paint(|ctx| {
/// ctx.draw(&Map {
/// resolution: MapResolution::High,
/// color: Color::White
/// color: Color::White,
/// });
/// ctx.layer();
/// ctx.draw(&Line {
@ -578,7 +587,7 @@ impl<'a> Context<'a> {
/// y: 20.0,
/// width: 10.0,
/// height: 10.0,
/// color: Color::Red
/// color: Color::Red,
/// });
/// });
/// ```
@ -666,10 +675,18 @@ where
/// ```
/// use ratatui::{prelude::*, widgets::canvas::*};
///
/// Canvas::default().marker(symbols::Marker::Braille).paint(|ctx| {});
/// Canvas::default().marker(symbols::Marker::HalfBlock).paint(|ctx| {});
/// Canvas::default().marker(symbols::Marker::Dot).paint(|ctx| {});
/// Canvas::default().marker(symbols::Marker::Block).paint(|ctx| {});
/// Canvas::default()
/// .marker(symbols::Marker::Braille)
/// .paint(|ctx| {});
/// Canvas::default()
/// .marker(symbols::Marker::HalfBlock)
/// .paint(|ctx| {});
/// Canvas::default()
/// .marker(symbols::Marker::Dot)
/// .paint(|ctx| {});
/// Canvas::default()
/// .marker(symbols::Marker::Block)
/// .paint(|ctx| {});
/// ```
pub fn marker(mut self, marker: symbols::Marker) -> Canvas<'a, F> {
self.marker = marker;

View file

@ -279,16 +279,32 @@ struct ChartLayout {
/// ];
/// Chart::new(datasets)
/// .block(Block::default().title("Chart"))
/// .x_axis(Axis::default()
/// .x_axis(
/// Axis::default()
/// .title(Span::styled("X Axis", Style::default().fg(Color::Red)))
/// .style(Style::default().fg(Color::White))
/// .bounds([0.0, 10.0])
/// .labels(["0.0", "5.0", "10.0"].iter().cloned().map(Span::from).collect()))
/// .y_axis(Axis::default()
/// .labels(
/// ["0.0", "5.0", "10.0"]
/// .iter()
/// .cloned()
/// .map(Span::from)
/// .collect(),
/// ),
/// )
/// .y_axis(
/// Axis::default()
/// .title(Span::styled("Y Axis", Style::default().fg(Color::Red)))
/// .style(Style::default().fg(Color::White))
/// .bounds([0.0, 10.0])
/// .labels(["0.0", "5.0", "10.0"].iter().cloned().map(Span::from).collect()));
/// .labels(
/// ["0.0", "5.0", "10.0"]
/// .iter()
/// .cloned()
/// .map(Span::from)
/// .collect(),
/// ),
/// );
/// ```
#[derive(Debug, Default, Clone, PartialEq)]
pub struct Chart<'a> {
@ -352,14 +368,10 @@ impl<'a> Chart<'a> {
///
/// ```
/// # use ratatui::{prelude::*, widgets::*};
/// let constraints = (
/// Constraint::Ratio(1, 3),
/// Constraint::Ratio(1, 4)
/// );
/// let constraints = (Constraint::Ratio(1, 3), Constraint::Ratio(1, 4));
/// // Hide the legend when either its width is greater than 33% of the total widget width
/// // or if its height is greater than 25% of the total widget height.
/// let _chart: Chart = Chart::new(vec![])
/// .hidden_legend_constraints(constraints);
/// let _chart: Chart = Chart::new(vec![]).hidden_legend_constraints(constraints);
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
pub fn hidden_legend_constraints(mut self, constraints: (Constraint, Constraint)) -> Chart<'a> {
@ -376,8 +388,7 @@ impl<'a> Chart<'a> {
///
/// ```
/// # use ratatui::widgets::{Chart, LegendPosition};
/// let _chart: Chart = Chart::new(vec![])
/// .legend_position(Some(LegendPosition::TopLeft));
/// let _chart: Chart = Chart::new(vec![]).legend_position(Some(LegendPosition::TopLeft));
/// ```
pub fn legend_position(mut self, position: Option<LegendPosition>) -> Chart<'a> {
self.legend_position = position;

View file

@ -452,7 +452,7 @@ impl<'a> List<'a> {
/// # use ratatui::{prelude::*, widgets::*};
/// let list = List::new([
/// Text::styled("Item 1", Style::default().red()),
/// Text::styled("Item 2", Style::default().red())
/// Text::styled("Item 2", Style::default().red()),
/// ]);
/// ```
///

View file

@ -29,16 +29,14 @@ fn get_line_offset(line_width: u16, text_area_width: u16, alignment: Alignment)
/// let text = vec![
/// Line::from(vec![
/// Span::raw("First"),
/// Span::styled("line",Style::new().green().italic()),
/// Span::styled("line", Style::new().green().italic()),
/// ".".into(),
/// ]),
/// Line::from("Second line".red()),
/// "Third line".into(),
/// ];
/// Paragraph::new(text)
/// .block(Block::new()
/// .title("Paragraph")
/// .borders(Borders::ALL))
/// .block(Block::new().title("Paragraph").borders(Borders::ALL))
/// .style(Style::new().white().on_black())
/// .alignment(Alignment::Center)
/// .wrap(Wrap { trim: true });
@ -66,9 +64,11 @@ pub struct Paragraph<'a> {
/// ```
/// use ratatui::{prelude::*, widgets::*};
///
/// let bullet_points = Text::from(r#"Some indented points:
/// let bullet_points = Text::from(
/// r#"Some indented points:
/// - First thing goes here and is long so that it wraps
/// - Here is another point that is long enough to wrap"#);
/// - Here is another point that is long enough to wrap"#,
/// );
///
/// // With leading spaces trimmed (window width of 30 chars):
/// Paragraph::new(bullet_points.clone()).wrap(Wrap { trim: true });
@ -108,10 +108,8 @@ impl<'a> Paragraph<'a> {
/// let paragraph = Paragraph::new("Hello, world!");
/// let paragraph = Paragraph::new(String::from("Hello, world!"));
/// let paragraph = Paragraph::new(Text::raw("Hello, world!"));
/// let paragraph = Paragraph::new(
/// Text::styled("Hello, world!", Style::default()));
/// let paragraph = Paragraph::new(
/// Line::from(vec!["Hello, ".into(), "world!".red()]));
/// let paragraph = Paragraph::new(Text::styled("Hello, world!", Style::default()));
/// let paragraph = Paragraph::new(Line::from(vec!["Hello, ".into(), "world!".red()]));
/// ```
pub fn new<T>(text: T) -> Paragraph<'a>
where
@ -134,9 +132,7 @@ impl<'a> Paragraph<'a> {
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// let paragraph = Paragraph::new("Hello, world!")
/// .block(Block::default()
/// .title("Paragraph")
/// .borders(Borders::ALL));
/// .block(Block::default().title("Paragraph").borders(Borders::ALL));
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
pub fn block(mut self, block: Block<'a>) -> Paragraph<'a> {
@ -153,8 +149,7 @@ impl<'a> Paragraph<'a> {
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// let paragraph = Paragraph::new("Hello, world!")
/// .style(Style::new().red().on_white());
/// let paragraph = Paragraph::new("Hello, world!").style(Style::new().red().on_white());
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
pub fn style(mut self, style: Style) -> Paragraph<'a> {
@ -170,8 +165,7 @@ impl<'a> Paragraph<'a> {
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// let paragraph = Paragraph::new("Hello, world!")
/// .wrap(Wrap { trim: true });
/// let paragraph = Paragraph::new("Hello, world!").wrap(Wrap { trim: true });
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
pub fn wrap(mut self, wrap: Wrap) -> Paragraph<'a> {
@ -205,8 +199,7 @@ impl<'a> Paragraph<'a> {
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// let paragraph = Paragraph::new("Hello World")
/// .alignment(Alignment::Center);
/// let paragraph = Paragraph::new("Hello World").alignment(Alignment::Center);
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
pub fn alignment(mut self, alignment: Alignment) -> Paragraph<'a> {

View file

@ -150,7 +150,11 @@ pub enum ScrollbarOrientation {
///
/// let vertical_scroll = 0; // from app state
///
/// let items = vec![Line::from("Item 1"), Line::from("Item 2"), Line::from("Item 3")];
/// let items = vec![
/// Line::from("Item 1"),
/// Line::from("Item 2"),
/// Line::from("Item 3"),
/// ];
/// let paragraph = Paragraph::new(items.clone())
/// .scroll((vertical_scroll as u16, 0))
/// .block(Block::new().borders(Borders::RIGHT)); // to show a background for the scrollbar
@ -163,12 +167,14 @@ pub enum ScrollbarOrientation {
///
/// let area = frame.size();
/// frame.render_widget(paragraph, area);
/// frame.render_stateful_widget(scrollbar,
/// frame.render_stateful_widget(
/// scrollbar,
/// area.inner(&Margin {
/// vertical: 1,
/// horizontal: 0,
/// }), // using a inner vertical margin of 1 unit makes the scrollbar inside the block
/// &mut scrollbar_state);
/// &mut scrollbar_state,
/// );
/// # }
/// ```
#[derive(Debug, Clone, Eq, PartialEq, Hash)]

View file

@ -58,30 +58,27 @@ use crate::{
///
/// let rows = [Row::new(vec!["Cell1", "Cell2", "Cell3"])];
/// // Columns widths are constrained in the same way as Layout...
/// let widths = [Constraint::Length(5), Constraint::Length(5), Constraint::Length(10)];
/// let widths = [
/// Constraint::Length(5),
/// Constraint::Length(5),
/// Constraint::Length(10),
/// ];
/// let table = Table::new(rows, widths)
///
/// // ...and they can be separated by a fixed spacing.
/// .column_spacing(1)
///
/// // You can set the style of the entire Table.
/// .style(Style::new().blue())
///
/// // It has an optional header, which is simply a Row always visible at the top.
/// .header(
/// Row::new(vec!["Col1", "Col2", "Col3"])
/// .style(Style::new().bold())
/// // To add space between the header and the rest of the rows, specify the margin
/// .bottom_margin(1)
/// .bottom_margin(1),
/// )
///
/// // As any other widget, a Table can be wrapped in a Block.
/// .block(Block::default().title("Table"))
///
///
/// // The selected row and its content can also be styled.
/// .highlight_style(Style::new().reversed())
///
/// // ...and potentially show a symbol in front of the selection.
/// .highlight_symbol(">>");
/// ```
@ -95,8 +92,7 @@ use crate::{
/// let row = Row::new(vec!["Row11", "Row12", "Row13"]);
///
/// // You can style the entire row.
/// let row = Row::new(vec!["Row21", "Row22", "Row23"])
/// .style(Style::new().red());
/// let row = Row::new(vec!["Row21", "Row22", "Row23"]).style(Style::new().red());
///
/// // If you need more control over the styling, create Cells directly
/// let row = Row::new(vec![
@ -104,7 +100,7 @@ use crate::{
/// Cell::from("Row32").style(Style::default().fg(Color::Yellow)),
/// Cell::from(Line::from(vec![
/// Span::raw("Row"),
/// Span::styled("33", Style::default().fg(Color::Green))
/// Span::styled("33", Style::default().fg(Color::Green)),
/// ])),
/// ]);
///
@ -113,7 +109,8 @@ use crate::{
/// Cell::from("Row\n41"),
/// Cell::from("Row\n42"),
/// Cell::from("Row\n43"),
/// ]).height(2);
/// ])
/// .height(2);
/// ```
///
/// Cells can be created from anything that can be converted to [`Text`]. See [`Cell`] for more
@ -127,7 +124,7 @@ use crate::{
/// Cell::from(Span::styled("styled span", Style::new().red()));
/// Cell::from(Line::from(vec![
/// Span::raw("a vec of "),
/// Span::styled("spans", Style::new().bold())
/// Span::styled("spans", Style::new().bold()),
/// ]));
/// Cell::from(Text::from("text"));
/// ```
@ -139,7 +136,11 @@ use crate::{
/// use ratatui::{prelude::*, widgets::*};
///
/// let rows = [Row::new(vec!["Cell1", "Cell2", "Cell3"])];
/// let widths = [Constraint::Length(5), Constraint::Length(5), Constraint::Length(10)];
/// let widths = [
/// Constraint::Length(5),
/// Constraint::Length(5),
/// Constraint::Length(10),
/// ];
/// let table = Table::new(rows, widths).red().italic();
/// ```
///
@ -236,6 +237,7 @@ pub struct Table<'a> {
///
/// ```rust
/// use std::borrow::Cow;
///
/// use ratatui::{prelude::*, widgets::*};
///
/// Row::new(vec![
@ -273,13 +275,14 @@ pub struct Row<'a> {
///
/// ```rust
/// use std::borrow::Cow;
///
/// use ratatui::{prelude::*, widgets::*};
///
/// Cell::from("simple string");
/// Cell::from(Span::from("span"));
/// Cell::from(Line::from(vec![
/// Span::raw("a vec of "),
/// Span::styled("spans", Style::default().add_modifier(Modifier::BOLD))
/// Span::styled("spans", Style::default().add_modifier(Modifier::BOLD)),
/// ]));
/// Cell::from(Text::from("a text"));
/// Cell::from(Text::from(Cow::Borrowed("hello")));
@ -445,7 +448,10 @@ impl<'a> Table<'a> {
///
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// let header = Row::new(vec![Cell::from("Header Cell 1"), Cell::from("Header Cell 2")]);
/// let header = Row::new(vec![
/// Cell::from("Header Cell 1"),
/// Cell::from("Header Cell 2"),
/// ]);
/// let table = Table::default().header(header);
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
@ -669,7 +675,11 @@ impl<'a> Row<'a> {
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// let row = Row::new(vec!["Cell 1", "Cell 2", "Cell 3"]);
/// let row = Row::new(vec![Cell::new("Cell 1"), Cell::new("Cell 2"), Cell::new("Cell 3")]);
/// let row = Row::new(vec![
/// Cell::new("Cell 1"),
/// Cell::new("Cell 2"),
/// Cell::new("Cell 3"),
/// ]);
/// ```
pub fn new<T>(cells: T) -> Self
where
@ -695,7 +705,11 @@ impl<'a> Row<'a> {
/// ```rust
/// # use ratatui::{prelude::*, widgets::*};
/// let row = Row::default().cells(vec!["Cell 1", "Cell 2", "Cell 3"]);
/// let row = Row::default().cells(vec![Cell::new("Cell 1"), Cell::new("Cell 2"), Cell::new("Cell 3")]);
/// let row = Row::default().cells(vec![
/// Cell::new("Cell 1"),
/// Cell::new("Cell 2"),
/// Cell::new("Cell 3"),
/// ]);
/// ```
#[must_use = "method moves the value of self and returns the modified value"]
pub fn cells<T>(mut self, cells: T) -> Self
@ -790,7 +804,7 @@ impl<'a> Cell<'a> {
/// Cell::new(Span::from("span"));
/// Cell::new(Line::from(vec![
/// Span::raw("a vec of "),
/// Span::styled("spans", Style::default().add_modifier(Modifier::BOLD))
/// Span::styled("spans", Style::default().add_modifier(Modifier::BOLD)),
/// ]));
/// Cell::new(Text::from("a text"));
/// ```
@ -818,7 +832,7 @@ impl<'a> Cell<'a> {
/// Cell::default().content(Span::from("span"));
/// Cell::default().content(Line::from(vec![
/// Span::raw("a vec of "),
/// Span::styled("spans", Style::new().bold())
/// Span::styled("spans", Style::new().bold()),
/// ]));
/// Cell::default().content(Text::from("a text"));
/// ```