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