use std::borrow::Cow;
use nu_ansi_term::{Color, Style};
use reedline::{
default_emacs_keybindings, ColumnarMenu, Completer, Emacs, FileBackedHistory, KeyCode,
KeyModifiers, MenuBuilder, Prompt, PromptEditMode, PromptHistorySearch,
PromptHistorySearchStatus, Reedline, ReedlineEvent, ReedlineMenu, Signal, Span, Suggestion,
};
use crate::corpus::CORPUS;
#[derive(Default)]
pub struct Session {
lines: Vec<String>,
seen: usize,
}
#[derive(Debug, PartialEq, Eq)]
pub enum Turn {
Output(Vec<String>),
Error(String),
}
impl Session {
pub fn new() -> Self {
Self::default()
}
pub fn source(&self) -> String {
self.lines.join("\n")
}
pub fn eval(&mut self, line: &str) -> Turn {
self.lines.push(line.to_string());
let src = self
.lines
.iter()
.map(|l| l.trim_end())
.filter(|l| *l != "\\end")
.collect::<Vec<_>>()
.join("\n");
match crate::run_messages_list(&src) {
Ok(msgs) => {
let new = msgs[self.seen.min(msgs.len())..].to_vec();
self.seen = msgs.len();
Turn::Output(new)
}
Err(e) => {
self.lines.pop();
Turn::Error(e.0)
}
}
}
}
pub fn run() -> Result<(), String> {
if unsafe { libc::isatty(0) } != 1 {
return run_piped();
}
crate::banner::print_banner(true);
let mut session = Session::new();
let history = dirs::home_dir()
.map(|h| h.join(".texrs").join("history"))
.and_then(|p| {
let _ = std::fs::create_dir_all(p.parent()?);
FileBackedHistory::with_file(2000, p).ok()
});
let completer = Box::new(PrimitiveCompleter);
let menu = Box::new(ColumnarMenu::default().with_name("completion_menu"));
let mut keybindings = default_emacs_keybindings();
keybindings.add_binding(
KeyModifiers::NONE,
KeyCode::Tab,
ReedlineEvent::UntilFound(vec![
ReedlineEvent::Menu("completion_menu".to_string()),
ReedlineEvent::MenuNext,
]),
);
let mut editor = Reedline::create()
.with_completer(completer)
.with_menu(ReedlineMenu::EngineCompleter(menu))
.with_edit_mode(Box::new(Emacs::new(keybindings)));
if let Some(h) = history {
editor = editor.with_history(Box::new(h));
}
let prompt = TexPrompt;
loop {
match editor.read_line(&prompt) {
Ok(Signal::Success(line)) => {
if line.trim().is_empty() {
continue;
}
match session.eval(&line) {
Turn::Output(msgs) => {
for m in msgs {
println!("{m}");
}
}
Turn::Error(e) => eprintln!("! {e}."),
}
}
Ok(Signal::CtrlC) => continue,
Ok(Signal::CtrlD) => break,
Ok(_) => continue,
Err(e) => return Err(format!("repl: {e}")),
}
}
Ok(())
}
fn run_piped() -> Result<(), String> {
use std::io::BufRead;
let mut session = Session::new();
for line in std::io::stdin().lock().lines() {
let line = line.map_err(|e| format!("repl: {e}"))?;
if line.trim().is_empty() {
continue;
}
match session.eval(&line) {
Turn::Output(msgs) => {
for m in msgs {
println!("{m}");
}
}
Turn::Error(e) => eprintln!("! {e}."),
}
}
Ok(())
}
struct PrimitiveCompleter;
impl Completer for PrimitiveCompleter {
fn complete(&mut self, line: &str, pos: usize) -> Vec<Suggestion> {
let head = &line[..pos.min(line.len())];
let start = head
.rfind('\\')
.unwrap_or_else(|| head.rfind(char::is_whitespace).map(|i| i + 1).unwrap_or(0));
let word = &head[start..];
CORPUS
.iter()
.filter(|(name, ..)| name.starts_with(word))
.map(|(name, chapter, doc, _example)| Suggestion {
value: (*name).to_string(),
description: Some(format!("{chapter} — {doc}")),
style: None,
extra: None,
span: Span::new(start, pos),
append_whitespace: false,
display_override: None,
match_indices: None,
})
.collect()
}
}
struct TexPrompt;
impl Prompt for TexPrompt {
fn render_prompt_left(&self) -> Cow<'_, str> {
Cow::Owned(
Style::new()
.fg(Color::Cyan)
.bold()
.paint("tex❯ ")
.to_string(),
)
}
fn render_prompt_right(&self) -> Cow<'_, str> {
Cow::Borrowed("")
}
fn render_prompt_indicator(&self, _mode: PromptEditMode) -> Cow<'_, str> {
Cow::Borrowed("")
}
fn render_prompt_multiline_indicator(&self) -> Cow<'_, str> {
Cow::Borrowed("... ")
}
fn render_prompt_history_search_indicator(
&self,
history_search: PromptHistorySearch,
) -> Cow<'_, str> {
let prefix = match history_search.status {
PromptHistorySearchStatus::Passing => "",
PromptHistorySearchStatus::Failing => "failing ",
};
Cow::Owned(format!(
"({prefix}reverse-search: {}) ",
history_search.term
))
}
}