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