]> git.lizzy.rs Git - rust.git/blob - library/term/src/lib.rs
rustdoc: link to stable/beta docs consistently in documentation
[rust.git] / library / term / src / lib.rs
1 //! Terminal formatting library.
2 //!
3 //! This crate provides the `Terminal` trait, which abstracts over an [ANSI
4 //! Terminal][ansi] to provide color printing, among other things. There are two
5 //! implementations, the `TerminfoTerminal`, which uses control characters from
6 //! a [terminfo][ti] database, and `WinConsole`, which uses the [Win32 Console
7 //! API][win].
8 //!
9 //! # Examples
10 //!
11 //! ```no_run
12 //! # #![feature(rustc_private)]
13 //! extern crate term;
14 //! use std::io::prelude::*;
15 //!
16 //! fn main() {
17 //!     let mut t = term::stdout().unwrap();
18 //!
19 //!     t.fg(term::color::GREEN).unwrap();
20 //!     write!(t, "hello, ").unwrap();
21 //!
22 //!     t.fg(term::color::RED).unwrap();
23 //!     writeln!(t, "world!").unwrap();
24 //!
25 //!     assert!(t.reset().unwrap());
26 //! }
27 //! ```
28 //!
29 //! [ansi]: https://en.wikipedia.org/wiki/ANSI_escape_code
30 //! [win]: https://docs.microsoft.com/en-us/windows/console/character-mode-applications
31 //! [ti]: https://en.wikipedia.org/wiki/Terminfo
32
33 #![doc(html_playground_url = "https://play.rust-lang.org/", test(attr(deny(warnings))))]
34 #![deny(missing_docs)]
35 #![cfg_attr(windows, feature(libc))]
36
37 use std::io::prelude::*;
38 use std::io::{self, Stderr, Stdout};
39
40 pub use terminfo::TerminfoTerminal;
41 #[cfg(windows)]
42 pub use win::WinConsole;
43
44 pub mod terminfo;
45
46 #[cfg(windows)]
47 mod win;
48
49 /// Alias for stdout terminals.
50 pub type StdoutTerminal = dyn Terminal<Output = Stdout> + Send;
51 /// Alias for stderr terminals.
52 pub type StderrTerminal = dyn Terminal<Output = Stderr> + Send;
53
54 #[cfg(not(windows))]
55 /// Returns a Terminal wrapping stdout, or None if a terminal couldn't be
56 /// opened.
57 pub fn stdout() -> Option<Box<StdoutTerminal>> {
58     TerminfoTerminal::new(io::stdout()).map(|t| Box::new(t) as Box<StdoutTerminal>)
59 }
60
61 #[cfg(windows)]
62 /// Returns a Terminal wrapping stdout, or None if a terminal couldn't be
63 /// opened.
64 pub fn stdout() -> Option<Box<StdoutTerminal>> {
65     TerminfoTerminal::new(io::stdout())
66         .map(|t| Box::new(t) as Box<StdoutTerminal>)
67         .or_else(|| WinConsole::new(io::stdout()).ok().map(|t| Box::new(t) as Box<StdoutTerminal>))
68 }
69
70 #[cfg(not(windows))]
71 /// Returns a Terminal wrapping stderr, or None if a terminal couldn't be
72 /// opened.
73 pub fn stderr() -> Option<Box<StderrTerminal>> {
74     TerminfoTerminal::new(io::stderr()).map(|t| Box::new(t) as Box<StderrTerminal>)
75 }
76
77 #[cfg(windows)]
78 /// Returns a Terminal wrapping stderr, or None if a terminal couldn't be
79 /// opened.
80 pub fn stderr() -> Option<Box<StderrTerminal>> {
81     TerminfoTerminal::new(io::stderr())
82         .map(|t| Box::new(t) as Box<StderrTerminal>)
83         .or_else(|| WinConsole::new(io::stderr()).ok().map(|t| Box::new(t) as Box<StderrTerminal>))
84 }
85
86 /// Terminal color definitions
87 #[allow(missing_docs)]
88 pub mod color {
89     /// Number for a terminal color
90     pub type Color = u32;
91
92     pub const BLACK: Color = 0;
93     pub const RED: Color = 1;
94     pub const GREEN: Color = 2;
95     pub const YELLOW: Color = 3;
96     pub const BLUE: Color = 4;
97     pub const MAGENTA: Color = 5;
98     pub const CYAN: Color = 6;
99     pub const WHITE: Color = 7;
100
101     pub const BRIGHT_BLACK: Color = 8;
102     pub const BRIGHT_RED: Color = 9;
103     pub const BRIGHT_GREEN: Color = 10;
104     pub const BRIGHT_YELLOW: Color = 11;
105     pub const BRIGHT_BLUE: Color = 12;
106     pub const BRIGHT_MAGENTA: Color = 13;
107     pub const BRIGHT_CYAN: Color = 14;
108     pub const BRIGHT_WHITE: Color = 15;
109 }
110
111 /// Terminal attributes for use with term.attr().
112 ///
113 /// Most attributes can only be turned on and must be turned off with term.reset().
114 /// The ones that can be turned off explicitly take a boolean value.
115 /// Color is also represented as an attribute for convenience.
116 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
117 pub enum Attr {
118     /// Bold (or possibly bright) mode
119     Bold,
120     /// Dim mode, also called faint or half-bright. Often not supported
121     Dim,
122     /// Italics mode. Often not supported
123     Italic(bool),
124     /// Underline mode
125     Underline(bool),
126     /// Blink mode
127     Blink,
128     /// Standout mode. Often implemented as Reverse, sometimes coupled with Bold
129     Standout(bool),
130     /// Reverse mode, inverts the foreground and background colors
131     Reverse,
132     /// Secure mode, also called invis mode. Hides the printed text
133     Secure,
134     /// Convenience attribute to set the foreground color
135     ForegroundColor(color::Color),
136     /// Convenience attribute to set the background color
137     BackgroundColor(color::Color),
138 }
139
140 /// A terminal with similar capabilities to an ANSI Terminal
141 /// (foreground/background colors etc).
142 pub trait Terminal: Write {
143     /// The terminal's output writer type.
144     type Output: Write;
145
146     /// Sets the foreground color to the given color.
147     ///
148     /// If the color is a bright color, but the terminal only supports 8 colors,
149     /// the corresponding normal color will be used instead.
150     ///
151     /// Returns `Ok(true)` if the color was set, `Ok(false)` otherwise, and `Err(e)`
152     /// if there was an I/O error.
153     fn fg(&mut self, color: color::Color) -> io::Result<bool>;
154
155     /// Sets the background color to the given color.
156     ///
157     /// If the color is a bright color, but the terminal only supports 8 colors,
158     /// the corresponding normal color will be used instead.
159     ///
160     /// Returns `Ok(true)` if the color was set, `Ok(false)` otherwise, and `Err(e)`
161     /// if there was an I/O error.
162     fn bg(&mut self, color: color::Color) -> io::Result<bool>;
163
164     /// Sets the given terminal attribute, if supported. Returns `Ok(true)`
165     /// if the attribute was supported, `Ok(false)` otherwise, and `Err(e)` if
166     /// there was an I/O error.
167     fn attr(&mut self, attr: Attr) -> io::Result<bool>;
168
169     /// Returns `true` if the given terminal attribute is supported.
170     fn supports_attr(&self, attr: Attr) -> bool;
171
172     /// Resets all terminal attributes and colors to their defaults.
173     ///
174     /// Returns `Ok(true)` if the terminal was reset, `Ok(false)` otherwise, and `Err(e)` if there
175     /// was an I/O error.
176     ///
177     /// *Note: This does not flush.*
178     ///
179     /// That means the reset command may get buffered so, if you aren't planning on doing anything
180     /// else that might flush stdout's buffer (e.g., writing a line of text), you should flush after
181     /// calling reset.
182     fn reset(&mut self) -> io::Result<bool>;
183
184     /// Gets an immutable reference to the stream inside
185     fn get_ref(&self) -> &Self::Output;
186
187     /// Gets a mutable reference to the stream inside
188     fn get_mut(&mut self) -> &mut Self::Output;
189
190     /// Returns the contained stream, destroying the `Terminal`
191     fn into_inner(self) -> Self::Output
192     where
193         Self: Sized;
194 }