| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
use codesnake::{Block, CodeWidth, Label, LineIndex}; |
| 5 |
use core::fmt::{self, Display, Formatter}; |
| 6 |
use yansi::{Color, Paint}; |
| 7 |
|
| 8 |
const SRC: &str = r#"(defun factorial (n) (if (zerop n) 1 |
| 9 |
(* n (factorial (1- n)))))"#; |
| 10 |
|
| 11 |
fn paint_html(f: &mut Formatter, color: &Color, s: &dyn Display) -> fmt::Result { |
| 12 |
if *color == Color::default() { |
| 13 |
write!(f, "{s}") |
| 14 |
} else { |
| 15 |
let mut color = format!("{color:?}"); |
| 16 |
color.make_ascii_lowercase(); |
| 17 |
write!(f, "<span class={color}>{s}</span>") |
| 18 |
} |
| 19 |
} |
| 20 |
|
| 21 |
fn paint_ansi(f: &mut Formatter, color: &Color, s: &dyn Display) -> fmt::Result { |
| 22 |
s.fg(*color).fmt(f) |
| 23 |
} |
| 24 |
|
| 25 |
fn main() { |
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
let html = std::env::args().skip(1).any(|arg| arg == "--html"); |
| 33 |
let idx = LineIndex::new(SRC); |
| 34 |
let paint = if html { paint_html } else { paint_ansi }; |
| 35 |
|
| 36 |
let labels = [ |
| 37 |
Label::new(1..6).with_style(Color::Red), |
| 38 |
Label::new(7..16) |
| 39 |
.with_text("this function ...") |
| 40 |
.with_style(Color::Green), |
| 41 |
Label::new(21..70) |
| 42 |
.with_text("... is defined by this") |
| 43 |
.with_style(Color::Blue), |
| 44 |
Label::new(71..71) |
| 45 |
.with_text("(and here is EOF)") |
| 46 |
.with_style(Color::Yellow), |
| 47 |
]; |
| 48 |
let block = Block::new(&idx, labels).unwrap(); |
| 49 |
let block = block.with_paint(paint).map_code(|s| { |
| 50 |
let s = s.replace('\t', " "); |
| 51 |
let w = unicode_width::UnicodeWidthStr::width(&*s); |
| 52 |
CodeWidth::new(s, core::cmp::max(w, 1)) |
| 53 |
}); |
| 54 |
|
| 55 |
let filename = from_fn(|f| paint(f, &Color::Red, &"[fac.lisp]")); |
| 56 |
println!("{}{filename}", block.prologue()); |
| 57 |
println!("{}", block.space_vert()); |
| 58 |
print!("{block}"); |
| 59 |
println!("{}", block.epilogue()); |
| 60 |
} |
| 61 |
|
| 62 |
|
| 63 |
fn from_fn<F: Fn(&mut Formatter) -> fmt::Result>(f: F) -> FromFn<F> { |
| 64 |
FromFn(f) |
| 65 |
} |
| 66 |
|
| 67 |
struct FromFn<F>(F); |
| 68 |
|
| 69 |
impl<F: Fn(&mut Formatter) -> fmt::Result> Display for FromFn<F> { |
| 70 |
fn fmt(&self, f: &mut Formatter) -> fmt::Result { |
| 71 |
(self.0)(f) |
| 72 |
} |
| 73 |
} |