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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
|
mod rope;
mod term;
use rope::Rope;
use std::ffi::{OsStr, OsString};
use std::io::{stdout, stdin, Write, Read};
use std::error::Error;
use std::path::Path;
use term::Key;
struct State {
buf: Rope,
row_start: usize,
cursor_row: usize,
cursor_col: usize,
line_offset: usize,
line_cols: usize,
}
fn parse_status_report(buf: &[u8]) -> Result<(usize, usize), Box<dyn Error>> {
let mut semicolon = 0;
for (i, &c) in buf.iter().enumerate() {
if c == b';' {
semicolon = i;
break;
}
}
if semicolon < 2 || semicolon == buf.len()-1 {
return Err(Box::from("invalid response"));
}
let row_str = std::str::from_utf8(&buf[2..semicolon])?;
let col_str = std::str::from_utf8(&buf[semicolon+1..buf.len()-1])?;
let row = row_str.parse::<usize>()?;
let col = col_str.parse::<usize>()?;
// Yuck... 1 indexing
return Ok((row-1, col-1));
}
impl State {
fn cursor_pos(&mut self) -> Result<(usize, usize), Box<dyn Error>> {
write!(stdout(), "\x1b[6n").map_err(|err| format!("cursor position: status report: {}", err))?;
stdout().flush().map_err(|err| format!("cursor position: status report: {}", err))?;
let mut buf = vec![0; 20];
let n = stdin().read(&mut buf).map_err(|err| format!("cursor position: read status report: {}", err))?;
buf.truncate(n);
let pos = parse_status_report(&buf).map_err(|_| format!("cursor position: invalid response: {}", String::from_utf8_lossy(&buf)))?;
return Ok(pos);
}
fn repaint_all(&mut self) -> Result<(), Box<dyn Error>> {
let size = term::size()?;
write!(stdout(), "\x1b[H\x1b[J")?;
for i in self.row_start..self.row_start+usize::from(size.ws_row) {
if i > 0 {
write!(stdout(), "\r\n")?;
}
if i > self.buf.lines() {
break;
}
let line = self.buf.line(i);
let max_len = line.char(usize::from(size.ws_col-1));
line.slice(0, max_len).print(&mut stdout())?;
if max_len < line.len() {
write!(stdout(), "\x1b[30m\x1b[47m>\x1b[m")?;
}
}
return Ok(());
}
fn repaint_line_full(&mut self) -> Result<(), Box<dyn Error>> {
let term_size = term::size()?;
write!(stdout(), "\x1b[{}H\x1b[K", self.cursor_row+1)?;
let mut line = self.buf.line(self.row_start+self.cursor_row);
let max_len = line.char(usize::from(term_size.ws_col-1));
let mut truncated = false;
if max_len < line.len() {
line = line.slice(0, max_len);
truncated = true;
}
line.print(&mut stdout())?;
let (_, col) = self.cursor_pos()?;
self.line_cols = col;
if self.cursor_col >= self.line_cols {
self.line_offset = line.len();
if truncated {
write!(stdout(), "\x1b[30m\x1b[47m>\x1b[m\x1b[{}G", self.cursor_col+1)?;
}
return Ok(());
}
let mut lo = line.char(self.cursor_col);
let mut hi = line.len();
// Binary search :D
while hi > lo {
let x = line.floor_char_boundary(lo + (hi - lo) / 2);
write!(stdout(), "\x1b[G")?;
line.slice(0, x).print(&mut stdout())?;
let (_, col) = self.cursor_pos()?;
if col <= self.cursor_col {
lo = line.ceil_char_boundary(x+1);
} else {
hi = x;
}
}
self.line_offset = line.floor_char_boundary(lo-1);
write!(stdout(), "\x1b[G")?;
line.print(&mut stdout())?;
if truncated {
write!(stdout(), "\x1b[30m\x1b[47m>\x1b[m")?;
}
write!(stdout(), "\x1b[{}G", self.cursor_col+1)?;
return Ok(());
}
fn up(&mut self) -> Result<(), Box<dyn Error>> {
if self.cursor_row == 0 && self.row_start == 0 {
return Ok(());
}
if self.cursor_row == 0 {
self.row_start -= 1;
self.repaint_all()?;
} else {
self.cursor_row -= 1;
}
return Ok(());
}
fn down(&mut self) -> Result<(), Box<dyn Error>> {
if self.row_start+self.cursor_row == self.buf.lines() {
return Ok(());
}
let size = term::size()?;
if self.cursor_row == usize::from(size.ws_row - 1) {
self.row_start += 1;
self.repaint_all()?;
} else {
self.cursor_row += 1;
}
return Ok(());
}
fn left(&mut self) -> Result<(), Box<dyn Error>> {
if self.cursor_col > self.line_cols {
self.cursor_col = self.line_cols;
}
if self.cursor_col == 0 && self.cursor_row == 0 {
return Ok(());
}
if self.cursor_col == 0 {
self.up()?;
self.repaint_line_full()?;
self.cursor_col = self.line_cols;
} else {
self.cursor_col -= 1;
}
return Ok(());
}
fn right(&mut self) -> Result<(), Box<dyn Error>> {
let size = term::size()?;
if self.cursor_col >= self.line_cols && self.cursor_row == usize::from(size.ws_row-1) {
return Ok(());
}
if self.cursor_col >= self.line_cols {
self.down()?;
self.cursor_col = 0;
} else {
self.cursor_col += 1;
}
return Ok(());
}
}
fn edit(file: &OsStr) -> Result<(), Box<dyn Error>> {
let _raw_handle = term::raw().map_err(|err| format!("cannot put terminal in raw mode: {}", err))?;
let r = Rope::open(Path::new(file))?;
let size = term::size()?;
let mut state = State{
buf: r,
row_start: 0,
cursor_row: 0,
cursor_col: 0,
line_offset: 0,
line_cols: 0,
};
let _ = state.repaint_all();
let _ = write!(stdout(), "\x1b[H");
let _ = stdout().flush();
loop {
let c = term::read_key(&mut stdin()).map_err(|err| format!("read key: {}", err))?;
match c {
Key::CtrlQ => {
break;
}
Key::CtrlS => {
let _ = state.buf.save(Path::new(file));
}
Key::Up => {
let _ = state.up();
let _ = state.repaint_line_full();
let _ = stdout().flush();
}
Key::Down => {
let _ = state.down();
let _ = state.repaint_line_full();
let _ = stdout().flush();
}
Key::Left => {
let _ = state.left();
let _ = state.repaint_line_full();
let _ = stdout().flush();
}
Key::Right => {
let _ = state.right();
let _ = state.repaint_line_full();
let _ = stdout().flush();
}
Key::Char(b'\r') => {
state.buf = state.buf.insert(state.buf.line_idx(state.row_start+state.cursor_row)+state.line_offset, b'\n');
if state.cursor_row == usize::from(size.ws_row - 1) {
state.row_start += 1;
} else {
state.cursor_row += 1;
}
state.cursor_col = 0;
let _ = state.repaint_all();
let _ = state.repaint_line_full();
let _ = stdout().flush();
}
Key::Char(c) => {
state.cursor_col = std::cmp::min(state.cursor_col, state.line_cols);
state.buf = state.buf.insert(state.buf.line_idx(state.row_start+state.cursor_row)+state.line_offset, c);
state.cursor_col += 1;
let _ = state.repaint_line_full();
let _ = stdout().flush();
}
}
}
return Ok(());
}
fn main() {
let args: Vec<OsString> = std::env::args_os().collect();
if args.len() != 2 {
println!("Usage: edit <filename>");
std::process::exit(1);
}
if let Err(err) = edit(&args[1]) {
println!("FAIL: {}", err);
std::process::exit(1);
}
}
|