我正在try 从stdin读取输入(Markdown),然后以一种对终端友好的方式输出,并使用彩色输出.为此,我使用termbg个 crate 确定航站楼的主题(亮/暗).
要读取通过管道传输到我的程序的内容,我使用以下命令:
fn read_from_stdin() -> String {
let stdin = io::stdin();
let stdin_lock = stdin.lock();
let buffer = stdin_lock.lines().filter_map(|l| l.ok()).fold("".to_string(), |acc, s| { format!("{acc}\n{s}")});
return buffer;
}
在我读完stdin之后,我try 找出终端使用的是亮主题还是暗主题,使用的是termbg
箱:
let timeout = std::time::Duration::from_millis(100);
let theme = termbg::theme(timeout);
match theme {
Ok(t) => {
println!("Detected theme: {:?}", t);
},
_ => {
println!("No theme detected!"); // happens with tmux
}
}
The problem is, termbg is trying to determine the theme by using OSC queries that apparently require the use of stdin/stdout.
Determining the right theme only works if I replace the reading from stdin with a hardcoded string and if I won't pass anything in via pipe.
So, apparently, termbg needs a clean and empty stdin to work properly but I can't find a way to make sure it gets that.
How can I make sure that stdin is empty and in a state that termbg can work with before attempting to determine the right terminal theme?个
完整的可测试代码:
use std::{io::{self, BufRead}}
fn main() => io::Result<()> {
let buffer = read_from_stdin();
let timeout = std::time::Duration::from_millis(100);
let theme = termbg::theme(timeout);
match theme { // Mostly outputs wrong theme or none at all
Ok(t) => {
println!("Detected theme: {:?}", t);
},
_ => {
println!("No theme detected!"); // happens with tmux
}
}
// Parsing and formatting the markdown read from stdin would follow here but isn't relevant
return Ok(());
}
fn read_from_stdin() -> String {
let stdin = io::stdin();
let stdin_lock = stdin.lock();
let buffer = stdin_lock.lines().filter_map(|l| l.ok()).fold("".to_string(), |acc, s| { format!("{acc}\n{s}")});
return buffer;
}