forked from CeleritasCelery/rune
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheditfns.rs
215 lines (191 loc) · 6.74 KB
/
editfns.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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
//! Buffer editing utilities.
use crate::core::{
env::{ArgSlice, Env},
gc::{Context, Rt},
object::{GcObj, Object},
};
use anyhow::{bail, ensure, Result};
use rune_macros::defun;
use std::{fmt::Write as _, io::Write};
#[defun]
fn message(format_string: &str, args: &[GcObj]) -> Result<String> {
let message = format(format_string, args)?;
println!("MESSAGE: {message}");
std::io::stdout().flush()?;
Ok(message)
}
defvar!(MESSAGE_NAME);
defvar!(MESSAGE_TYPE, "new message");
#[defun]
fn format(string: &str, objects: &[GcObj]) -> Result<String> {
let mut result = String::new();
let mut arguments = objects.iter();
let mut remaining = string;
let mut escaped = false;
let mut is_format_char = |c: char| {
if escaped {
escaped = false;
false
} else if c == '\\' {
escaped = true;
false
} else {
c == '%'
}
};
while let Some(start) = remaining.find(&mut is_format_char) {
result += &remaining[..start];
let Some(specifier) = remaining.as_bytes().get(start + 1) else {
bail!("Format string ends in middle of format specifier")
};
// "%%" inserts a single "%" in the output
if *specifier == b'%' {
result.push('%');
} else {
// TODO: currently handles all format types the same. Need to check the modifier characters.
let Some(val) = arguments.next() else {
bail!("Not enough arguments for format string")
};
match val.untag() {
Object::String(string) => write!(result, "{string}")?,
obj => write!(result, "{obj}")?,
}
}
remaining = &remaining[start + 2..];
}
result += remaining;
ensure!(arguments.next().is_none(), "Too many arguments for format string");
Ok(result)
}
#[defun]
fn format_message(string: &str, objects: &[GcObj]) -> Result<String> {
let formatted = format(string, objects)?;
// TODO: implement support for `text-quoting-style`.
Ok(formatted
.chars()
.map(|c| if matches!(c, '`' | '\'') { '"' } else { c })
.collect())
}
#[defun]
fn string_to_char(string: &str) -> char {
string.chars().next().unwrap_or('\0')
}
#[defun]
fn char_to_string(chr: u64) -> Result<String> {
let Some(chr) = std::char::from_u32(u32::try_from(chr)?) else {
bail!("Invalid character")
};
Ok(format!("{chr}"))
}
// TODO: this should not throw and error. Buffer will always be present.
#[defun]
pub(crate) fn insert(args: ArgSlice, env: &mut Rt<Env>, cx: &Context) -> Result<()> {
let env = &mut **env; // Deref into rooted type so we can split the borrow
let Some(buffer) = env.current_buffer.as_mut() else { bail!("No current buffer") };
let args = Rt::bind_slice(env.stack.arg_slice(args), cx);
for arg in args {
buffer.insert(*arg)?;
}
Ok(())
}
// TODO: this should not throw and error. Buffer will always be present.
#[defun]
pub(crate) fn goto_char(position: usize, env: &mut Rt<Env>) -> Result<()> {
let Some(buffer) = env.current_buffer.as_mut() else { bail!("No current buffer") };
buffer.text.set_cursor(position);
Ok(())
}
// TODO: this should not throw and error. Buffer will always be present.
#[defun]
pub(crate) fn point_max(env: &mut Rt<Env>) -> Result<usize> {
let Some(buffer) = env.current_buffer.as_mut() else { bail!("No current buffer") };
// TODO: Handle narrowing
Ok(buffer.text.len_chars() + 1)
}
// TODO: this should not throw and error. Buffer will always be present.
#[defun]
pub(crate) fn point_marker(env: &mut Rt<Env>) -> Result<usize> {
let Some(buffer) = env.current_buffer.as_mut() else { bail!("No current buffer") };
// TODO: Implement marker objects
Ok(buffer.text.cursor().chars())
}
// TODO: this should not throw and error. Buffer will always be present.
#[defun]
fn delete_region(start: usize, end: usize, env: &mut Rt<Env>) -> Result<()> {
let Some(buffer) = env.current_buffer.as_mut() else { bail!("No current buffer") };
buffer.delete(start, end);
Ok(())
}
#[defun]
fn bolp(env: &Rt<Env>) -> bool {
env.with_buffer(None, |b| {
let chars = b.text.cursor().chars();
chars == 0 || b.text.char_at(chars - 1).unwrap() == '\n'
})
.unwrap_or(false)
}
#[defun]
fn point(env: &Rt<Env>) -> usize {
env.with_buffer(None, |b| b.text.cursor().chars()).unwrap_or(0)
}
#[defun]
fn system_name() -> String {
hostname::get()
.expect("Failed to get hostname")
.into_string()
.expect("Failed to convert OsString to String")
}
#[cfg(test)]
mod test {
use crate::core::object::NIL;
use crate::{
buffer::{get_buffer_create, set_buffer},
core::gc::{Context, RootSet},
};
use rune_core::macros::root;
use super::*;
#[test]
fn test_format() {
assert_eq!(&format("%s", &[1.into()]).unwrap(), "1");
assert_eq!(&format("foo-%s", &[2.into()]).unwrap(), "foo-2");
assert_eq!(&format("%%", &[]).unwrap(), "%");
assert_eq!(&format("_%%_", &[]).unwrap(), "_%_");
assert_eq!(&format("foo-%s %s", &[3.into(), 4.into()]).unwrap(), "foo-3 4");
let sym = crate::core::env::sym::FUNCTION.into();
assert_eq!(&format("%s", &[sym]).unwrap(), "function");
assert!(&format("%s", &[]).is_err());
assert!(&format("%s", &[1.into(), 2.into()]).is_err());
assert!(format("`%s' %s%s%s", &[0.into(), 1.into(), 2.into(), 3.into()]).is_ok());
}
#[test]
fn test_insert() {
let roots = &RootSet::default();
let cx = &mut Context::new(roots);
root!(env, Env::default(), cx);
let buffer = get_buffer_create(cx.add("test_insert"), Some(NIL), cx).unwrap();
set_buffer(buffer, env, cx).unwrap();
cx.garbage_collect(true);
env.stack.push(104);
env.stack.push(101);
env.stack.push(108);
env.stack.push(108);
env.stack.push(111);
insert(ArgSlice::new(5), env, cx).unwrap();
assert_eq!(env.current_buffer.as_ref().unwrap(), "hello");
}
#[test]
fn test_delete_region() {
let roots = &RootSet::default();
let cx = &mut Context::new(roots);
root!(env, Env::default(), cx);
let buffer = get_buffer_create(cx.add("test_delete_region"), Some(NIL), cx).unwrap();
set_buffer(buffer, env, cx).unwrap();
cx.garbage_collect(true);
env.stack.push(cx.add("hello"));
env.stack.push(cx.add(" world"));
insert(ArgSlice::new(2), env, cx).unwrap();
assert_eq!(env.current_buffer.as_ref().unwrap(), "hello world");
delete_region(1, 3, env).unwrap();
assert_eq!(env.current_buffer.as_ref().unwrap(), "hlo world");
}
}