-
Notifications
You must be signed in to change notification settings - Fork 18
/
demo.rs
194 lines (167 loc) · 6.15 KB
/
demo.rs
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
extern crate linefeed;
extern crate rand;
use std::io;
use std::sync::Arc;
use std::thread;
use std::time::Duration;
use rand::{Rng, thread_rng};
use linefeed::{Interface, Prompter, ReadResult};
use linefeed::chars::escape_sequence;
use linefeed::command::COMMANDS;
use linefeed::complete::{Completer, Completion};
use linefeed::inputrc::parse_text;
use linefeed::terminal::Terminal;
const HISTORY_FILE: &str = "linefeed.hst";
fn main() -> io::Result<()> {
let interface = Arc::new(Interface::new("demo")?);
let mut thread_id = 0;
println!("This is the linefeed demo program.");
println!("Enter \"help\" for a list of commands.");
println!("Press Ctrl-D or enter \"quit\" to exit.");
println!("");
interface.set_completer(Arc::new(DemoCompleter));
interface.set_prompt("demo> ")?;
if let Err(e) = interface.load_history(HISTORY_FILE) {
if e.kind() == io::ErrorKind::NotFound {
println!("History file {} doesn't exist, not loading history.", HISTORY_FILE);
} else {
eprintln!("Could not load history file {}: {}", HISTORY_FILE, e);
}
}
while let ReadResult::Input(line) = interface.read_line()? {
if !line.trim().is_empty() {
interface.add_history_unique(line.clone());
}
let (cmd, args) = split_first_word(&line);
match cmd {
"help" => {
println!("linefeed demo commands:");
println!();
for &(cmd, help) in DEMO_COMMANDS {
println!(" {:15} - {}", cmd, help);
}
println!();
}
"bind" => {
let d = parse_text("<input>", args);
interface.evaluate_directives(d);
}
"get" => {
if let Some(var) = interface.get_variable(args) {
println!("{} = {}", args, var);
} else {
println!("no variable named `{}`", args);
}
}
"list-bindings" => {
for (seq, cmd) in interface.lock_reader().bindings() {
let seq = format!("\"{}\"", escape_sequence(seq));
println!("{:20}: {}", seq, cmd);
}
}
"list-commands" => {
for cmd in COMMANDS {
println!("{}", cmd);
}
}
"list-variables" => {
for (name, var) in interface.lock_reader().variables() {
println!("{:30} = {}", name, var);
}
}
"spawn-log-thread" => {
let my_thread_id = thread_id;
println!("Spawning log thread #{}", my_thread_id);
let iface = interface.clone();
thread::spawn(move || {
let mut rng = thread_rng();
let mut i = 0usize;
loop {
writeln!(iface, "[#{}] Concurrent message #{}",
my_thread_id, i).unwrap();
let wait_ms = rng.gen_range(1, 500);
thread::sleep(Duration::from_millis(wait_ms));
i += 1;
}
});
thread_id += 1;
}
"history" => {
let w = interface.lock_writer_erase()?;
for (i, entry) in w.history().enumerate() {
println!("{}: {}", i, entry);
}
}
"save-history" => {
if let Err(e) = interface.save_history(HISTORY_FILE) {
eprintln!("Could not save history file {}: {}", HISTORY_FILE, e);
} else {
println!("History saved to {}", HISTORY_FILE);
}
}
"quit" => break,
"set" => {
let d = parse_text("<input>", &line);
interface.evaluate_directives(d);
}
_ => println!("read input: {:?}", line)
}
}
println!("Goodbye.");
Ok(())
}
fn split_first_word(s: &str) -> (&str, &str) {
let s = s.trim();
match s.find(|ch: char| ch.is_whitespace()) {
Some(pos) => (&s[..pos], s[pos..].trim_start()),
None => (s, "")
}
}
static DEMO_COMMANDS: &[(&str, &str)] = &[
("bind", "Set bindings in inputrc format"),
("get", "Print the value of a variable"),
("help", "You're looking at it"),
("list-bindings", "List bound sequences"),
("list-commands", "List command names"),
("list-variables", "List variables"),
("spawn-log-thread", "Spawns a thread that concurrently logs messages"),
("history", "Print history"),
("save-history", "Write history to file"),
("quit", "Quit the demo"),
("set", "Assign a value to a variable"),
];
struct DemoCompleter;
impl<Term: Terminal> Completer<Term> for DemoCompleter {
fn complete(&self, word: &str, prompter: &Prompter<Term>,
start: usize, _end: usize) -> Option<Vec<Completion>> {
let line = prompter.buffer();
let mut words = line[..start].split_whitespace();
match words.next() {
// Complete command name
None => {
let mut compls = Vec::new();
for &(cmd, _) in DEMO_COMMANDS {
if cmd.starts_with(word) {
compls.push(Completion::simple(cmd.to_owned()));
}
}
Some(compls)
}
// Complete command parameters
Some("get") | Some("set") => {
if words.count() == 0 {
let mut res = Vec::new();
for (name, _) in prompter.variables() {
if name.starts_with(word) {
res.push(Completion::simple(name.to_owned()));
}
}
Some(res)
} else {
None
}
}
_ => None
}
}
}