1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
//! Support for running TeX REPLs

use super::script;
use std::sync::Arc;
use texlang::traits::*;
use texlang::*;
use texlang_common as common;

pub struct RunOptions<'a> {
    pub prompt: &'a str,
    pub help: &'a str,
}

#[derive(Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Component {
    help: String,
    quit_requested: bool,
}

#[cfg(feature = "repl")]
pub mod run {
    use super::*;
    use linefeed::{Interface, ReadResult};

    pub fn run<S: HasComponent<script::Component> + HasComponent<Component>>(
        vm: &mut vm::VM<S>,
        opts: RunOptions,
    ) {
        let c = HasComponent::<Component>::component_mut(&mut vm.state);
        c.help = opts.help.into();
        c.quit_requested = false;
        let reader = Interface::new("").unwrap();

        reader.set_prompt(opts.prompt).unwrap();

        let mut names: Vec<String> = vm.get_commands_as_map_slow().into_keys().collect();
        names.sort();
        let mut num_names = names.len();
        let a = Arc::new(ControlSequenceCompleter { names });
        reader.set_completer(a);
        script::set_io_writer(vm, std::io::stdout());
        while let ReadResult::Input(input) = reader.read_line().unwrap() {
            reader.add_history(input.clone());

            vm.clear_sources();
            vm.push_source("".to_string(), input).unwrap();
            match script::run(vm) {
                Ok(()) => (),
                Err(err) => {
                    if HasComponent::<Component>::component(&vm.state).quit_requested {
                        return;
                    }
                    println!("{err}");
                    continue;
                }
            };
            // TODO: better new line handling in the REPL
            println!();
            if vm.commands_map.len() != num_names {
                let mut names: Vec<String> = vm.get_commands_as_map_slow().into_keys().collect();
                names.sort();
                num_names = names.len();
                let a = Arc::new(ControlSequenceCompleter { names });
                reader.set_completer(a);
            }
        }
    }

    struct ControlSequenceCompleter {
        names: Vec<String>,
    }

    impl<Term: linefeed::Terminal> linefeed::Completer<Term> for ControlSequenceCompleter {
        fn complete(
            &self,
            word: &str,
            prompter: &linefeed::Prompter<Term>,
            start: usize,
            _end: usize,
        ) -> Option<Vec<linefeed::Completion>> {
            if prompter.buffer()[..start].ends_with('\\') {
                return None;
            }
            let mut completions = Vec::new();
            for name in &self.names {
                if name.starts_with(word) {
                    completions.push(linefeed::Completion {
                        completion: name.clone(),
                        display: None,
                        suffix: linefeed::Suffix::Default,
                    });
                }
            }
            Some(completions)
        }
    }
}

/// Get the `\exit` command.
///
/// This exits the REPL.
pub fn get_exit<S: HasComponent<Component>>() -> command::BuiltIn<S> {
    command::BuiltIn::new_execution(
        |_: token::Token, input: &mut vm::ExecutionInput<S>| -> command::Result<()> {
            HasComponent::<Component>::component_mut(input.state_mut()).quit_requested = true;
            Err(error::SimpleEndOfInputError::new(
                input.vm(),
                "quitting Texcraft REPL. This error should never be seen!",
            )
            .into())
        },
    )
}

/// Get the `\help` command.
///
/// This prints help text for the REPL.
pub fn get_help<S: HasComponent<Component> + common::HasLogging>() -> command::BuiltIn<S> {
    command::BuiltIn::new_execution(
        |token: token::Token, input: &mut vm::ExecutionInput<S>| -> command::Result<()> {
            let help = HasComponent::<Component>::component(input.state())
                .help
                .clone();
            match writeln![input.state().terminal_out().borrow_mut(), "{help}"] {
                Ok(_) => Ok(()),
                Err(err) => Err(error::SimpleTokenError::new(
                    input.vm(),
                    token,
                    format!["failed to write help text: {err}"],
                )
                .into()),
            }
        },
    )
}

/// Get the `\doc` command.
///
/// This prints the documentation for a TeX command.
pub fn get_doc<S: TexlangState + common::HasLogging>() -> command::BuiltIn<S> {
    command::BuiltIn::new_execution(
        |token: token::Token, input: &mut vm::ExecutionInput<S>| -> command::Result<()> {
            let target = token::CommandRef::parse(input)?;
            let name = target.to_string(input.vm().cs_name_interner());
            let doc = match input.commands_map().get_command_slow(&target) {
                None => format!["Unknown command {name}"],
                Some(cmd) => match cmd.doc() {
                    None => format!["No documentation available for the {name} command"],
                    Some(doc) => format!["{name}  {doc}"],
                },
            };
            match writeln![input.state().terminal_out().borrow_mut(), "{doc}"] {
                Ok(_) => Ok(()),
                Err(err) => Err(error::SimpleTokenError::new(
                    input.vm(),
                    token,
                    format!["failed to write doc text: {err}"],
                )
                .into()),
            }
        },
    )
}