]> git.lizzy.rs Git - rust.git/blob - src/libterm/lib.rs
doc: remove incomplete sentence
[rust.git] / src / libterm / lib.rs
1 // Copyright 2013-2014 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 implementations,
15 //! the `TerminfoTerminal`, which uses control characters from a
16 //! [terminfo][ti] database, and `WinConsole`, which uses the [Win32 Console
17 //! API][win].
18 //!
19 //! # Examples
20 //!
21 //! ```no_run
22 //! extern crate term;
23 //!
24 //! fn main() {
25 //!     let mut t = term::stdout().unwrap();
26 //!
27 //!     t.fg(term::color::GREEN).unwrap();
28 //!     (write!(t, "hello, ")).unwrap();
29 //!
30 //!     t.fg(term::color::RED).unwrap();
31 //!     (writeln!(t, "world!")).unwrap();
32 //!
33 //!     t.reset().unwrap();
34 //! }
35 //! ```
36 //!
37 //! [ansi]: https://en.wikipedia.org/wiki/ANSI_escape_code
38 //! [win]: http://msdn.microsoft.com/en-us/library/windows/desktop/ms682010%28v=vs.85%29.aspx
39 //! [ti]: https://en.wikipedia.org/wiki/Terminfo
40
41 #![crate_name = "term"]
42 #![experimental = "use the crates.io `term` library instead"]
43 #![crate_type = "rlib"]
44 #![crate_type = "dylib"]
45 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
46        html_favicon_url = "http://www.rust-lang.org/favicon.ico",
47        html_root_url = "http://doc.rust-lang.org/nightly/",
48        html_playground_url = "http://play.rust-lang.org/")]
49
50 #![allow(unknown_features)]
51 #![feature(macro_rules, phase, slicing_syntax, globs)]
52
53 #![deny(missing_docs)]
54
55 #[phase(plugin, link)] extern crate log;
56
57 pub use terminfo::TerminfoTerminal;
58 #[cfg(windows)]
59 pub use win::WinConsole;
60
61 use std::io::IoResult;
62
63 pub mod terminfo;
64
65 #[cfg(windows)]
66 mod win;
67
68 /// A hack to work around the fact that `Box<Writer + Send>` does not
69 /// currently implement `Writer`.
70 pub struct WriterWrapper {
71     wrapped: Box<Writer + Send>,
72 }
73
74 impl Writer for WriterWrapper {
75     #[inline]
76     fn write(&mut self, buf: &[u8]) -> IoResult<()> {
77         self.wrapped.write(buf)
78     }
79
80     #[inline]
81     fn flush(&mut self) -> IoResult<()> {
82         self.wrapped.flush()
83     }
84 }
85
86 #[cfg(not(windows))]
87 /// Return a Terminal wrapping stdout, or None if a terminal couldn't be
88 /// opened.
89 pub fn stdout() -> Option<Box<Terminal<WriterWrapper> + Send>> {
90     TerminfoTerminal::new(WriterWrapper {
91         wrapped: box std::io::stdout() as Box<Writer + Send>,
92     })
93 }
94
95 #[cfg(windows)]
96 /// Return a Terminal wrapping stdout, or None if a terminal couldn't be
97 /// opened.
98 pub fn stdout() -> Option<Box<Terminal<WriterWrapper> + Send>> {
99     let ti = TerminfoTerminal::new(WriterWrapper {
100         wrapped: box std::io::stdout() as Box<Writer + Send>,
101     });
102
103     match ti {
104         Some(t) => Some(t),
105         None => {
106             WinConsole::new(WriterWrapper {
107                 wrapped: box std::io::stdout() as Box<Writer + Send>,
108             })
109         }
110     }
111 }
112
113 #[cfg(not(windows))]
114 /// Return a Terminal wrapping stderr, or None if a terminal couldn't be
115 /// opened.
116 pub fn stderr() -> Option<Box<Terminal<WriterWrapper> + Send>> {
117     TerminfoTerminal::new(WriterWrapper {
118         wrapped: box std::io::stderr() as Box<Writer + Send>,
119     })
120 }
121
122 #[cfg(windows)]
123 /// Return a Terminal wrapping stderr, or None if a terminal couldn't be
124 /// opened.
125 pub fn stderr() -> Option<Box<Terminal<WriterWrapper> + Send>> {
126     let ti = TerminfoTerminal::new(WriterWrapper {
127         wrapped: box std::io::stderr() as Box<Writer + Send>,
128     });
129
130     match ti {
131         Some(t) => Some(t),
132         None => {
133             WinConsole::new(WriterWrapper {
134                 wrapped: box std::io::stderr() as Box<Writer + Send>,
135             })
136         }
137     }
138 }
139
140
141 /// Terminal color definitions
142 pub mod color {
143     /// Number for a terminal color
144     pub type Color = u16;
145
146     pub const BLACK:   Color = 0u16;
147     pub const RED:     Color = 1u16;
148     pub const GREEN:   Color = 2u16;
149     pub const YELLOW:  Color = 3u16;
150     pub const BLUE:    Color = 4u16;
151     pub const MAGENTA: Color = 5u16;
152     pub const CYAN:    Color = 6u16;
153     pub const WHITE:   Color = 7u16;
154
155     pub const BRIGHT_BLACK:   Color = 8u16;
156     pub const BRIGHT_RED:     Color = 9u16;
157     pub const BRIGHT_GREEN:   Color = 10u16;
158     pub const BRIGHT_YELLOW:  Color = 11u16;
159     pub const BRIGHT_BLUE:    Color = 12u16;
160     pub const BRIGHT_MAGENTA: Color = 13u16;
161     pub const BRIGHT_CYAN:    Color = 14u16;
162     pub const BRIGHT_WHITE:   Color = 15u16;
163 }
164
165 /// Terminal attributes
166 pub mod attr {
167     pub use self::Attr::*;
168
169     /// Terminal attributes for use with term.attr().
170     ///
171     /// Most attributes can only be turned on and must be turned off with term.reset().
172     /// The ones that can be turned off explicitly take a boolean value.
173     /// Color is also represented as an attribute for convenience.
174     #[deriving(Copy)]
175     pub enum Attr {
176         /// Bold (or possibly bright) mode
177         Bold,
178         /// Dim mode, also called faint or half-bright. Often not supported
179         Dim,
180         /// Italics mode. Often not supported
181         Italic(bool),
182         /// Underline mode
183         Underline(bool),
184         /// Blink mode
185         Blink,
186         /// Standout mode. Often implemented as Reverse, sometimes coupled with Bold
187         Standout(bool),
188         /// Reverse mode, inverts the foreground and background colors
189         Reverse,
190         /// Secure mode, also called invis mode. Hides the printed text
191         Secure,
192         /// Convenience attribute to set the foreground color
193         ForegroundColor(super::color::Color),
194         /// Convenience attribute to set the background color
195         BackgroundColor(super::color::Color)
196     }
197 }
198
199 /// A terminal with similar capabilities to an ANSI Terminal
200 /// (foreground/background colors etc).
201 pub trait Terminal<T: Writer>: Writer {
202     /// Sets the foreground color to the given color.
203     ///
204     /// If the color is a bright color, but the terminal only supports 8 colors,
205     /// the corresponding normal color will be used instead.
206     ///
207     /// Returns `Ok(true)` if the color was set, `Ok(false)` otherwise, and `Err(e)`
208     /// if there was an I/O error.
209     fn fg(&mut self, color: color::Color) -> IoResult<bool>;
210
211     /// Sets the background color to the given color.
212     ///
213     /// If the color is a bright color, but the terminal only supports 8 colors,
214     /// the corresponding normal color will be used instead.
215     ///
216     /// Returns `Ok(true)` if the color was set, `Ok(false)` otherwise, and `Err(e)`
217     /// if there was an I/O error.
218     fn bg(&mut self, color: color::Color) -> IoResult<bool>;
219
220     /// Sets the given terminal attribute, if supported.  Returns `Ok(true)`
221     /// if the attribute was supported, `Ok(false)` otherwise, and `Err(e)` if
222     /// there was an I/O error.
223     fn attr(&mut self, attr: attr::Attr) -> IoResult<bool>;
224
225     /// Returns whether the given terminal attribute is supported.
226     fn supports_attr(&self, attr: attr::Attr) -> bool;
227
228     /// Resets all terminal attributes and color to the default.
229     /// Returns `Ok()`.
230     fn reset(&mut self) -> IoResult<()>;
231
232     /// Gets an immutable reference to the stream inside
233     fn get_ref<'a>(&'a self) -> &'a T;
234
235     /// Gets a mutable reference to the stream inside
236     fn get_mut<'a>(&'a mut self) -> &'a mut T;
237 }
238
239 /// A terminal which can be unwrapped.
240 pub trait UnwrappableTerminal<T: Writer>: Terminal<T> {
241     /// Returns the contained stream, destroying the `Terminal`
242     fn unwrap(self) -> T;
243 }