sgr_const/lib.rs
1//! A macro to generate SGR (Set Graphic Rendition) control sequences for [ECMA-48] compatible terminals.
2//!
3//! # Examples
4//!
5//! The general syntax is:
6//! ```text
7//! [visibity] <name> = <attribute> [| attributes...];
8//! ```
9//!
10//! You can specify multiple constants at once,
11//! as well as add attributes or doc comments to each:
12//!
13//! ```rust
14//! sgr_const::sgr_const! {
15//! /// Error styling. Should be flashy.
16//! STYLE_ERROR = Bold | BlackFg | RedBg;
17//! STYLE_WARN = Bold | YellowFg;
18//! STYLE_INFO = Bold | CyanFg;
19//! STYLE_DEBUG = MagentaFg;
20//! #[allow(unused)]
21//! STYLE_TRACE = GreenFg;
22//! STYLE_NONE = Reset;
23//! }
24//!
25//! # fn main() {
26//! assert_eq!(STYLE_ERROR, "\x1b[1;30;41m");
27//! assert_eq!(STYLE_WARN, "\x1b[1;33m");
28//! assert_eq!(STYLE_INFO, "\x1b[1;36m");
29//! assert_eq!(STYLE_DEBUG, "\x1b[35m");
30//! assert_eq!(STYLE_TRACE, "\x1b[32m");
31//! assert_eq!(STYLE_NONE, "\x1b[0m");
32//! # }
33//! ```
34//!
35//! [ECMA-48]: https://www.ecma-international.org/publications/standards/Ecma-048.htm
36
37#![no_std]
38
39#[macro_export]
40macro_rules! sgr_const {
41 // SGR attribute name to parameter value lookup.
42 (@sgr Reset) => { 0 };
43
44 (@sgr Bold) => { 1 };
45 (@sgr Dim) => { 2 };
46 (@sgr Italics) => { 3 };
47 (@sgr Underline) => { 4 };
48 (@sgr Blink) => { 5 };
49 (@sgr Negative) => { 7 };
50
51 (@sgr NoBold) => { 22 };
52 (@sgr NoItalics) => { 23 };
53 (@sgr NoUnderline) => { 24 };
54 (@sgr NoBlink) => { 25 };
55 (@sgr NoNegative) => { 27 };
56
57 (@sgr BlackFg) => { 30 };
58 (@sgr RedFg) => { 31 };
59 (@sgr GreenFg) => { 32 };
60 (@sgr YellowFg) => { 33 };
61 (@sgr BlueFg) => { 34 };
62 (@sgr MagentaFg) => { 35 };
63 (@sgr CyanFg) => { 36 };
64 (@sgr WhiteFg) => { 37 };
65
66 (@sgr ResetFg) => { 39 };
67
68 (@sgr BlackBg) => { 40 };
69 (@sgr RedBg) => { 41 };
70 (@sgr GreenBg) => { 42 };
71 (@sgr YellowBg) => { 43 };
72 (@sgr BlueBg) => { 44 };
73 (@sgr MegantaBg) => { 45 };
74 (@sgr CyanBg) => { 46 };
75 (@sgr WhiteBg) => { 47 };
76
77 (@sgr ResetBg) => { 49 };
78
79 // Take unseperated list of expressions, throw them into `concat!`.
80 (@collect $($strs:expr)*) => { concat!("\x1b[", $($strs),*, "m") };
81
82 // Entry.
83 {
84 $(
85 $(#[$($attr:meta)+])*
86 $vis:vis $name:ident = $($sgr:ident)|+;
87 )*
88 } => {
89 $(
90 $(#[$($attr)+])*
91 $vis const $name: &'static str = $crate::sgr_const!(@collect $($crate::sgr_const!(@sgr $sgr))";"+);
92 )*
93 };
94}