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