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
|
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,
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_line_full(&mut self) -> Result<(), Box<dyn Error>> {
write!(stdout(), "\x1b[{}H", self.cursor_row+1)?;
let line = self.buf.line(self.cursor_row);
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();
return Ok(());
}
let mut lo = line.ceil_char_boundary(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\x1b[K")?;
line.print(&mut stdout())?;
write!(stdout(), "\x1b[{}G", 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,
cursor_row: 0,
cursor_col: 0,
line_offset: 0,
line_cols: 0,
};
let _ = write!(stdout(), "\x1b[J");
for i in 0..usize::from(size.ws_row) {
if i > 0 {
let _ = write!(stdout(), "\r\n");
}
if i > state.buf.lines() {
break;
}
let line = state.buf.line(i);
// TODO: handle line-wrapping.
let _ = line.print(&mut stdout());
if i == 0 {
let (_, col) = state.cursor_pos()?;
state.line_cols = col;
}
}
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 => {
if state.cursor_row == 0 {
continue;
}
state.cursor_row -= 1;
let _ = state.repaint_line_full();
let _ = stdout().flush();
}
Key::Down => {
if state.cursor_row == usize::from(size.ws_row - 1) || state.cursor_row == state.buf.lines() {
continue;
}
state.cursor_row += 1;
let _ = state.repaint_line_full();
let _ = stdout().flush();
}
Key::Left => {
state.cursor_col = std::cmp::min(state.cursor_col, state.line_cols);
if state.cursor_col == 0 {
continue;
}
state.cursor_col -= 1;
let _ = state.repaint_line_full();
let _ = stdout().flush();
}
Key::Right => {
if state.cursor_col >= state.line_cols {
continue;
}
state.cursor_col += 1;
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.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);
}
}
|