forked from jmacdonald/amp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreflow.rs
241 lines (207 loc) · 7.61 KB
/
reflow.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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
use super::*;
/// Encapsulate reflow logic for buffer manipulation.
pub struct Reflow<'a> {
buf: &'a mut Buffer,
rng: Range,
txt: String,
lmt: usize,
}
impl<'a> Reflow<'a> {
/// Create a reflow instance, where buffer and range determine the target,
/// and the limit is the maximum length of a line, regardless of prefixes.
pub fn new(
buf: &'a mut Buffer, rng: Range, lmt: usize
) -> std::result::Result<Self, Error> {
let txt = match buf.read(&rng) {
Some(t) => t,
None => bail!("Selection is invalid."),
};
Ok(Self { buf, rng, txt, lmt })
}
pub fn apply(mut self) -> std::result::Result<(), Error> {
let prefix = self.infer_prefix()?;
let jtxt = self.justify_str(&prefix);
self.buf.delete_range(self.rng.clone());
self.buf.cursor.move_to(self.rng.start());
self.buf.insert(jtxt);
Ok(())
}
fn infer_prefix(&self) -> std::result::Result<String, Error> {
match self.txt.split_whitespace().next() {
Some(n) => if n.chars().next().unwrap().is_alphanumeric() {
Ok("".to_string())
} else {
Ok(n.to_string())
},
None => bail!("Selection is empty."),
}
}
fn justify_str(&mut self, prefix: &str) -> String {
let txt = self.buf.read(&self.rng).unwrap();
let mut limit = self.lmt;
let mut justified = String::with_capacity(txt.len());
let mut pars = txt.split("\n\n").peekable();
let mut space_delims = ["".to_string(), " ".to_string(), "\n".to_string()];
if prefix != "" {
space_delims[0] += prefix;
space_delims[0] += " ";
space_delims[2] += prefix;
space_delims[2] += " ";
limit -= prefix.len() + 1;
}
while let Some(par) = pars.next() {
let mut words = par.split_whitespace();
let mut len = 0;
let mut first = true;
while let Some(word) = words.next() {
if word == prefix {
continue;
}
len += word.len();
let over = len > limit;
let u_over = over as usize;
let idx = (!first as usize) * u_over + !first as usize;
justified += &space_delims[idx];
justified += word;
// if we're over, set the length to 0, otherwise increment it
// properly. This just does that mith multiplication by 0 instead of
// branching.
len = (len + 1) * (1 - u_over) + (word.len() + 1) * u_over;
first = false;
}
if pars.peek().is_some() {
justified += "\n\n"; // add back the paragraph break.
}
}
justified
}
}
#[cfg(test)]
mod tests {
use super::*;
// as simple as it gets: one character words for easy debugging.
#[test]
fn justify_simple() {
let mut buf = Buffer::new();
buf.insert("\
a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a\n");
Reflow::new(
&mut buf,
Range::new(
scribe::buffer::Position { line: 0, offset: 0 },
scribe::buffer::Position { line: 1, offset: 0 },
),
80,
).unwrap().apply().unwrap();
assert_eq!(
buf.data(),
"\
a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a
a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a"
);
}
#[test]
fn justify_paragraph() {
let mut buf = Buffer::new();
buf.insert("\
these are words to be used as demos for the thing that this is. this is text \
reflowing and justification over a few lines. this is just filler text in case \
it wasn't obvious.\n"
);
Reflow::new(
&mut buf,
Range::new(
scribe::buffer::Position { line: 0, offset: 0 },
scribe::buffer::Position { line: 1, offset: 0 },
),
80,
).unwrap().apply().unwrap();
assert_eq!(
buf.data(), "\
these are words to be used as demos for the thing that this is. this is text
reflowing and justification over a few lines. this is just filler text in case
it wasn't obvious."
);
}
#[test]
fn justify_multiple_pars() {
let mut buf = Buffer::new();
buf.insert("\
Here's more filler text! So fun fact of the day, I was trying to just copy paste \
some lorem ipsum to annoy my latin student friends, but honestly it broke the \
M-q 'justify' function in emacs, which makes it a bit difficult to work with. \
Overall, it's just not that great with code!
Fun fact of the day number two, writing random paragraphs of text is honestly \
taking way more effort than I anticipated, and I deeply apologize for the lack \
of sanity and coherence here!
Fun fact of the day number three is that I spent three hours getting this to not \
branch. There is no way that that micro-optimization will actually save three \
hours worth of time, but I did it anyway for no good reason!\n"
);
Reflow::new(
&mut buf,
Range::new(
scribe::buffer::Position { line: 0, offset: 0 },
scribe::buffer::Position { line: 5, offset: 0 },
),
80,
).unwrap().apply().unwrap();
assert_eq!(
buf.data(), "\
Here's more filler text! So fun fact of the day, I was trying to just copy paste
some lorem ipsum to annoy my latin student friends, but honestly it broke the
M-q 'justify' function in emacs, which makes it a bit difficult to work with.
Overall, it's just not that great with code!
Fun fact of the day number two, writing random paragraphs of text is honestly
taking way more effort than I anticipated, and I deeply apologize for the lack
of sanity and coherence here!
Fun fact of the day number three is that I spent three hours getting this to not
branch. There is no way that that micro-optimization will actually save three
hours worth of time, but I did it anyway for no good reason!"
);
}
#[test]
fn justify_simple_prefix() {
let mut buf = Buffer::new();
buf.insert("\
# a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a\n"
);
Reflow::new(
&mut buf,
Range::new(
scribe::buffer::Position { line: 0, offset: 0 },
scribe::buffer::Position { line: 1, offset: 0 },
),
80,
).unwrap().apply().unwrap();
assert_eq!(
buf.data(), "\
# a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a
# a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a"
);
}
#[test]
fn justify_paragraph_prefix() {
let mut buf = Buffer::new();
buf.insert("\
// filler text meant
// to do stuff and things that end up with text nicely \
wrappped around a comment delimiter such as the double slashes in c-style \
languages.\n"
);
Reflow::new(
&mut buf,
Range::new(
scribe::buffer::Position { line: 0, offset: 0 },
scribe::buffer::Position { line: 2, offset: 0 },
),
80,
).unwrap().apply().unwrap();
assert_eq!(
buf.data(), "\
// filler text meant to do stuff and things that end up with text nicely
// wrappped around a comment delimiter such as the double slashes in c-style
// languages.",
);
}
}