term/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//! # Usage
20//!
21//! This crate is [on crates.io](https://crates.io/crates/term) and can be
22//! used by adding `term` to the dependencies in your project's `Cargo.toml`.
23//!
24//! ```toml
25//! [dependencies]
26//!
27//! term = "0.4.6"
28//! ```
29//!
30//! and this to your crate root:
31//!
32//! ```rust
33//! extern crate term;
34//! ```
35//!
36//! # Examples
37//!
38//! ```no_run
39//! extern crate term;
40//! use std::io::prelude::*;
41//!
42//! fn main() {
43//! let mut t = term::stdout().unwrap();
44//!
45//! t.fg(term::color::GREEN).unwrap();
46//! write!(t, "hello, ").unwrap();
47//!
48//! t.fg(term::color::RED).unwrap();
49//! writeln!(t, "world!").unwrap();
50//!
51//! t.reset().unwrap();
52//! }
53//! ```
54//!
55//! [ansi]: https://en.wikipedia.org/wiki/ANSI_escape_code
56//! [win]: http://msdn.microsoft.com/en-us/library/windows/desktop/ms682010%28v=vs.85%29.aspx
57//! [ti]: https://en.wikipedia.org/wiki/Terminfo
58
59#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
60 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
61 html_root_url = "https://stebalien.github.io/doc/term/term/", test(attr(deny(warnings))))]
62#![deny(missing_docs)]
63#![cfg_attr(test, deny(warnings))]
64
65extern crate byteorder;
66
67use std::io::prelude::*;
68
69pub use terminfo::TerminfoTerminal;
70#[cfg(windows)]
71pub use win::WinConsole;
72
73use std::io::{self, Stderr, Stdout};
74
75pub mod terminfo;
76
77#[cfg(windows)]
78mod win;
79
80/// Alias for stdout terminals.
81pub type StdoutTerminal = Terminal<Output = Stdout> + Send;
82/// Alias for stderr terminals.
83pub type StderrTerminal = Terminal<Output = Stderr> + Send;
84
85#[cfg(not(windows))]
86/// Return a Terminal wrapping stdout, or None if a terminal couldn't be
87/// opened.
88pub fn stdout() -> Option<Box<StdoutTerminal>> {
89 TerminfoTerminal::new(io::stdout()).map(|t| Box::new(t) as Box<StdoutTerminal>)
90}
91
92#[cfg(windows)]
93/// Return a Terminal wrapping stdout, or None if a terminal couldn't be
94/// opened.
95pub fn stdout() -> Option<Box<StdoutTerminal>> {
96 TerminfoTerminal::new(io::stdout())
97 .map(|t| Box::new(t) as Box<StdoutTerminal>)
98 .or_else(|| {
99 WinConsole::new(io::stdout())
100 .ok()
101 .map(|t| Box::new(t) as Box<StdoutTerminal>)
102 })
103}
104
105#[cfg(not(windows))]
106/// Return a Terminal wrapping stderr, or None if a terminal couldn't be
107/// opened.
108pub fn stderr() -> Option<Box<StderrTerminal>> {
109 TerminfoTerminal::new(io::stderr()).map(|t| Box::new(t) as Box<StderrTerminal>)
110}
111
112#[cfg(windows)]
113/// Return a Terminal wrapping stderr, or None if a terminal couldn't be
114/// opened.
115pub fn stderr() -> Option<Box<StderrTerminal>> {
116 TerminfoTerminal::new(io::stderr())
117 .map(|t| Box::new(t) as Box<StderrTerminal>)
118 .or_else(|| {
119 WinConsole::new(io::stderr())
120 .ok()
121 .map(|t| Box::new(t) as Box<StderrTerminal>)
122 })
123}
124
125/// Terminal color definitions
126#[allow(missing_docs)]
127pub mod color {
128 /// Number for a terminal color
129 pub type Color = u32;
130
131 pub const BLACK: Color = 0;
132 pub const RED: Color = 1;
133 pub const GREEN: Color = 2;
134 pub const YELLOW: Color = 3;
135 pub const BLUE: Color = 4;
136 pub const MAGENTA: Color = 5;
137 pub const CYAN: Color = 6;
138 pub const WHITE: Color = 7;
139
140 pub const BRIGHT_BLACK: Color = 8;
141 pub const BRIGHT_RED: Color = 9;
142 pub const BRIGHT_GREEN: Color = 10;
143 pub const BRIGHT_YELLOW: Color = 11;
144 pub const BRIGHT_BLUE: Color = 12;
145 pub const BRIGHT_MAGENTA: Color = 13;
146 pub const BRIGHT_CYAN: Color = 14;
147 pub const BRIGHT_WHITE: Color = 15;
148}
149
150/// Terminal attributes for use with term.attr().
151///
152/// Most attributes can only be turned on and must be turned off with term.reset().
153/// The ones that can be turned off explicitly take a boolean value.
154/// Color is also represented as an attribute for convenience.
155#[derive(Debug, PartialEq, Hash, Eq, Copy, Clone)]
156pub enum Attr {
157 /// Bold (or possibly bright) mode
158 Bold,
159 /// Dim mode, also called faint or half-bright. Often not supported
160 Dim,
161 /// Italics mode. Often not supported
162 Italic(bool),
163 /// Underline mode
164 Underline(bool),
165 /// Blink mode
166 Blink,
167 /// Standout mode. Often implemented as Reverse, sometimes coupled with Bold
168 Standout(bool),
169 /// Reverse mode, inverts the foreground and background colors
170 Reverse,
171 /// Secure mode, also called invis mode. Hides the printed text
172 Secure,
173 /// Convenience attribute to set the foreground color
174 ForegroundColor(color::Color),
175 /// Convenience attribute to set the background color
176 BackgroundColor(color::Color),
177}
178
179/// An error arising from interacting with the terminal.
180#[derive(Debug)]
181pub enum Error {
182 /// Indicates an error from any underlying IO
183 Io(io::Error),
184 /// Indicates an error during terminfo parsing
185 TerminfoParsing(terminfo::Error),
186 /// Indicates an error expanding a parameterized string from the terminfo database
187 ParameterizedExpansion(terminfo::parm::Error),
188 /// Indicates that the terminal does not support the requested operation.
189 NotSupported,
190 /// Indicates that the `TERM` environment variable was unset, and thus we were unable to detect
191 /// which terminal we should be using.
192 TermUnset,
193 /// Indicates that we were unable to find a terminfo entry for the requested terminal.
194 TerminfoEntryNotFound,
195 /// Indicates that the cursor could not be moved to the requested position.
196 CursorDestinationInvalid,
197 /// Indicates that the terminal does not support displaying the requested color.
198 ///
199 /// This is like `NotSupported`, but more specific.
200 ColorOutOfRange,
201 #[doc(hidden)]
202 /// Please don't match against this - if you do, we can't promise we won't break your crate
203 /// with a semver-compliant version bump.
204 __Nonexhaustive,
205}
206
207// manually implemented because std::io::Error does not implement Eq/PartialEq
208impl std::cmp::PartialEq for Error {
209 fn eq(&self, other: &Error) -> bool {
210 use Error::*;
211 match *self {
212 Io(_) => false,
213 TerminfoParsing(ref inner1) => match *other {
214 TerminfoParsing(ref inner2) => inner1 == inner2,
215 _ => false,
216 },
217 ParameterizedExpansion(ref inner1) => match *other {
218 ParameterizedExpansion(ref inner2) => inner1 == inner2,
219 _ => false,
220 },
221 NotSupported => match *other {
222 NotSupported => true,
223 _ => false,
224 },
225 TermUnset => match *other {
226 TermUnset => true,
227 _ => false,
228 },
229 TerminfoEntryNotFound => match *other {
230 TerminfoEntryNotFound => true,
231 _ => false,
232 },
233 CursorDestinationInvalid => match *other {
234 CursorDestinationInvalid => true,
235 _ => false,
236 },
237 ColorOutOfRange => match *other {
238 ColorOutOfRange => true,
239 _ => false,
240 },
241 __Nonexhaustive => match *other {
242 __Nonexhaustive => true,
243 _ => false,
244 },
245 }
246 }
247}
248
249/// The canonical `Result` type using this crate's Error type.
250pub type Result<T> = std::result::Result<T, Error>;
251
252impl std::fmt::Display for Error {
253 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
254 use std::error::Error;
255 if let ::Error::Io(ref e) = *self {
256 write!(f, "{}", e)
257 } else {
258 f.write_str(self.description())
259 }
260 }
261}
262
263impl std::error::Error for Error {
264 fn description(&self) -> &str {
265 use Error::*;
266 match *self {
267 Io(ref io) => io.description(),
268 TerminfoParsing(ref e) => e.description(),
269 ParameterizedExpansion(ref e) => e.description(),
270 NotSupported => "operation not supported by the terminal",
271 TermUnset => "TERM environment variable unset, unable to detect a terminal",
272 TerminfoEntryNotFound => "could not find a terminfo entry for this terminal",
273 CursorDestinationInvalid => "could not move cursor to requested position",
274 ColorOutOfRange => "color not supported by the terminal",
275 __Nonexhaustive => "placeholder variant that shouldn't be used",
276 }
277 }
278
279 fn cause(&self) -> Option<&std::error::Error> {
280 match *self {
281 Error::Io(ref io) => Some(io),
282 Error::TerminfoParsing(ref e) => Some(e),
283 Error::ParameterizedExpansion(ref e) => Some(e),
284 _ => None,
285 }
286 }
287}
288
289impl From<Error> for io::Error {
290 fn from(err: Error) -> io::Error {
291 let kind = match err {
292 Error::Io(ref e) => e.kind(),
293 _ => io::ErrorKind::Other,
294 };
295 io::Error::new(kind, err)
296 }
297}
298
299impl std::convert::From<io::Error> for Error {
300 fn from(val: io::Error) -> Self {
301 Error::Io(val)
302 }
303}
304
305impl std::convert::From<terminfo::Error> for Error {
306 fn from(val: terminfo::Error) -> Self {
307 Error::TerminfoParsing(val)
308 }
309}
310
311impl std::convert::From<terminfo::parm::Error> for Error {
312 fn from(val: terminfo::parm::Error) -> Self {
313 Error::ParameterizedExpansion(val)
314 }
315}
316
317/// A terminal with similar capabilities to an ANSI Terminal
318/// (foreground/background colors etc).
319pub trait Terminal: Write {
320 /// The terminal's output writer type.
321 type Output: Write;
322
323 /// Sets the foreground color to the given color.
324 ///
325 /// If the color is a bright color, but the terminal only supports 8 colors,
326 /// the corresponding normal color will be used instead.
327 ///
328 /// Returns `Ok(())` if the color change code was sent to the terminal, or `Err(e)` if there
329 /// was an error.
330 fn fg(&mut self, color: color::Color) -> Result<()>;
331
332 /// Sets the background color to the given color.
333 ///
334 /// If the color is a bright color, but the terminal only supports 8 colors,
335 /// the corresponding normal color will be used instead.
336 ///
337 /// Returns `Ok(())` if the color change code was sent to the terminal, or `Err(e)` if there
338 /// was an error.
339 fn bg(&mut self, color: color::Color) -> Result<()>;
340
341 /// Sets the given terminal attribute, if supported. Returns `Ok(())` if the attribute is
342 /// supported and was sent to the terminal, or `Err(e)` if there was an error or the attribute
343 /// wasn't supported.
344 fn attr(&mut self, attr: Attr) -> Result<()>;
345
346 /// Returns whether the given terminal attribute is supported.
347 fn supports_attr(&self, attr: Attr) -> bool;
348
349 /// Resets all terminal attributes and colors to their defaults.
350 ///
351 /// Returns `Ok(())` if the reset code was printed, or `Err(e)` if there was an error.
352 ///
353 /// *Note: This does not flush.*
354 ///
355 /// That means the reset command may get buffered so, if you aren't planning on doing anything
356 /// else that might flush stdout's buffer (e.g. writing a line of text), you should flush after
357 /// calling reset.
358 fn reset(&mut self) -> Result<()>;
359
360 /// Returns true if reset is supported.
361 fn supports_reset(&self) -> bool;
362
363 /// Returns true if color is fully supported.
364 ///
365 /// If this function returns `true`, `bg`, `fg`, and `reset` will never
366 /// return `Err(Error::NotSupported)`.
367 fn supports_color(&self) -> bool;
368
369 /// Moves the cursor up one line.
370 ///
371 /// Returns `Ok(())` if the cursor movement code was printed, or `Err(e)` if there was an
372 /// error.
373 fn cursor_up(&mut self) -> Result<()>;
374
375 /// Deletes the text from the cursor location to the end of the line.
376 ///
377 /// Returns `Ok(())` if the deletion code was printed, or `Err(e)` if there was an error.
378 fn delete_line(&mut self) -> Result<()>;
379
380 /// Moves the cursor to the left edge of the current line.
381 ///
382 /// Returns `Ok(true)` if the deletion code was printed, or `Err(e)` if there was an error.
383 fn carriage_return(&mut self) -> Result<()>;
384
385 /// Gets an immutable reference to the stream inside
386 fn get_ref(&self) -> &Self::Output;
387
388 /// Gets a mutable reference to the stream inside
389 fn get_mut(&mut self) -> &mut Self::Output;
390
391 /// Returns the contained stream, destroying the `Terminal`
392 fn into_inner(self) -> Self::Output
393 where
394 Self: Sized;
395}