on master help sign in
Command needs access to view information for certain changes.
commit48330ddb5f36a1c5f44a636525089a019ce4439d authorBlaž Hrastnik <blaz@mxxn.io> dateSat 19 Sep 2020, 23:16 (6 years ago) parent1303ffd
7 files changed+132−107
helix-core/src/lib.rs+1−2 helix-core/src/state.rs+8−7 helix-core/src/transaction.rs+2−2 helix-core/src/commands.rs → helix-term/src/commands.rs+66−55 helix-term/src/editor.rs+52−40 helix-term/src/keymap.rs+1−1 helix-term/src/main.rs+2
helix-core/src/lib.rs+1−2
@@ -1,5 +1,4 @@
11#![allow(unused)]
2−pub mod commands;
32pub mod graphemes;
43mod position;
54mod selection;
@@ -11,7 +10,7 @@ pub use ropey::{Rope, RopeSlice};
1110pub use tendril::StrTendril as Tendril;
1211
1312pub use position::Position;
14−pub use selection::Range as SelectionRange;
13+pub use selection::Range;
1514pub use selection::Selection;
1615pub use syntax::Syntax;
1716
helix-core/src/state.rs+8−7
@@ -1,5 +1,5 @@
11use crate::graphemes::{nth_next_grapheme_boundary, nth_prev_grapheme_boundary, RopeGraphemes};
2−use crate::{Position, Rope, RopeSlice, Selection, SelectionRange, Syntax};
2+use crate::{Position, Range, Rope, RopeSlice, Selection, Syntax};
33use anyhow::Error;
44
55use std::path::PathBuf;
@@ -12,11 +12,12 @@ pub enum Mode {
1212
1313/// A state represents the current editor state of a single buffer.
1414pub struct State {
15+ // TODO: fields should be private but we need to refactor commands.rs first
1516 /// Path to file on disk.
16− pub(crate) path: Option<PathBuf>,
17− pub(crate) doc: Rope,
18− pub(crate) selection: Selection,
19− pub(crate) mode: Mode,
17+ pub path: Option<PathBuf>,
18+ pub doc: Rope,
19+ pub selection: Selection,
20+ pub mode: Mode,
2021
2122 //
2223 pub syntax: Option<Syntax>,
@@ -189,7 +190,7 @@ impl State {
189190 // } else {
190191 let pos = self.move_pos(range.head, dir, granularity, count);
191192 // };
192− SelectionRange::new(pos, pos)
193+ Range::new(pos, pos)
193194 })
194195 }
195196
@@ -201,7 +202,7 @@ impl State {
201202 ) -> Selection {
202203 self.selection.transform(|range| {
203204 let pos = self.move_pos(range.head, dir, granularity, count);
204− SelectionRange::new(range.anchor, pos)
205+ Range::new(range.anchor, pos)
205206 })
206207 }
207208}
helix-core/src/transaction.rs+2−2
@@ -1,4 +1,4 @@
1−use crate::{Rope, Selection, SelectionRange, State, Tendril};
1+use crate::{Range, Rope, Selection, State, Tendril};
22
33/// (from, to, replacement)
44pub type Change = (usize, usize, Option<Tendril>);
@@ -387,7 +387,7 @@ impl Transaction {
387387 /// Generate a transaction with a change per selection range.
388388 pub fn change_by_selection<F>(state: &State, f: F) -> Self
389389 where
390− F: Fn(&SelectionRange) -> Change,
390+ F: Fn(&Range) -> Change,
391391 {
392392 Self::change(state, state.selection.ranges().iter().map(f))
393393 }
helix-core/src/commands.rs → helix-term/src/commands.rsrenamed+66−55
@@ -1,32 +1,42 @@
1−use crate::graphemes;
2−use crate::selection::{Range, Selection};
3−use crate::state::{Direction, Granularity, Mode, State};
4−use crate::transaction::{ChangeSet, Transaction};
5−use crate::Tendril;
1+use helix_core::{
2+ graphemes,
3+ state::{Direction, Granularity, Mode, State},
4+ ChangeSet, Range, Selection, Tendril, Transaction,
5+};
6+
7+use crate::editor::View;
68
79/// A command is a function that takes the current state and a count, and does a side-effect on the
810/// state (usually by creating and applying a transaction).
9−pub type Command = fn(state: &mut State, count: usize);
11+pub type Command = fn(view: &mut View, count: usize);
1012
11−pub fn move_char_left(state: &mut State, count: usize) {
13+pub fn move_char_left(view: &mut View, count: usize) {
1214 // TODO: use a transaction
13− let selection = state.move_selection(Direction::Backward, Granularity::Character, count);
14− state.selection = selection;
15+ let selection = view
16+ .state
17+ .move_selection(Direction::Backward, Granularity::Character, count);
18+ view.state.selection = selection;
1519}
1620
17−pub fn move_char_right(state: &mut State, count: usize) {
21+pub fn move_char_right(view: &mut View, count: usize) {
1822 // TODO: use a transaction
19− state.selection = state.move_selection(Direction::Forward, Granularity::Character, count);
23+ view.state.selection =
24+ view.state
25+ .move_selection(Direction::Forward, Granularity::Character, count);
2026}
2127
22−pub fn move_line_up(state: &mut State, count: usize) {
28+pub fn move_line_up(view: &mut View, count: usize) {
2329 // TODO: use a transaction
24− state.selection = state.move_selection(Direction::Backward, Granularity::Line, count);
30+ view.state.selection = view
31+ .state
32+ .move_selection(Direction::Backward, Granularity::Line, count);
2533}
2634
27−pub fn move_line_down(state: &mut State, count: usize) {
35+pub fn move_line_down(view: &mut View, count: usize) {
2836 // TODO: use a transaction
29− state.selection = state.move_selection(Direction::Forward, Granularity::Line, count);
37+ view.state.selection = view
38+ .state
39+ .move_selection(Direction::Forward, Granularity::Line, count);
3040}
3141
3242// avoid select by default by having a visual mode switch that makes movements into selects
@@ -37,21 +47,22 @@ pub fn move_line_down(state: &mut State, count: usize) {
3747// lastly, if it was append mode we shift cursor by 1?
3848
3949// inserts at the start of each selection
40−pub fn insert_mode(state: &mut State, _count: usize) {
41− state.mode = Mode::Insert;
50+pub fn insert_mode(view: &mut View, _count: usize) {
51+ view.state.mode = Mode::Insert;
4252
43− state.selection = state
53+ view.state.selection = view
54+ .state
4455 .selection
4556 .transform(|range| Range::new(range.to(), range.from()))
4657}
4758
4859// inserts at the end of each selection
49−pub fn append_mode(state: &mut State, _count: usize) {
50− state.mode = Mode::Insert;
60+pub fn append_mode(view: &mut View, _count: usize) {
61+ view.state.mode = Mode::Insert;
5162
5263 // TODO: as transaction
53− let text = &state.doc.slice(..);
54− state.selection = state.selection.transform(|range| {
64+ let text = &view.state.doc.slice(..);
65+ view.state.selection = view.state.selection.transform(|range| {
5566 // TODO: to() + next char
5667 Range::new(
5768 range.from(),
@@ -78,63 +89,63 @@ fn selection_lines(state: &State) -> Vec<usize> {
7889}
7990
8091// I inserts at the start of each line with a selection
81−pub fn prepend_to_line(state: &mut State, _count: usize) {
82− state.mode = Mode::Insert;
92+pub fn prepend_to_line(view: &mut View, _count: usize) {
93+ view.state.mode = Mode::Insert;
8394
84− let lines = selection_lines(state);
95+ let lines = selection_lines(&view.state);
8596
8697 let positions = lines
8798 .into_iter()
8899 .map(|index| {
89100 // adjust all positions to the start of the line.
90− state.doc.line_to_char(index)
101+ view.state.doc.line_to_char(index)
91102 })
92103 .map(|pos| Range::new(pos, pos));
93104
94105 let selection = Selection::new(positions.collect(), 0);
95106
96− let transaction = Transaction::new(state).with_selection(selection);
107+ let transaction = Transaction::new(&mut view.state).with_selection(selection);
97108
98− transaction.apply(state);
109+ transaction.apply(&mut view.state);
99110 // TODO: need to store into history if successful
100111}
101112
102113// A inserts at the end of each line with a selection
103−pub fn append_to_line(state: &mut State, _count: usize) {
104− state.mode = Mode::Insert;
114+pub fn append_to_line(view: &mut View, _count: usize) {
115+ view.state.mode = Mode::Insert;
105116
106− let lines = selection_lines(state);
117+ let lines = selection_lines(&view.state);
107118
108119 let positions = lines
109120 .into_iter()
110121 .map(|index| {
111122 // adjust all positions to the end of the line.
112− let line = state.doc.line(index);
113− let line_start = state.doc.line_to_char(index);
123+ let line = view.state.doc.line(index);
124+ let line_start = view.state.doc.line_to_char(index);
114125 line_start + line.len_chars() - 1
115126 })
116127 .map(|pos| Range::new(pos, pos));
117128
118129 let selection = Selection::new(positions.collect(), 0);
119130
120− let transaction = Transaction::new(state).with_selection(selection);
131+ let transaction = Transaction::new(&mut view.state).with_selection(selection);
121132
122− transaction.apply(state);
133+ transaction.apply(&mut view.state);
123134 // TODO: need to store into history if successful
124135}
125136
126137// o inserts a new line after each line with a selection
127−pub fn open_below(state: &mut State, _count: usize) {
128− state.mode = Mode::Insert;
138+pub fn open_below(view: &mut View, _count: usize) {
139+ view.state.mode = Mode::Insert;
129140
130− let lines = selection_lines(state);
141+ let lines = selection_lines(&view.state);
131142
132143 let positions: Vec<_> = lines
133144 .into_iter()
134145 .map(|index| {
135146 // adjust all positions to the end of the line.
136− let line = state.doc.line(index);
137− let line_start = state.doc.line_to_char(index);
147+ let line = view.state.doc.line(index);
148+ let line_start = view.state.doc.line_to_char(index);
138149 line_start + line.len_chars()
139150 })
140151 .collect();
@@ -155,51 +166,51 @@ pub fn open_below(state: &mut State, _count: usize) {
155166 0,
156167 );
157168
158− let transaction = Transaction::change(state, changes).with_selection(selection);
169+ let transaction = Transaction::change(&view.state, changes).with_selection(selection);
159170
160− transaction.apply(state);
171+ transaction.apply(&mut view.state);
161172 // TODO: need to store into history if successful
162173}
163174
164175// O inserts a new line before each line with a selection
165176
166−pub fn normal_mode(state: &mut State, _count: usize) {
177+pub fn normal_mode(view: &mut View, _count: usize) {
167178 // TODO: if leaving append mode, move cursor back by 1
168− state.mode = Mode::Normal;
179+ view.state.mode = Mode::Normal;
169180}
170181
171182// TODO: insert means add text just before cursor, on exit we should be on the last letter.
172−pub fn insert_char(state: &mut State, c: char) {
183+pub fn insert_char(view: &mut View, c: char) {
173184 let c = Tendril::from_char(c);
174− let transaction = Transaction::insert(&state, c);
185+ let transaction = Transaction::insert(&view.state, c);
175186
176− transaction.apply(state);
187+ transaction.apply(&mut view.state);
177188 // TODO: need to store into history if successful
178189}
179190
180191// TODO: handle indent-aware delete
181−pub fn delete_char_backward(state: &mut State, count: usize) {
182− let text = &state.doc.slice(..);
183− let transaction = Transaction::change_by_selection(state, |range| {
192+pub fn delete_char_backward(view: &mut View, count: usize) {
193+ let text = &view.state.doc.slice(..);
194+ let transaction = Transaction::change_by_selection(&view.state, |range| {
184195 (
185196 graphemes::nth_prev_grapheme_boundary(text, range.head, count),
186197 range.head,
187198 None,
188199 )
189200 });
190− transaction.apply(state);
201+ transaction.apply(&mut view.state);
191202 // TODO: need to store into history if successful
192203}
193204
194−pub fn delete_char_forward(state: &mut State, count: usize) {
195− let text = &state.doc.slice(..);
196− let transaction = Transaction::change_by_selection(state, |range| {
205+pub fn delete_char_forward(view: &mut View, count: usize) {
206+ let text = &view.state.doc.slice(..);
207+ let transaction = Transaction::change_by_selection(&view.state, |range| {
197208 (
198209 graphemes::nth_next_grapheme_boundary(text, range.head, count),
199210 range.head,
200211 None,
201212 )
202213 });
203− transaction.apply(state);
214+ transaction.apply(&mut view.state);
204215 // TODO: need to store into history if successful
205216}
helix-term/src/editor.rs+52−40
@@ -1,4 +1,4 @@
1−use crate::{keymap, theme::Theme, Args};
1+use crate::{commands, keymap, theme::Theme, Args};
22use helix_core::{
33 state::coords_at_pos,
44 state::Mode,
@@ -31,10 +31,15 @@ type Terminal = tui::Terminal<CrosstermBackend<std::io::Stdout>>;
3131
3232static EX: smol::Executor = smol::Executor::new();
3333
34+pub struct View {
35+ pub state: State,
36+ pub first_line: u16,
37+ pub size: (u16, u16),
38+}
39+
3440pub struct Editor {
3541 terminal: Terminal,
36− state: Option<State>,
37− first_line: u16,
42+ view: Option<View>,
3843 size: (u16, u16),
3944 surface: Surface,
4045 cache: Surface,
@@ -52,8 +57,7 @@ impl Editor {
5257
5358 let mut editor = Editor {
5459 terminal,
55− state: None,
56− first_line: 0,
60+ view: None,
5761 size,
5862 surface: Surface::empty(area),
5963 cache: Surface::empty(area),
@@ -75,7 +79,14 @@ impl Editor {
7579 .as_mut()
7680 .unwrap()
7781 .configure(self.theme.scopes());
78− self.state = Some(state);
82+
83+ let view = View {
84+ state,
85+ first_line: 0,
86+ size: self.size,
87+ };
88+
89+ self.view = Some(view);
7990 Ok(())
8091 }
8192
@@ -83,8 +94,8 @@ impl Editor {
8394 use tui::backend::Backend;
8495 use tui::style::Color;
8596 // TODO: ideally not mut but highlights require it because of cursor cache
86− match &mut self.state {
87− Some(state) => {
97+ match &mut self.view {
98+ Some(view) => {
8899 let area = Rect::new(0, 0, self.size.0, self.size.1);
89100 let mut stdout = stdout();
90101 self.surface.reset(); // reset is faster than allocating new empty surface
@@ -97,18 +108,18 @@ impl Editor {
97108 let viewport = Rect::new(offset, 0, self.size.0, self.size.1 - 1); // - 1 for statusline
98109
99110 // TODO: inefficient, should feed chunks.iter() to tree_sitter.parse_with(|offset, pos|)
100− let source_code = state.doc().to_string();
111+ let source_code = view.state.doc().to_string();
101112
102113 let last_line = std::cmp::min(
103− (self.first_line + viewport.height - 1) as usize,
104− state.doc().len_lines() - 1,
114+ (view.first_line + viewport.height - 1) as usize,
115+ view.state.doc().len_lines() - 1,
105116 );
106117
107118 let range = {
108119 // calculate viewport byte ranges
109− let start = state.doc().line_to_byte(self.first_line.into());
110− let end = state.doc().line_to_byte(last_line)
111− + state.doc().line(last_line).len_bytes();
120+ let start = view.state.doc().line_to_byte(view.first_line.into());
121+ let end = view.state.doc().line_to_byte(last_line)
122+ + view.state.doc().line(last_line).len_bytes();
112123
113124 start..end
114125 };
@@ -117,7 +128,8 @@ impl Editor {
117128
118129 // TODO: cache highlight results
119130 // TODO: only recalculate when state.doc is actually modified
120− let highlights: Vec<_> = state
131+ let highlights: Vec<_> = view
132+ .state
121133 .syntax
122134 .as_mut()
123135 .unwrap()
@@ -141,10 +153,10 @@ impl Editor {
141153 HighlightEvent::Source { start, end } => {
142154 // TODO: filter out spans out of viewport for now..
143155
144− let start = state.doc().byte_to_char(start);
145− let end = state.doc().byte_to_char(end);
156+ let start = view.state.doc().byte_to_char(start);
157+ let end = view.state.doc().byte_to_char(end);
146158
147− let text = state.doc().slice(start..end);
159+ let text = view.state.doc().slice(start..end);
148160
149161 use helix_core::graphemes::{grapheme_width, RopeGraphemes};
150162
@@ -191,7 +203,7 @@ impl Editor {
191203
192204 let mut line = 0;
193205 let style = self.theme.get("ui.linenr");
194− for i in self.first_line..(last_line as u16) {
206+ for i in view.first_line..(last_line as u16) {
195207 self.surface
196208 .set_stringn(0, line, format!("{:>5}", i + 1), 5, style); // lavender
197209 line += 1;
@@ -223,7 +235,7 @@ impl Editor {
223235 // }
224236
225237 // statusline
226− let mode = match state.mode() {
238+ let mode = match view.state.mode() {
227239 Mode::Insert => "INS",
228240 Mode::Normal => "NOR",
229241 };
@@ -235,7 +247,7 @@ impl Editor {
235247 let text_color = Style::default().fg(Color::Rgb(219, 191, 239)); // lilac
236248 self.surface
237249 .set_string(1, self.size.1 - 1, mode, text_color);
238− if let Some(path) = state.path() {
250+ if let Some(path) = view.state.path() {
239251 self.surface
240252 .set_string(6, self.size.1 - 1, path.to_string_lossy(), text_color);
241253 }
@@ -247,19 +259,19 @@ impl Editor {
247259 std::mem::swap(&mut self.surface, &mut self.cache);
248260
249261 // set cursor shape
250− match state.mode() {
262+ match view.state.mode() {
251263 Mode::Insert => write!(stdout, "\x1B[6 q"),
252264 Mode::Normal => write!(stdout, "\x1B[2 q"),
253265 };
254266
255267 // render the cursor
256− let pos = state.selection().cursor();
257− let coords = coords_at_pos(&state.doc().slice(..), pos);
268+ let pos = view.state.selection().cursor();
269+ let coords = coords_at_pos(&view.state.doc().slice(..), pos);
258270 execute!(
259271 stdout,
260272 cursor::MoveTo(
261273 coords.col as u16 + viewport.x,
262− coords.row as u16 - self.first_line + viewport.y,
274+ coords.row as u16 - view.first_line + viewport.y,
263275 )
264276 );
265277 }
@@ -295,29 +307,29 @@ impl Editor {
295307 break;
296308 }
297309 Some(Ok(Event::Key(event))) => {
298− if let Some(state) = &mut self.state {
299− match state.mode() {
310+ if let Some(view) = &mut self.view {
311+ match view.state.mode() {
300312 Mode::Insert => {
301313 match event {
302314 KeyEvent {
303315 code: KeyCode::Esc, ..
304− } => helix_core::commands::normal_mode(state, 1),
316+ } => commands::normal_mode(view, 1),
305317 KeyEvent {
306318 code: KeyCode::Backspace,
307319 ..
308− } => helix_core::commands::delete_char_backward(state, 1),
320+ } => commands::delete_char_backward(view, 1),
309321 KeyEvent {
310322 code: KeyCode::Delete,
311323 ..
312− } => helix_core::commands::delete_char_forward(state, 1),
324+ } => commands::delete_char_forward(view, 1),
313325 KeyEvent {
314326 code: KeyCode::Char(c),
315327 ..
316− } => helix_core::commands::insert_char(state, c),
328+ } => commands::insert_char(view, c),
317329 KeyEvent {
318330 code: KeyCode::Enter,
319331 ..
320− } => helix_core::commands::insert_char(state, '\n'),
332+ } => commands::insert_char(view, '\n'),
321333 _ => (), // skip
322334 }
323335 // TODO: simplistic ensure cursor in view for now
@@ -329,7 +341,7 @@ impl Editor {
329341 // TODO: handle modes and sequences (`gg`)
330342 if let Some(command) = keymap.get(&event) {
331343 // TODO: handle count other than 1
332− command(state, 1);
344+ command(view, 1);
333345
334346 // TODO: simplistic ensure cursor in view for now
335347 self.ensure_cursor_in_view();
@@ -350,10 +362,10 @@ impl Editor {
350362 }
351363
352364 fn ensure_cursor_in_view(&mut self) {
353− if let Some(state) = &mut self.state {
354− let cursor = state.selection().cursor();
355− let line = state.doc().char_to_line(cursor) as u16;
356− let document_end = self.first_line + self.size.1.saturating_sub(1) - 1;
365+ if let Some(view) = &mut self.view {
366+ let cursor = view.state.selection().cursor();
367+ let line = view.state.doc().char_to_line(cursor) as u16;
368+ let document_end = view.first_line + self.size.1.saturating_sub(1) - 1;
357369
358370 let padding = 5u16;
359371
@@ -361,10 +373,10 @@ impl Editor {
361373
362374 if line > document_end.saturating_sub(padding) {
363375 // scroll down
364− self.first_line += line - (document_end.saturating_sub(padding));
365− } else if line < self.first_line + padding {
376+ view.first_line += line - (document_end.saturating_sub(padding));
377+ } else if line < view.first_line + padding {
366378 // scroll up
367− self.first_line = line.saturating_sub(padding);
379+ view.first_line = line.saturating_sub(padding);
368380 }
369381 }
370382 }
helix-term/src/keymap.rs+1−1
@@ -1,9 +1,9 @@
1+use crate::commands::{self, Command};
12use crossterm::{
23 event::{KeyCode, KeyEvent as Key, KeyModifiers as Modifiers},
34 execute,
45 style::Print,
56};
6−use helix_core::commands::{self, Command};
77use std::collections::HashMap;
88
99// Kakoune-inspired:
helix-term/src/main.rs+2
@@ -1,6 +1,8 @@
11#![allow(unused)]
22#[macro_use]
33mod macros;
4+
5+mod commands;
46mod editor;
57mod keymap;
68mod theme;