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