on master help sign in
Refactor: Document type as a wrapper around barebones State.
b39849dBlaž Hrastnik
Cargo.lock+2
@@ -447,6 +447,7 @@ dependencies = [
447 "futures-util",
447 "futures-util",
448 "glob",
448 "glob",
449 "helix-core",
449 "helix-core",
450+ "helix-view",
450 "jsonrpc-core",
451 "jsonrpc-core",
451 "lsp-types",
452 "lsp-types",
452 "pathdiff",
453 "pathdiff",
@@ -491,6 +492,7 @@ dependencies = [
491 "helix-core",
492 "helix-core",
492 "once_cell",
493 "once_cell",
493 "tui",
494 "tui",
495+ "url",
494]
496]
495
497
496[[package]]
498[[package]]
helix-core/src/indent.rs+17−12
@@ -111,17 +111,17 @@ fn find_first_non_whitespace_char(state: &State, line_num: usize) -> usize {
111 start
111 start
112}
112}
113
113
114−fn suggested_indent_for_line(state: &State, line_num: usize) -> usize {
114+fn suggested_indent_for_line(syntax: Option<&Syntax>, state: &State, line_num: usize) -> usize {
115 let line = state.doc.line(line_num);
115 let line = state.doc.line(line_num);
116 let current = indent_level_for_line(line);
116 let current = indent_level_for_line(line);
117
117
118 let start = find_first_non_whitespace_char(state, line_num);
118 let start = find_first_non_whitespace_char(state, line_num);
119
119
120− suggested_indent_for_pos(state, start)
120+ suggested_indent_for_pos(syntax, state, start)
121}
121}
122
122
123−pub fn suggested_indent_for_pos(state: &State, pos: usize) -> usize {
123+pub fn suggested_indent_for_pos(syntax: Option<&Syntax>, state: &State, pos: usize) -> usize {
124− if let Some(syntax) = &state.syntax {
124+ if let Some(syntax) = syntax {
125 let byte_start = state.doc.char_to_byte(pos);
125 let byte_start = state.doc.char_to_byte(pos);
126 let node = get_highest_syntax_node_at_bytepos(syntax, byte_start);
126 let node = get_highest_syntax_node_at_bytepos(syntax, byte_start);
127
127
@@ -163,13 +163,18 @@ mod test {
163",
163",
164 );
164 );
165
165
166− let mut state = State::new(doc);
166+ let state = State::new(doc);
167− state.set_language("source.rust", &[]);
167+ // TODO: set_language
168−
168+ let language_config = crate::syntax::LOADER
169+ .language_config_for_scope("source.rust")
170+ .unwrap();
171+ let highlight_config = language_config.highlight_config(&[]).unwrap().unwrap();
172+ let syntax = Syntax::new(&state.doc, highlight_config.clone());
173+
169− assert_eq!(suggested_indent_for_line(&state, 0), 0); // mod
174+ assert_eq!(suggested_indent_for_line(Some(&syntax), &state, 0), 0); // mod
170− assert_eq!(suggested_indent_for_line(&state, 1), 1); // fn
175+ assert_eq!(suggested_indent_for_line(Some(&syntax), &state, 1), 1); // fn
171− assert_eq!(suggested_indent_for_line(&state, 2), 2); // 1 + 1
176+ assert_eq!(suggested_indent_for_line(Some(&syntax), &state, 2), 2); // 1 + 1
172− assert_eq!(suggested_indent_for_line(&state, 4), 1); // }
177+ assert_eq!(suggested_indent_for_line(Some(&syntax), &state, 4), 1); // }
173− assert_eq!(suggested_indent_for_line(&state, 5), 0); // }
178+ assert_eq!(suggested_indent_for_line(Some(&syntax), &state, 5), 0); // }
174 }
179 }
175}
180}
helix-core/src/state.rs−81
@@ -3,34 +3,11 @@ use crate::syntax::LOADER;
3use crate::{ChangeSet, Diagnostic, Position, Range, Rope, RopeSlice, Selection, Syntax};
3use crate::{ChangeSet, Diagnostic, Position, Range, Rope, RopeSlice, Selection, Syntax};
4use anyhow::Error;
4use anyhow::Error;
5
5
6−use std::path::PathBuf;
7−
8−#[derive(Copy, Clone, PartialEq, Eq, Hash)]
9−pub enum Mode {
10− Normal,
11− Insert,
12− Goto,
13−}
14−
15/// A state represents the current editor state of a single buffer.
6/// A state represents the current editor state of a single buffer.
16pub struct State {
7pub struct State {
17 // TODO: fields should be private but we need to refactor commands.rs first
8 // TODO: fields should be private but we need to refactor commands.rs first
18− /// Path to file on disk.
19− pub path: Option<PathBuf>,
20 pub doc: Rope,
9 pub doc: Rope,
21 pub selection: Selection,
10 pub selection: Selection,
22− pub mode: Mode,
23−
24− pub restore_cursor: bool,
25−
26− // TODO: move these to a Document wrapper?
27− pub syntax: Option<Syntax>,
28− /// Pending changes since last history commit.
29− pub changes: ChangeSet,
30− pub old_state: Option<(Rope, Selection)>,
31−
32− pub version: i64,
33− pub diagnostics: Vec<Diagnostic>,
34}
11}
35
12
36#[derive(Copy, Clone, PartialEq, Eq)]
13#[derive(Copy, Clone, PartialEq, Eq)]
@@ -49,60 +26,12 @@ pub enum Granularity {
49impl State {
26impl State {
50 #[must_use]
27 #[must_use]
51 pub fn new(doc: Rope) -> Self {
28 pub fn new(doc: Rope) -> Self {
52− let changes = ChangeSet::new(&doc);
53− let old_state = Some((doc.clone(), Selection::single(0, 0)));
54−
55 Self {
29 Self {
56− path: None,
57 doc,
30 doc,
58 selection: Selection::single(0, 0),
31 selection: Selection::single(0, 0),
59− mode: Mode::Normal,
60− restore_cursor: false,
61− syntax: None,
62− changes,
63− old_state,
64− diagnostics: Vec::new(),
65− version: 0,
66 }
32 }
67 }
33 }
68
34
69− // TODO: passing scopes here is awkward
70− pub fn load(path: PathBuf, scopes: &[String]) -> Result<Self, Error> {
71− use std::{env, fs::File, io::BufReader};
72− let _current_dir = env::current_dir()?;
73−
74− let doc = Rope::from_reader(BufReader::new(File::open(path.clone())?))?;
75−
76− // TODO: create if not found
77−
78− let mut state = Self::new(doc);
79−
80− if let Some(language_config) = LOADER.language_config_for_file_name(path.as_path()) {
81− let highlight_config = language_config.highlight_config(scopes).unwrap().unwrap();
82− // TODO: config.configure(scopes) is now delayed, is that ok?
83−
84− let syntax = Syntax::new(&state.doc, highlight_config.clone());
85−
86− state.syntax = Some(syntax);
87− };
88−
89− // canonicalize path to absolute value
90− state.path = Some(std::fs::canonicalize(path)?);
91−
92− Ok(state)
93− }
94−
95− pub fn set_language(&mut self, scope: &str, scopes: &[String]) {
96− if let Some(language_config) = LOADER.language_config_for_scope(scope) {
97− let highlight_config = language_config.highlight_config(scopes).unwrap().unwrap();
98− // TODO: config.configure(scopes) is now delayed, is that ok?
99−
100− let syntax = Syntax::new(&self.doc, highlight_config.clone());
101−
102− self.syntax = Some(syntax);
103− };
104− }
105−
106 // TODO: doc/selection accessors
35 // TODO: doc/selection accessors
107
36
108 // TODO: be able to take either Rope or RopeSlice
37 // TODO: be able to take either Rope or RopeSlice
@@ -116,16 +45,6 @@ impl State {
116 &self.selection
45 &self.selection
117 }
46 }
118
47
119− #[inline]
120− pub fn mode(&self) -> Mode {
121− self.mode
122− }
123−
124− #[inline]
125− pub fn path(&self) -> Option<&PathBuf> {
126− self.path.as_ref()
127− }
128−
129 // pub fn doc<R>(&self, range: R) -> RopeSlice
48 // pub fn doc<R>(&self, range: R) -> RopeSlice
130 // where
49 // where
131 // R: std::ops::RangeBounds<usize>,
50 // R: std::ops::RangeBounds<usize>,
helix-core/src/syntax.rs+1−1
@@ -66,7 +66,7 @@ impl LanguageConfiguration {
66
66
67use once_cell::sync::Lazy;
67use once_cell::sync::Lazy;
68
68
69−pub(crate) static LOADER: Lazy<Loader> = Lazy::new(Loader::init);
69+pub static LOADER: Lazy<Loader> = Lazy::new(Loader::init);
70
70
71pub struct Loader {
71pub struct Loader {
72 // highlight_names ?
72 // highlight_names ?
helix-core/src/transaction.rs+6−30
@@ -351,22 +351,6 @@ pub struct Transaction {
351 // scroll_into_view
351 // scroll_into_view
352}
352}
353
353
354−/// Like std::mem::replace() except it allows the replacement value to be mapped from the
355−/// original value.
356−pub fn take_with<T, F>(mut_ref: &mut T, closure: F)
357−where
358− F: FnOnce(T) -> T,
359−{
360− use std::{panic, ptr};
361−
362− unsafe {
363− let old_t = ptr::read(mut_ref);
364− let new_t = panic::catch_unwind(panic::AssertUnwindSafe(|| closure(old_t)))
365− .unwrap_or_else(|_| ::std::process::abort());
366− ptr::write(mut_ref, new_t);
367− }
368−}
369−
370impl Transaction {
354impl Transaction {
371 /// Create a new, empty transaction.
355 /// Create a new, empty transaction.
372 pub fn new(state: &mut State) -> Self {
356 pub fn new(state: &mut State) -> Self {
@@ -376,29 +360,21 @@ impl Transaction {
376 }
360 }
377 }
361 }
378
362
363+ pub fn changes(&self) -> &ChangeSet {
364+ &self.changes
365+ }
366+
379 /// Returns true if applied successfully.
367 /// Returns true if applied successfully.
380 pub fn apply(&self, state: &mut State) -> bool {
368 pub fn apply(&self, state: &mut State) -> bool {
381 if !self.changes.is_empty() {
369 if !self.changes.is_empty() {
382− // TODO: also avoid mapping the selection if not necessary
383−
384− let old_doc = state.doc().clone();
385−
386 // apply changes to the document
370 // apply changes to the document
387 if !self.changes.apply(&mut state.doc) {
371 if !self.changes.apply(&mut state.doc) {
388 return false;
372 return false;
389 }
373 }
390−
391− // Compose this transaction with the previous one
392− take_with(&mut state.changes, |changes| {
393− changes.compose(self.changes.clone()).unwrap()
394− });
395−
396− if let Some(syntax) = &mut state.syntax {
397− // TODO: no unwrap
398− syntax.update(&old_doc, &state.doc, &self.changes).unwrap();
399− }
400 }
374 }
401
375
376+ // TODO: also avoid mapping the selection if not necessary
377+
402 // update the selection: either take the selection specified in the transaction, or map the
378 // update the selection: either take the selection specified in the transaction, or map the
403 // current selection through changes.
379 // current selection through changes.
404 state.selection = self
380 state.selection = self
helix-lsp/Cargo.toml+1
@@ -8,6 +8,7 @@ edition = "2018"
8
8
9[dependencies]
9[dependencies]
10helix-core = { path = "../helix-core" }
10helix-core = { path = "../helix-core" }
11+helix-view = { path = "../helix-view" }
11
12
12lsp-types = { version = "0.82", features = ["proposed"] }
13lsp-types = { version = "0.82", features = ["proposed"] }
13smol = "1.2"
14smol = "1.2"
helix-lsp/src/client.rs+11−10
@@ -6,6 +6,7 @@ use crate::{
6type Result<T> = core::result::Result<T, Error>;
6type Result<T> = core::result::Result<T, Error>;
7
7
8use helix_core::{State, Transaction};
8use helix_core::{State, Transaction};
9+use helix_view::Document;
9
10
10// use std::collections::HashMap;
11// use std::collections::HashMap;
11
12
@@ -190,13 +191,13 @@ impl Client {
190 // Text document
191 // Text document
191 // -------------------------------------------------------------------------------------------
192 // -------------------------------------------------------------------------------------------
192
193
193− pub async fn text_document_did_open(&mut self, state: &State) -> Result<()> {
194+ pub async fn text_document_did_open(&mut self, doc: &Document) -> Result<()> {
194 self.notify::<lsp::notification::DidOpenTextDocument>(lsp::DidOpenTextDocumentParams {
195 self.notify::<lsp::notification::DidOpenTextDocument>(lsp::DidOpenTextDocumentParams {
195 text_document: lsp::TextDocumentItem {
196 text_document: lsp::TextDocumentItem {
196− uri: lsp::Url::from_file_path(state.path().unwrap()).unwrap(),
197+ uri: lsp::Url::from_file_path(doc.path().unwrap()).unwrap(),
197 language_id: "rust".to_string(), // TODO: hardcoded for now
198 language_id: "rust".to_string(), // TODO: hardcoded for now
198− version: state.version,
199+ version: doc.version,
199− text: String::from(&state.doc),
200+ text: String::from(doc.text()),
200 },
201 },
201 })
202 })
202 .await
203 .await
@@ -205,13 +206,13 @@ impl Client {
205 // TODO: trigger any time history.commit_revision happens
206 // TODO: trigger any time history.commit_revision happens
206 pub async fn text_document_did_change(
207 pub async fn text_document_did_change(
207 &mut self,
208 &mut self,
208− state: &State,
209+ doc: &Document,
209 transaction: &Transaction,
210 transaction: &Transaction,
210 ) -> Result<()> {
211 ) -> Result<()> {
211 self.notify::<lsp::notification::DidChangeTextDocument>(lsp::DidChangeTextDocumentParams {
212 self.notify::<lsp::notification::DidChangeTextDocument>(lsp::DidChangeTextDocumentParams {
212 text_document: lsp::VersionedTextDocumentIdentifier::new(
213 text_document: lsp::VersionedTextDocumentIdentifier::new(
213− lsp::Url::from_file_path(state.path().unwrap()).unwrap(),
214+ lsp::Url::from_file_path(doc.path().unwrap()).unwrap(),
214− state.version,
215+ doc.version,
215 ),
216 ),
216 content_changes: vec![lsp::TextDocumentContentChangeEvent {
217 content_changes: vec![lsp::TextDocumentContentChangeEvent {
217 // range = None -> whole document
218 // range = None -> whole document
@@ -223,12 +224,12 @@ impl Client {
223 .await
224 .await
224 }
225 }
225
226
226− // TODO: impl into() TextDocumentIdentifier / VersionedTextDocumentIdentifier for State.
227+ // TODO: impl into() TextDocumentIdentifier / VersionedTextDocumentIdentifier for Document.
227
228
228− pub async fn text_document_did_close(&mut self, state: &State) -> Result<()> {
229+ pub async fn text_document_did_close(&mut self, doc: &Document) -> Result<()> {
229 self.notify::<lsp::notification::DidCloseTextDocument>(lsp::DidCloseTextDocumentParams {
230 self.notify::<lsp::notification::DidCloseTextDocument>(lsp::DidCloseTextDocumentParams {
230 text_document: lsp::TextDocumentIdentifier::new(
231 text_document: lsp::TextDocumentIdentifier::new(
231− lsp::Url::from_file_path(state.path().unwrap()).unwrap(),
232+ lsp::Url::from_file_path(doc.path().unwrap()).unwrap(),
232 ),
233 ),
233 })
234 })
234 .await
235 .await
helix-term/src/application.rs+25−23
@@ -1,10 +1,11 @@
1use clap::ArgMatches as Args;
1use clap::ArgMatches as Args;
2−use helix_core::{indent::TAB_WIDTH, state::Mode, syntax::HighlightEvent, Position, Range, State};
2+use helix_core::{indent::TAB_WIDTH, syntax::HighlightEvent, Position, Range, State};
3use helix_view::{
3use helix_view::{
4 commands,
4 commands,
5+ document::Mode,
5 keymap::{self, Keymaps},
6 keymap::{self, Keymaps},
6 prompt::Prompt,
7 prompt::Prompt,
7− Editor, Theme, View,
8+ Document, Editor, Theme, View,
8};
9};
9
10
10use std::{
11use std::{
@@ -95,15 +96,15 @@ impl Renderer {
95 self.surface.set_style(area, theme.get("ui.background"));
96 self.surface.set_style(area, theme.get("ui.background"));
96
97
97 // TODO: inefficient, should feed chunks.iter() to tree_sitter.parse_with(|offset, pos|)
98 // TODO: inefficient, should feed chunks.iter() to tree_sitter.parse_with(|offset, pos|)
98− let source_code = view.state.doc().to_string();
99+ let source_code = view.doc.text().to_string();
99
100
100 let last_line = view.last_line();
101 let last_line = view.last_line();
101
102
102 let range = {
103 let range = {
103 // calculate viewport byte ranges
104 // calculate viewport byte ranges
104− let start = view.state.doc().line_to_byte(view.first_line);
105+ let start = view.doc.text().line_to_byte(view.first_line);
105− let end = view.state.doc().line_to_byte(last_line)
106+ let end = view.doc.text().line_to_byte(last_line)
106− + view.state.doc().line(last_line).len_bytes();
107+ + view.doc.text().line(last_line).len_bytes();
107
108
108 start..end
109 start..end
109 };
110 };
@@ -111,7 +112,7 @@ impl Renderer {
111 // TODO: range doesn't actually restrict source, just highlight range
112 // TODO: range doesn't actually restrict source, just highlight range
112 // TODO: cache highlight results
113 // TODO: cache highlight results
113 // TODO: only recalculate when state.doc is actually modified
114 // TODO: only recalculate when state.doc is actually modified
114− let highlights: Vec<_> = match view.state.syntax.as_mut() {
115+ let highlights: Vec<_> = match view.doc.syntax.as_mut() {
115 Some(syntax) => {
116 Some(syntax) => {
116 syntax
117 syntax
117 .highlight_iter(source_code.as_bytes(), Some(range), None, |_| None)
118 .highlight_iter(source_code.as_bytes(), Some(range), None, |_| None)
@@ -127,6 +128,7 @@ impl Renderer {
127 let mut visual_x = 0;
128 let mut visual_x = 0;
128 let mut line = 0u16;
129 let mut line = 0u16;
129 let visible_selections: Vec<Range> = view
130 let visible_selections: Vec<Range> = view
131+ .doc
130 .state
132 .state
131 .selection()
133 .selection()
132 .ranges()
134 .ranges()
@@ -147,10 +149,10 @@ impl Renderer {
147 HighlightEvent::Source { start, end } => {
149 HighlightEvent::Source { start, end } => {
148 // TODO: filter out spans out of viewport for now..
150 // TODO: filter out spans out of viewport for now..
149
151
150− let start = view.state.doc().byte_to_char(start);
152+ let start = view.doc.text().byte_to_char(start);
151− let end = view.state.doc().byte_to_char(end); // <-- index 744, len 743
153+ let end = view.doc.text().byte_to_char(end); // <-- index 744, len 743
152
154
153− let text = view.state.doc().slice(start..end);
155+ let text = view.doc.text().slice(start..end);
154
156
155 use helix_core::graphemes::{grapheme_width, RopeGraphemes};
157 use helix_core::graphemes::{grapheme_width, RopeGraphemes};
156
158
@@ -207,7 +209,7 @@ impl Renderer {
207
209
208 // ugh, improve with a traverse method
210 // ugh, improve with a traverse method
209 // or interleave highlight spans with selection and diagnostic spans
211 // or interleave highlight spans with selection and diagnostic spans
210− let style = if view.state.diagnostics.iter().any(|diagnostic| {
212+ let style = if view.doc.diagnostics.iter().any(|diagnostic| {
211 diagnostic.range.0 <= char_index && diagnostic.range.1 > char_index
213 diagnostic.range.0 <= char_index && diagnostic.range.1 > char_index
212 }) {
214 }) {
213 style.clone().add_modifier(Modifier::UNDERLINED)
215 style.clone().add_modifier(Modifier::UNDERLINED)
@@ -233,7 +235,7 @@ impl Renderer {
233 let warning: Style = theme.get("warning");
235 let warning: Style = theme.get("warning");
234 let last_line = view.last_line();
236 let last_line = view.last_line();
235 for (i, line) in (view.first_line..last_line).enumerate() {
237 for (i, line) in (view.first_line..last_line).enumerate() {
236− if view.state.diagnostics.iter().any(|d| d.line == line) {
238+ if view.doc.diagnostics.iter().any(|d| d.line == line) {
237 self.surface.set_stringn(0, i as u16, "●", 1, warning);
239 self.surface.set_stringn(0, i as u16, "●", 1, warning);
238 }
240 }
239
241
@@ -243,7 +245,7 @@ impl Renderer {
243 }
245 }
244
246
245 pub fn render_statusline(&mut self, view: &View, theme: &Theme) {
247 pub fn render_statusline(&mut self, view: &View, theme: &Theme) {
246− let mode = match view.state.mode() {
248+ let mode = match view.doc.mode() {
247 Mode::Insert => "INS",
249 Mode::Insert => "INS",
248 Mode::Normal => "NOR",
250 Mode::Normal => "NOR",
249 Mode::Goto => "GOTO",
251 Mode::Goto => "GOTO",
@@ -259,7 +261,7 @@ impl Renderer {
259 self.surface.set_string(
261 self.surface.set_string(
260 self.size.0 - 10,
262 self.size.0 - 10,
261 self.size.1 - 2,
263 self.size.1 - 2,
262− format!("{}", view.state.diagnostics.len()),
264+ format!("{}", view.doc.diagnostics.len()),
263 self.text_color,
265 self.text_color,
264 );
266 );
265 }
267 }
@@ -329,14 +331,14 @@ impl Renderer {
329
331
330 pub fn render_cursor(&mut self, view: &View, prompt: Option<&Prompt>, viewport: Rect) {
332 pub fn render_cursor(&mut self, view: &View, prompt: Option<&Prompt>, viewport: Rect) {
331 let mut stdout = stdout();
333 let mut stdout = stdout();
332− match view.state.mode() {
334+ match view.doc.mode() {
333 Mode::Insert => write!(stdout, "\x1B[6 q"),
335 Mode::Insert => write!(stdout, "\x1B[6 q"),
334 mode => write!(stdout, "\x1B[2 q"),
336 mode => write!(stdout, "\x1B[2 q"),
335 };
337 };
336 let pos = if let Some(prompt) = prompt {
338 let pos = if let Some(prompt) = prompt {
337 Position::new(self.size.0 as usize, 2 + prompt.cursor)
339 Position::new(self.size.0 as usize, 2 + prompt.cursor)
338 } else {
340 } else {
339− if let Some(path) = view.state.path() {
341+ if let Some(path) = view.doc.path() {
340 self.surface.set_string(
342 self.surface.set_string(
341 6,
343 6,
342 self.size.1 - 1,
344 self.size.1 - 1,
@@ -345,10 +347,10 @@ impl Renderer {
345 );
347 );
346 }
348 }
347
349
348− let cursor = view.state.selection().cursor();
350+ let cursor = view.doc.state.selection().cursor();
349
351
350 let mut pos = view
352 let mut pos = view
351− .screen_coords_at_pos(&view.state.doc().slice(..), cursor)
353+ .screen_coords_at_pos(&view.doc.text().slice(..), cursor)
352 .expect("Cursor is out of bounds.");
354 .expect("Cursor is out of bounds.");
353 pos.col += viewport.x as usize;
355 pos.col += viewport.x as usize;
354 pos.row += viewport.y as usize;
356 pos.row += viewport.y as usize;
@@ -416,7 +418,7 @@ impl<'a> Application<'a> {
416 let res = self.lsp.initialize().await;
418 let res = self.lsp.initialize().await;
417 let res = self
419 let res = self
418 .lsp
420 .lsp
419− .text_document_did_open(&self.editor.view().unwrap().state)
421+ .text_document_did_open(&self.editor.view().unwrap().doc)
420 .await;
422 .await;
421
423
422 self.render();
424 self.render();
@@ -469,7 +471,7 @@ impl<'a> Application<'a> {
469 let keys = vec![event];
471 let keys = vec![event];
470 // TODO: sequences (`gg`)
472 // TODO: sequences (`gg`)
471 // TODO: handle count other than 1
473 // TODO: handle count other than 1
472− match view.state.mode() {
474+ match view.doc.mode() {
473 Mode::Insert => {
475 Mode::Insert => {
474 if let Some(command) = self.keymap[&Mode::Insert].get(&keys) {
476 if let Some(command) = self.keymap[&Mode::Insert].get(&keys) {
475 command(view, 1);
477 command(view, 1);
@@ -573,10 +575,10 @@ impl<'a> Application<'a> {
573 .editor
575 .editor
574 .views
576 .views
575 .iter_mut()
577 .iter_mut()
576− .find(|view| view.state.path == path);
578+ .find(|view| view.doc.path == path);
577
579
578 if let Some(view) = view {
580 if let Some(view) = view {
579− let doc = view.state.doc().slice(..);
581+ let doc = view.doc.text().slice(..);
580 let diagnostics = params
582 let diagnostics = params
581 .diagnostics
583 .diagnostics
582 .into_iter()
584 .into_iter()
@@ -596,7 +598,7 @@ impl<'a> Application<'a> {
596 })
598 })
597 .collect();
599 .collect();
598
600
599− view.state.diagnostics = diagnostics;
601+ view.doc.diagnostics = diagnostics;
600
602
601 self.render();
603 self.render();
602 }
604 }
helix-view/Cargo.toml+1
@@ -19,3 +19,4 @@ helix-core = { path = "../helix-core" }
19tui = { git = "https://github.com/fdehau/tui-rs", default-features = false, features = ["crossterm"], optional = true}
19tui = { git = "https://github.com/fdehau/tui-rs", default-features = false, features = ["crossterm"], optional = true}
20crossterm = { version = "0.18", features = ["event-stream"], optional = true}
20crossterm = { version = "0.18", features = ["event-stream"], optional = true}
21once_cell = "1.4"
21once_cell = "1.4"
22+url = "2"
helix-view/src/commands.rs+136−119
@@ -3,12 +3,13 @@ use helix_core::{
3 indent::TAB_WIDTH,
3 indent::TAB_WIDTH,
4 regex::Regex,
4 regex::Regex,
5 register, selection,
5 register, selection,
6− state::{Direction, Granularity, Mode, State},
6+ state::{Direction, Granularity, State},
7 ChangeSet, Range, Selection, Tendril, Transaction,
7 ChangeSet, Range, Selection, Tendril, Transaction,
8};
8};
9use once_cell::sync::Lazy;
9use once_cell::sync::Lazy;
10
10
11use crate::{
11use crate::{
12+ document::Mode,
12 prompt::Prompt,
13 prompt::Prompt,
13 view::{View, PADDING},
14 view::{View, PADDING},
14};
15};
@@ -19,36 +20,40 @@ pub type Command = fn(view: &mut View, count: usize);
19
20
20pub fn move_char_left(view: &mut View, count: usize) {
21pub fn move_char_left(view: &mut View, count: usize) {
21 // TODO: use a transaction
22 // TODO: use a transaction
22− let selection = view
23+ let selection =
24+ view.doc
23− .state
25+ .state
24− .move_selection(Direction::Backward, Granularity::Character, count);
26+ .move_selection(Direction::Backward, Granularity::Character, count);
25− view.state.selection = selection;
27+ view.doc.state.selection = selection;
26}
28}
27
29
28pub fn move_char_right(view: &mut View, count: usize) {
30pub fn move_char_right(view: &mut View, count: usize) {
29 // TODO: use a transaction
31 // TODO: use a transaction
30− view.state.selection =
32+ view.doc.state.selection =
33+ view.doc
31− view.state
34+ .state
32 .move_selection(Direction::Forward, Granularity::Character, count);
35 .move_selection(Direction::Forward, Granularity::Character, count);
33}
36}
34
37
35pub fn move_line_up(view: &mut View, count: usize) {
38pub fn move_line_up(view: &mut View, count: usize) {
36 // TODO: use a transaction
39 // TODO: use a transaction
37− view.state.selection = view
40+ view.doc.state.selection =
41+ view.doc
38− .state
42+ .state
39− .move_selection(Direction::Backward, Granularity::Line, count);
43+ .move_selection(Direction::Backward, Granularity::Line, count);
40}
44}
41
45
42pub fn move_line_down(view: &mut View, count: usize) {
46pub fn move_line_down(view: &mut View, count: usize) {
43 // TODO: use a transaction
47 // TODO: use a transaction
44− view.state.selection = view
48+ view.doc.state.selection =
49+ view.doc
45− .state
50+ .state
46− .move_selection(Direction::Forward, Granularity::Line, count);
51+ .move_selection(Direction::Forward, Granularity::Line, count);
47}
52}
48
53
49pub fn move_line_end(view: &mut View, _count: usize) {
54pub fn move_line_end(view: &mut View, _count: usize) {
50 // TODO: use a transaction
55 // TODO: use a transaction
51− let lines = selection_lines(&view.state);
56+ let lines = selection_lines(&view.doc.state);
52
57
53 let positions = lines
58 let positions = lines
54 .into_iter()
59 .into_iter()
@@ -57,89 +62,89 @@ pub fn move_line_end(view: &mut View, _count: usize) {
57
62
58 // Line end is pos at the start of next line - 1
63 // Line end is pos at the start of next line - 1
59 // subtract another 1 because the line ends with \n
64 // subtract another 1 because the line ends with \n
60− view.state.doc.line_to_char(index + 1).saturating_sub(2)
65+ view.doc.text().line_to_char(index + 1).saturating_sub(2)
61 })
66 })
62 .map(|pos| Range::new(pos, pos));
67 .map(|pos| Range::new(pos, pos));
63
68
64 let selection = Selection::new(positions.collect(), 0);
69 let selection = Selection::new(positions.collect(), 0);
65
70
66− let transaction = Transaction::new(&mut view.state).with_selection(selection);
71+ let transaction = Transaction::new(&mut view.doc.state).with_selection(selection);
67
72
68− transaction.apply(&mut view.state);
73+ view.doc.apply(&transaction);
69}
74}
70
75
71pub fn move_line_start(view: &mut View, _count: usize) {
76pub fn move_line_start(view: &mut View, _count: usize) {
72− let lines = selection_lines(&view.state);
77+ let lines = selection_lines(&view.doc.state);
73
78
74 let positions = lines
79 let positions = lines
75 .into_iter()
80 .into_iter()
76 .map(|index| {
81 .map(|index| {
77 // adjust all positions to the start of the line.
82 // adjust all positions to the start of the line.
78− view.state.doc.line_to_char(index)
83+ view.doc.text().line_to_char(index)
79 })
84 })
80 .map(|pos| Range::new(pos, pos));
85 .map(|pos| Range::new(pos, pos));
81
86
82 let selection = Selection::new(positions.collect(), 0);
87 let selection = Selection::new(positions.collect(), 0);
83
88
84− let transaction = Transaction::new(&mut view.state).with_selection(selection);
89+ let transaction = Transaction::new(&mut view.doc.state).with_selection(selection);
85
90
86− transaction.apply(&mut view.state);
91+ view.doc.apply(&transaction);
87}
92}
88
93
89pub fn move_next_word_start(view: &mut View, count: usize) {
94pub fn move_next_word_start(view: &mut View, count: usize) {
90− let pos = view.state.move_pos(
95+ let pos = view.doc.state.move_pos(
91− view.state.selection.cursor(),
96+ view.doc.state.selection.cursor(),
92 Direction::Forward,
97 Direction::Forward,
93 Granularity::Word,
98 Granularity::Word,
94 count,
99 count,
95 );
100 );
96
101
97 // TODO: use a transaction
102 // TODO: use a transaction
98− view.state.selection = Selection::single(pos, pos);
103+ view.doc.state.selection = Selection::single(pos, pos);
99}
104}
100
105
101pub fn move_prev_word_start(view: &mut View, count: usize) {
106pub fn move_prev_word_start(view: &mut View, count: usize) {
102− let pos = view.state.move_pos(
107+ let pos = view.doc.state.move_pos(
103− view.state.selection.cursor(),
108+ view.doc.state.selection.cursor(),
104 Direction::Backward,
109 Direction::Backward,
105 Granularity::Word,
110 Granularity::Word,
106 count,
111 count,
107 );
112 );
108
113
109 // TODO: use a transaction
114 // TODO: use a transaction
110− view.state.selection = Selection::single(pos, pos);
115+ view.doc.state.selection = Selection::single(pos, pos);
111}
116}
112
117
113pub fn move_next_word_end(view: &mut View, count: usize) {
118pub fn move_next_word_end(view: &mut View, count: usize) {
114 let pos = State::move_next_word_end(
119 let pos = State::move_next_word_end(
115− &view.state.doc().slice(..),
120+ &view.doc.text().slice(..),
116− view.state.selection.cursor(),
121+ view.doc.state.selection.cursor(),
117 count,
122 count,
118 );
123 );
119
124
120 // TODO: use a transaction
125 // TODO: use a transaction
121− view.state.selection = Selection::single(pos, pos);
126+ view.doc.state.selection = Selection::single(pos, pos);
122}
127}
123
128
124pub fn move_file_start(view: &mut View, _count: usize) {
129pub fn move_file_start(view: &mut View, _count: usize) {
125 // TODO: use a transaction
130 // TODO: use a transaction
126− view.state.selection = Selection::single(0, 0);
131+ view.doc.state.selection = Selection::single(0, 0);
127
132
128− view.state.mode = Mode::Normal;
133+ view.doc.mode = Mode::Normal;
129}
134}
130
135
131pub fn move_file_end(view: &mut View, _count: usize) {
136pub fn move_file_end(view: &mut View, _count: usize) {
132 // TODO: use a transaction
137 // TODO: use a transaction
133− let text = &view.state.doc;
138+ let text = &view.doc.text();
134 let last_line = text.line_to_char(text.len_lines().saturating_sub(2));
139 let last_line = text.line_to_char(text.len_lines().saturating_sub(2));
135− view.state.selection = Selection::single(last_line, last_line);
140+ view.doc.state.selection = Selection::single(last_line, last_line);
136
141
137− view.state.mode = Mode::Normal;
142+ view.doc.mode = Mode::Normal;
138}
143}
139
144
140pub fn check_cursor_in_view(view: &mut View) -> bool {
145pub fn check_cursor_in_view(view: &mut View) -> bool {
141− let cursor = view.state.selection().cursor();
146+ let cursor = view.doc.state.selection().cursor();
142− let line = view.state.doc().char_to_line(cursor);
147+ let line = view.doc.text().char_to_line(cursor);
143 let document_end = view.first_line + view.size.1.saturating_sub(1) as usize;
148 let document_end = view.first_line + view.size.1.saturating_sub(1) as usize;
144
149
145 if (line > document_end.saturating_sub(PADDING)) | (line < view.first_line + PADDING) {
150 if (line > document_end.saturating_sub(PADDING)) | (line < view.first_line + PADDING) {
@@ -156,19 +161,19 @@ pub fn page_up(view: &mut View, _count: usize) {
156 view.first_line = view.first_line.saturating_sub(view.size.1 as usize);
161 view.first_line = view.first_line.saturating_sub(view.size.1 as usize);
157
162
158 if !check_cursor_in_view(view) {
163 if !check_cursor_in_view(view) {
159− let text = view.state.doc();
164+ let text = view.doc.text();
160 let pos = text.line_to_char(view.last_line().saturating_sub(PADDING));
165 let pos = text.line_to_char(view.last_line().saturating_sub(PADDING));
161− view.state.selection = Selection::single(pos, pos);
166+ view.doc.state.selection = Selection::single(pos, pos);
162 }
167 }
163}
168}
164
169
165pub fn page_down(view: &mut View, _count: usize) {
170pub fn page_down(view: &mut View, _count: usize) {
166 view.first_line += view.size.1 as usize + PADDING;
171 view.first_line += view.size.1 as usize + PADDING;
167
172
168− if view.first_line < view.state.doc().len_lines() {
173+ if view.first_line < view.doc.text().len_lines() {
169− let text = view.state.doc();
174+ let text = view.doc.text();
170 let pos = text.line_to_char(view.first_line as usize);
175 let pos = text.line_to_char(view.first_line as usize);
171− view.state.selection = Selection::single(pos, pos);
176+ view.doc.state.selection = Selection::single(pos, pos);
172 }
177 }
173}
178}
174
179
@@ -180,79 +185,84 @@ pub fn half_page_up(view: &mut View, _count: usize) {
180 view.first_line = view.first_line.saturating_sub(view.size.1 as usize / 2);
185 view.first_line = view.first_line.saturating_sub(view.size.1 as usize / 2);
181
186
182 if !check_cursor_in_view(view) {
187 if !check_cursor_in_view(view) {
183− let text = &view.state.doc;
188+ let text = &view.doc.text();
184 let pos = text.line_to_char(view.last_line() - PADDING);
189 let pos = text.line_to_char(view.last_line() - PADDING);
185− view.state.selection = Selection::single(pos, pos);
190+ view.doc.state.selection = Selection::single(pos, pos);
186 }
191 }
187}
192}
188
193
189pub fn half_page_down(view: &mut View, _count: usize) {
194pub fn half_page_down(view: &mut View, _count: usize) {
190− let lines = view.state.doc().len_lines();
195+ let lines = view.doc.text().len_lines();
191 if view.first_line < lines.saturating_sub(view.size.1 as usize) {
196 if view.first_line < lines.saturating_sub(view.size.1 as usize) {
192 view.first_line += view.size.1 as usize / 2;
197 view.first_line += view.size.1 as usize / 2;
193 }
198 }
194 if !check_cursor_in_view(view) {
199 if !check_cursor_in_view(view) {
195− let text = view.state.doc();
200+ let text = view.doc.text();
196 let pos = text.line_to_char(view.first_line as usize);
201 let pos = text.line_to_char(view.first_line as usize);
197− view.state.selection = Selection::single(pos, pos);
202+ view.doc.state.selection = Selection::single(pos, pos);
198 }
203 }
199}
204}
200// avoid select by default by having a visual mode switch that makes movements into selects
205// avoid select by default by having a visual mode switch that makes movements into selects
201
206
202pub fn extend_char_left(view: &mut View, count: usize) {
207pub fn extend_char_left(view: &mut View, count: usize) {
203 // TODO: use a transaction
208 // TODO: use a transaction
204− let selection = view
209+ let selection =
210+ view.doc
205− .state
211+ .state
206− .extend_selection(Direction::Backward, Granularity::Character, count);
212+ .extend_selection(Direction::Backward, Granularity::Character, count);
207− view.state.selection = selection;
213+ view.doc.state.selection = selection;
208}
214}
209
215
210pub fn extend_char_right(view: &mut View, count: usize) {
216pub fn extend_char_right(view: &mut View, count: usize) {
211 // TODO: use a transaction
217 // TODO: use a transaction
212− view.state.selection =
218+ view.doc.state.selection =
219+ view.doc
213− view.state
220+ .state
214 .extend_selection(Direction::Forward, Granularity::Character, count);
221 .extend_selection(Direction::Forward, Granularity::Character, count);
215}
222}
216
223
217pub fn extend_line_up(view: &mut View, count: usize) {
224pub fn extend_line_up(view: &mut View, count: usize) {
218 // TODO: use a transaction
225 // TODO: use a transaction
219− view.state.selection =
226+ view.doc.state.selection =
227+ view.doc
220− view.state
228+ .state
221 .extend_selection(Direction::Backward, Granularity::Line, count);
229 .extend_selection(Direction::Backward, Granularity::Line, count);
222}
230}
223
231
224pub fn extend_line_down(view: &mut View, count: usize) {
232pub fn extend_line_down(view: &mut View, count: usize) {
225 // TODO: use a transaction
233 // TODO: use a transaction
226− view.state.selection =
234+ view.doc.state.selection =
235+ view.doc
227− view.state
236+ .state
228 .extend_selection(Direction::Forward, Granularity::Line, count);
237 .extend_selection(Direction::Forward, Granularity::Line, count);
229}
238}
230
239
231pub fn split_selection_on_newline(view: &mut View, _count: usize) {
240pub fn split_selection_on_newline(view: &mut View, _count: usize) {
232− let text = &view.state.doc.slice(..);
241+ let text = &view.doc.text().slice(..);
233 // only compile the regex once
242 // only compile the regex once
234 #[allow(clippy::trivial_regex)]
243 #[allow(clippy::trivial_regex)]
235 static REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(r"\n").unwrap());
244 static REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(r"\n").unwrap());
236 // TODO: use a transaction
245 // TODO: use a transaction
237− view.state.selection = selection::split_on_matches(text, view.state.selection(), &REGEX)
246+ view.doc.state.selection = selection::split_on_matches(text, view.doc.state.selection(), &REGEX)
238}
247}
239
248
240pub fn select_line(view: &mut View, _count: usize) {
249pub fn select_line(view: &mut View, _count: usize) {
241 // TODO: count
250 // TODO: count
242− let pos = view.state.selection().primary();
251+ let pos = view.doc.state.selection().primary();
243− let text = view.state.doc();
252+ let text = view.doc.text();
244 let line = text.char_to_line(pos.head);
253 let line = text.char_to_line(pos.head);
245 let start = text.line_to_char(line);
254 let start = text.line_to_char(line);
246 let end = text.line_to_char(line + 1).saturating_sub(1);
255 let end = text.line_to_char(line + 1).saturating_sub(1);
247
256
248 // TODO: use a transaction
257 // TODO: use a transaction
249− view.state.selection = Selection::single(start, end);
258+ view.doc.state.selection = Selection::single(start, end);
250}
259}
251
260
252pub fn delete_selection(view: &mut View, _count: usize) {
261pub fn delete_selection(view: &mut View, _count: usize) {
253− let transaction =
254− Transaction::change_by_selection(&view.state, |range| (range.from(), range.to() + 1, None));
262+ let transaction = Transaction::change_by_selection(&view.doc.state, |range| {
255− transaction.apply(&mut view.state);
263+ (range.from(), range.to() + 1, None)
264+ });
265+ view.doc.apply(&transaction);
256
266
257 append_changes_to_history(view);
267 append_changes_to_history(view);
258}
268}
@@ -263,21 +273,23 @@ pub fn change_selection(view: &mut View, count: usize) {
263}
273}
264
274
265pub fn collapse_selection(view: &mut View, _count: usize) {
275pub fn collapse_selection(view: &mut View, _count: usize) {
266− view.state.selection = view
276+ view.doc.state.selection = view
277+ .doc
267 .state
278 .state
268 .selection
279 .selection
269 .transform(|range| Range::new(range.head, range.head))
280 .transform(|range| Range::new(range.head, range.head))
270}
281}
271
282
272pub fn flip_selections(view: &mut View, _count: usize) {
283pub fn flip_selections(view: &mut View, _count: usize) {
273− view.state.selection = view
284+ view.doc.state.selection = view
285+ .doc
274 .state
286 .state
275 .selection
287 .selection
276 .transform(|range| Range::new(range.head, range.anchor))
288 .transform(|range| Range::new(range.head, range.anchor))
277}
289}
278
290
279fn enter_insert_mode(view: &mut View) {
291fn enter_insert_mode(view: &mut View) {
280− view.state.mode = Mode::Insert;
292+ view.doc.mode = Mode::Insert;
281
293
282 append_changes_to_history(view);
294 append_changes_to_history(view);
283}
295}
@@ -285,7 +297,8 @@ fn enter_insert_mode(view: &mut View) {
285pub fn insert_mode(view: &mut View, _count: usize) {
297pub fn insert_mode(view: &mut View, _count: usize) {
286 enter_insert_mode(view);
298 enter_insert_mode(view);
287
299
288− view.state.selection = view
300+ view.doc.state.selection = view
301+ .doc
289 .state
302 .state
290 .selection
303 .selection
291 .transform(|range| Range::new(range.to(), range.from()))
304 .transform(|range| Range::new(range.to(), range.from()))
@@ -294,11 +307,11 @@ pub fn insert_mode(view: &mut View, _count: usize) {
294// inserts at the end of each selection
307// inserts at the end of each selection
295pub fn append_mode(view: &mut View, _count: usize) {
308pub fn append_mode(view: &mut View, _count: usize) {
296 enter_insert_mode(view);
309 enter_insert_mode(view);
297− view.state.restore_cursor = true;
310+ view.doc.restore_cursor = true;
298
311
299 // TODO: as transaction
312 // TODO: as transaction
300− let text = &view.state.doc.slice(..);
313+ let text = &view.doc.text().slice(..);
301− view.state.selection = view.state.selection.transform(|range| {
314+ view.doc.state.selection = view.doc.state.selection.transform(|range| {
302 // TODO: to() + next char
315 // TODO: to() + next char
303 Range::new(
316 Range::new(
304 range.from(),
317 range.from(),
@@ -346,13 +359,13 @@ pub fn append_to_line(view: &mut View, count: usize) {
346pub fn open_below(view: &mut View, _count: usize) {
359pub fn open_below(view: &mut View, _count: usize) {
347 enter_insert_mode(view);
360 enter_insert_mode(view);
348
361
349− let lines = selection_lines(&view.state);
362+ let lines = selection_lines(&view.doc.state);
350
363
351 let positions: Vec<_> = lines
364 let positions: Vec<_> = lines
352 .into_iter()
365 .into_iter()
353 .map(|index| {
366 .map(|index| {
354 // adjust all positions to the end of the line/start of the next one.
367 // adjust all positions to the end of the line/start of the next one.
355− view.state.doc.line_to_char(index + 1)
368+ view.doc.text().line_to_char(index + 1)
356 })
369 })
357 .collect();
370 .collect();
358
371
@@ -373,63 +386,63 @@ pub fn open_below(view: &mut View, _count: usize) {
373 0,
386 0,
374 );
387 );
375
388
376− let transaction = Transaction::change(&view.state, changes).with_selection(selection);
389+ let transaction = Transaction::change(&view.doc.state, changes).with_selection(selection);
377
390
378− transaction.apply(&mut view.state);
391+ view.doc.apply(&transaction);
379}
392}
380
393
381// O inserts a new line before each line with a selection
394// O inserts a new line before each line with a selection
382
395
383fn append_changes_to_history(view: &mut View) {
396fn append_changes_to_history(view: &mut View) {
384− if view.state.changes.is_empty() {
397+ if view.doc.changes.is_empty() {
385 return;
398 return;
386 }
399 }
387
400
388− let new_changeset = ChangeSet::new(view.state.doc());
401+ let new_changeset = ChangeSet::new(view.doc.text());
389− let changes = std::mem::replace(&mut view.state.changes, new_changeset);
402+ let changes = std::mem::replace(&mut view.doc.changes, new_changeset);
390 // Instead of doing this messy merge we could always commit, and based on transaction
403 // Instead of doing this messy merge we could always commit, and based on transaction
391 // annotations either add a new layer or compose into the previous one.
404 // annotations either add a new layer or compose into the previous one.
392− let transaction = Transaction::from(changes).with_selection(view.state.selection().clone());
405+ let transaction = Transaction::from(changes).with_selection(view.doc.state.selection().clone());
393
406
394 // increment document version
407 // increment document version
395 // TODO: needs to happen on undo/redo too
408 // TODO: needs to happen on undo/redo too
396− view.state.version += 1;
409+ view.doc.version += 1;
397
410
398 // TODO: trigger lsp/documentDidChange with changes
411 // TODO: trigger lsp/documentDidChange with changes
399
412
400 // HAXX: we need to reconstruct the state as it was before the changes..
413 // HAXX: we need to reconstruct the state as it was before the changes..
401− let (doc, selection) = view.state.old_state.take().unwrap();
414+ let (doc, selection) = view.doc.old_state.take().unwrap();
402 let mut old_state = State::new(doc);
415 let mut old_state = State::new(doc);
403 old_state.selection = selection;
416 old_state.selection = selection;
404
417
405 // TODO: take transaction by value?
418 // TODO: take transaction by value?
406− view.history.commit_revision(&transaction, &old_state);
419+ view.doc.history.commit_revision(&transaction, &old_state);
407
420
408 // HAXX
421 // HAXX
409− view.state.old_state = Some((view.state.doc().clone(), view.state.selection.clone()));
422+ view.doc.old_state = Some((view.doc.text().clone(), view.doc.state.selection.clone()));
410}
423}
411
424
412pub fn normal_mode(view: &mut View, _count: usize) {
425pub fn normal_mode(view: &mut View, _count: usize) {
413− view.state.mode = Mode::Normal;
426+ view.doc.mode = Mode::Normal;
414
427
415 append_changes_to_history(view);
428 append_changes_to_history(view);
416
429
417 // if leaving append mode, move cursor back by 1
430 // if leaving append mode, move cursor back by 1
418− if view.state.restore_cursor {
431+ if view.doc.restore_cursor {
419− let text = &view.state.doc.slice(..);
432+ let text = &view.doc.text().slice(..);
420− view.state.selection = view.state.selection.transform(|range| {
433+ view.doc.state.selection = view.doc.state.selection.transform(|range| {
421 Range::new(
434 Range::new(
422 range.from(),
435 range.from(),
423 graphemes::prev_grapheme_boundary(text, range.to()),
436 graphemes::prev_grapheme_boundary(text, range.to()),
424 )
437 )
425 });
438 });
426
439
427− view.state.restore_cursor = false;
440+ view.doc.restore_cursor = false;
428 }
441 }
429}
442}
430
443
431pub fn goto_mode(view: &mut View, _count: usize) {
444pub fn goto_mode(view: &mut View, _count: usize) {
432− view.state.mode = Mode::Goto;
445+ view.doc.mode = Mode::Goto;
433}
446}
434
447
435// NOTE: Transactions in this module get appended to history when we switch back to normal mode.
448// NOTE: Transactions in this module get appended to history when we switch back to normal mode.
@@ -438,9 +451,9 @@ pub mod insert {
438 // TODO: insert means add text just before cursor, on exit we should be on the last letter.
451 // TODO: insert means add text just before cursor, on exit we should be on the last letter.
439 pub fn insert_char(view: &mut View, c: char) {
452 pub fn insert_char(view: &mut View, c: char) {
440 let c = Tendril::from_char(c);
453 let c = Tendril::from_char(c);
441− let transaction = Transaction::insert(&view.state, c);
454+ let transaction = Transaction::insert(&view.doc.state, c);
442
455
443− transaction.apply(&mut view.state);
456+ view.doc.apply(&transaction);
444 }
457 }
445
458
446 pub fn insert_tab(view: &mut View, _count: usize) {
459 pub fn insert_tab(view: &mut View, _count: usize) {
@@ -448,41 +461,44 @@ pub mod insert {
448 }
461 }
449
462
450 pub fn insert_newline(view: &mut View, _count: usize) {
463 pub fn insert_newline(view: &mut View, _count: usize) {
451− let transaction = Transaction::change_by_selection(&view.state, |range| {
464+ let transaction = Transaction::change_by_selection(&view.doc.state, |range| {
452− let indent_level =
453− helix_core::indent::suggested_indent_for_pos(&view.state, range.head);
465+ let indent_level = helix_core::indent::suggested_indent_for_pos(
466+ view.doc.syntax.as_ref(),
467+ &view.doc.state,
468+ range.head,
469+ );
454 let indent = " ".repeat(TAB_WIDTH).repeat(indent_level);
470 let indent = " ".repeat(TAB_WIDTH).repeat(indent_level);
455 let mut text = String::with_capacity(1 + indent.len());
471 let mut text = String::with_capacity(1 + indent.len());
456 text.push('\n');
472 text.push('\n');
457 text.push_str(&indent);
473 text.push_str(&indent);
458 (range.head, range.head, Some(text.into()))
474 (range.head, range.head, Some(text.into()))
459 });
475 });
460− transaction.apply(&mut view.state);
476+ view.doc.apply(&transaction);
461 }
477 }
462
478
463 // TODO: handle indent-aware delete
479 // TODO: handle indent-aware delete
464 pub fn delete_char_backward(view: &mut View, count: usize) {
480 pub fn delete_char_backward(view: &mut View, count: usize) {
465− let text = &view.state.doc.slice(..);
481+ let text = &view.doc.text().slice(..);
466− let transaction = Transaction::change_by_selection(&view.state, |range| {
482+ let transaction = Transaction::change_by_selection(&view.doc.state, |range| {
467 (
483 (
468 graphemes::nth_prev_grapheme_boundary(text, range.head, count),
484 graphemes::nth_prev_grapheme_boundary(text, range.head, count),
469 range.head,
485 range.head,
470 None,
486 None,
471 )
487 )
472 });
488 });
473− transaction.apply(&mut view.state);
489+ view.doc.apply(&transaction);
474 }
490 }
475
491
476 pub fn delete_char_forward(view: &mut View, count: usize) {
492 pub fn delete_char_forward(view: &mut View, count: usize) {
477− let text = &view.state.doc.slice(..);
493+ let text = &view.doc.text().slice(..);
478− let transaction = Transaction::change_by_selection(&view.state, |range| {
494+ let transaction = Transaction::change_by_selection(&view.doc.state, |range| {
479 (
495 (
480 range.head,
496 range.head,
481 graphemes::nth_next_grapheme_boundary(text, range.head, count),
497 graphemes::nth_next_grapheme_boundary(text, range.head, count),
482 None,
498 None,
483 )
499 )
484 });
500 });
485− transaction.apply(&mut view.state);
501+ view.doc.apply(&transaction);
486 }
502 }
487}
503}
488
504
@@ -493,13 +509,13 @@ pub fn insert_char_prompt(prompt: &mut Prompt, c: char) {
493// Undo / Redo
509// Undo / Redo
494
510
495pub fn undo(view: &mut View, _count: usize) {
511pub fn undo(view: &mut View, _count: usize) {
496− view.history.undo(&mut view.state);
512+ view.doc.history.undo(&mut view.doc.state);
497
513
498 // TODO: each command could simply return a Option<transaction>, then the higher level handles storing it?
514 // TODO: each command could simply return a Option<transaction>, then the higher level handles storing it?
499}
515}
500
516
501pub fn redo(view: &mut View, _count: usize) {
517pub fn redo(view: &mut View, _count: usize) {
502− view.history.redo(&mut view.state);
518+ view.doc.history.redo(&mut view.doc.state);
503}
519}
504
520
505// Yank / Paste
521// Yank / Paste
@@ -507,9 +523,10 @@ pub fn redo(view: &mut View, _count: usize) {
507pub fn yank(view: &mut View, _count: usize) {
523pub fn yank(view: &mut View, _count: usize) {
508 // TODO: should selections be made end inclusive?
524 // TODO: should selections be made end inclusive?
509 let values = view
525 let values = view
526+ .doc
510 .state
527 .state
511 .selection()
528 .selection()
512− .fragments(&view.state.doc().slice(..))
529+ .fragments(&view.doc.text().slice(..))
513 .map(|cow| cow.into_owned())
530 .map(|cow| cow.into_owned())
514 .collect();
531 .collect();
515
532
@@ -550,18 +567,18 @@ pub fn paste(view: &mut View, _count: usize) {
550 let transaction = if linewise {
567 let transaction = if linewise {
551 // paste on the next line
568 // paste on the next line
552 // TODO: can simply take a range + modifier and compute the right pos without ifs
569 // TODO: can simply take a range + modifier and compute the right pos without ifs
553− let text = view.state.doc();
570+ let text = view.doc.text();
554− Transaction::change_by_selection(&view.state, |range| {
571+ Transaction::change_by_selection(&view.doc.state, |range| {
555 let line_end = text.line_to_char(text.char_to_line(range.head) + 1);
572 let line_end = text.line_to_char(text.char_to_line(range.head) + 1);
556 (line_end, line_end, Some(values.next().unwrap()))
573 (line_end, line_end, Some(values.next().unwrap()))
557 })
574 })
558 } else {
575 } else {
559− Transaction::change_by_selection(&view.state, |range| {
576+ Transaction::change_by_selection(&view.doc.state, |range| {
560 (range.head + 1, range.head + 1, Some(values.next().unwrap()))
577 (range.head + 1, range.head + 1, Some(values.next().unwrap()))
561 })
578 })
562 };
579 };
563
580
564− transaction.apply(&mut view.state);
581+ view.doc.apply(&transaction);
565 append_changes_to_history(view);
582 append_changes_to_history(view);
566 }
583 }
567}
584}
@@ -570,9 +587,9 @@ fn get_lines(view: &View) -> Vec<usize> {
570 let mut lines = Vec::new();
587 let mut lines = Vec::new();
571
588
572 // Get all line numbers
589 // Get all line numbers
573− for range in view.state.selection.ranges() {
590+ for range in view.doc.state.selection.ranges() {
574− let start = view.state.doc.char_to_line(range.from());
591+ let start = view.doc.text().char_to_line(range.from());
575− let end = view.state.doc.char_to_line(range.to());
592+ let end = view.doc.text().char_to_line(range.to());
576
593
577 for line in start..=end {
594 for line in start..=end {
578 lines.push(line)
595 lines.push(line)
@@ -590,13 +607,13 @@ pub fn indent(view: &mut View, _count: usize) {
590 let indent = Tendril::from(" ".repeat(TAB_WIDTH));
607 let indent = Tendril::from(" ".repeat(TAB_WIDTH));
591
608
592 let transaction = Transaction::change(
609 let transaction = Transaction::change(
593− &view.state,
610+ &view.doc.state,
594 lines.into_iter().map(|line| {
611 lines.into_iter().map(|line| {
595− let pos = view.state.doc.line_to_char(line);
612+ let pos = view.doc.text().line_to_char(line);
596 (pos, pos, Some(indent.clone()))
613 (pos, pos, Some(indent.clone()))
597 }),
614 }),
598 );
615 );
599− transaction.apply(&mut view.state);
616+ view.doc.apply(&transaction);
600 append_changes_to_history(view);
617 append_changes_to_history(view);
601}
618}
602
619
@@ -605,7 +622,7 @@ pub fn unindent(view: &mut View, _count: usize) {
605 let mut changes = Vec::with_capacity(lines.len());
622 let mut changes = Vec::with_capacity(lines.len());
606
623
607 for line_idx in lines {
624 for line_idx in lines {
608− let line = view.state.doc.line(line_idx);
625+ let line = view.doc.text().line(line_idx);
609 let mut width = 0;
626 let mut width = 0;
610
627
611 for ch in line.chars() {
628 for ch in line.chars() {
@@ -621,14 +638,14 @@ pub fn unindent(view: &mut View, _count: usize) {
621 }
638 }
622
639
623 if width > 0 {
640 if width > 0 {
624− let start = view.state.doc.line_to_char(line_idx);
641+ let start = view.doc.text().line_to_char(line_idx);
625 changes.push((start, start + width, None))
642 changes.push((start, start + width, None))
626 }
643 }
627 }
644 }
628
645
629− let transaction = Transaction::change(&view.state, changes.into_iter());
646+ let transaction = Transaction::change(&view.doc.state, changes.into_iter());
630
647
631− transaction.apply(&mut view.state);
648+ view.doc.apply(&transaction);
632 append_changes_to_history(view);
649 append_changes_to_history(view);
633}
650}
634
651
helix-view/src/document.rsnew file+157
@@ -0,0 +1,157 @@
1+use anyhow::Error;
2+use std::path::PathBuf;
3+
4+use helix_core::{
5+ syntax::LOADER, ChangeSet, Diagnostic, History, Position, Range, Rope, RopeSlice, Selection,
6+ State, Syntax, Transaction,
7+};
8+
9+#[derive(Copy, Clone, PartialEq, Eq, Hash)]
10+pub enum Mode {
11+ Normal,
12+ Insert,
13+ Goto,
14+}
15+
16+pub struct Document {
17+ pub state: State, // rope + selection
18+ /// File path on disk.
19+ pub path: Option<PathBuf>,
20+
21+ /// Current editing mode.
22+ pub mode: Mode,
23+ pub restore_cursor: bool,
24+
25+ /// Tree-sitter AST tree
26+ pub syntax: Option<Syntax>,
27+
28+ /// Pending changes since last history commit.
29+ pub changes: ChangeSet,
30+ pub history: History,
31+ pub version: i64, // should be usize?
32+ pub old_state: Option<(Rope, Selection)>,
33+
34+ pub diagnostics: Vec<Diagnostic>,
35+}
36+
37+/// Like std::mem::replace() except it allows the replacement value to be mapped from the
38+/// original value.
39+fn take_with<T, F>(mut_ref: &mut T, closure: F)
40+where
41+ F: FnOnce(T) -> T,
42+{
43+ use std::{panic, ptr};
44+
45+ unsafe {
46+ let old_t = ptr::read(mut_ref);
47+ let new_t = panic::catch_unwind(panic::AssertUnwindSafe(|| closure(old_t)))
48+ .unwrap_or_else(|_| ::std::process::abort());
49+ ptr::write(mut_ref, new_t);
50+ }
51+}
52+
53+use url::Url;
54+
55+impl Document {
56+ fn new(state: State) -> Self {
57+ let changes = ChangeSet::new(&state.doc);
58+ let old_state = Some((state.doc.clone(), Selection::single(0, 0)));
59+
60+ Self {
61+ path: None,
62+ state,
63+ mode: Mode::Normal,
64+ restore_cursor: false,
65+ syntax: None,
66+ changes,
67+ old_state,
68+ diagnostics: Vec::new(),
69+ version: 0,
70+ history: History::default(),
71+ }
72+ }
73+
74+ // TODO: passing scopes here is awkward
75+ pub fn load(path: PathBuf, scopes: &[String]) -> Result<Self, Error> {
76+ use std::{env, fs::File, io::BufReader};
77+ let _current_dir = env::current_dir()?;
78+
79+ let doc = Rope::from_reader(BufReader::new(File::open(path.clone())?))?;
80+
81+ // TODO: create if not found
82+
83+ let mut doc = Self::new(State::new(doc));
84+
85+ if let Some(language_config) = LOADER.language_config_for_file_name(path.as_path()) {
86+ let highlight_config = language_config.highlight_config(scopes).unwrap().unwrap();
87+ // TODO: config.configure(scopes) is now delayed, is that ok?
88+
89+ let syntax = Syntax::new(&doc.state.doc, highlight_config.clone());
90+
91+ doc.syntax = Some(syntax);
92+ };
93+
94+ // canonicalize path to absolute value
95+ doc.path = Some(std::fs::canonicalize(path)?);
96+
97+ Ok(doc)
98+ }
99+
100+ pub fn set_language(&mut self, scope: &str, scopes: &[String]) {
101+ if let Some(language_config) = LOADER.language_config_for_scope(scope) {
102+ let highlight_config = language_config.highlight_config(scopes).unwrap().unwrap();
103+ // TODO: config.configure(scopes) is now delayed, is that ok?
104+
105+ let syntax = Syntax::new(&self.state.doc, highlight_config.clone());
106+
107+ self.syntax = Some(syntax);
108+ };
109+ }
110+
111+ // TODO: needs to run on undo/redo
112+ pub fn apply(&mut self, transaction: &Transaction) -> bool {
113+ let old_doc = self.text().clone();
114+
115+ let success = transaction.apply(&mut self.state);
116+
117+ if !transaction.changes().is_empty() {
118+ // Compose this transaction with the previous one
119+ take_with(&mut self.changes, |changes| {
120+ changes.compose(transaction.changes().clone()).unwrap()
121+ });
122+
123+ // update tree-sitter syntax tree
124+ if let Some(syntax) = &mut self.syntax {
125+ // TODO: no unwrap
126+ syntax
127+ .update(&old_doc, &self.state.doc, transaction.changes())
128+ .unwrap();
129+ }
130+
131+ // TODO: map state.diagnostics over changes::map_pos too
132+ }
133+ success
134+ }
135+
136+ #[inline]
137+ pub fn mode(&self) -> Mode {
138+ self.mode
139+ }
140+
141+ #[inline]
142+ pub fn path(&self) -> Option<&PathBuf> {
143+ self.path.as_ref()
144+ }
145+
146+ pub fn url(&self) -> Option<Url> {
147+ self.path().map(|path| Url::from_file_path(path).unwrap())
148+ }
149+
150+ pub fn text(&self) -> &Rope {
151+ &self.state.doc
152+ }
153+
154+ // pub fn slice<R>(&self, range: R) -> RopeSlice where R: RangeBounds {
155+ // self.state.doc.slice
156+ // }
157+}
helix-view/src/editor.rs+3−4
@@ -1,6 +1,5 @@
1use crate::theme::Theme;
1use crate::theme::Theme;
2−use crate::View;
2+use crate::{Document, View};
3−use helix_core::State;
4
3
5use std::path::PathBuf;
4use std::path::PathBuf;
6
5
@@ -27,8 +26,8 @@ impl Editor {
27
26
28 pub fn open(&mut self, path: PathBuf, size: (u16, u16)) -> Result<(), Error> {
27 pub fn open(&mut self, path: PathBuf, size: (u16, u16)) -> Result<(), Error> {
29 let pos = self.views.len();
28 let pos = self.views.len();
30− let state = State::load(path, self.theme.scopes())?;
29+ let doc = Document::load(path, self.theme.scopes())?;
31− self.views.push(View::new(state, size)?);
30+ self.views.push(View::new(doc, size)?);
32 self.focus = pos;
31 self.focus = pos;
33 Ok(())
32 Ok(())
34 }
33 }
helix-view/src/keymap.rs+5−4
@@ -1,4 +1,5 @@
1use crate::commands::{self, Command};
1use crate::commands::{self, Command};
2+use crate::document::Mode;
2use helix_core::{hashmap, state};
3use helix_core::{hashmap, state};
3use std::collections::HashMap;
4use std::collections::HashMap;
4
5
@@ -88,7 +89,7 @@ pub use crossterm::event::{KeyCode, KeyEvent as Key, KeyModifiers as Modifiers};
88
89
89// TODO: could be trie based
90// TODO: could be trie based
90pub type Keymap = HashMap<Vec<Key>, Command>;
91pub type Keymap = HashMap<Vec<Key>, Command>;
91−pub type Keymaps = HashMap<state::Mode, Keymap>;
92+pub type Keymaps = HashMap<Mode, Keymap>;
92
93
93macro_rules! key {
94macro_rules! key {
94 ($ch:expr) => {
95 ($ch:expr) => {
@@ -128,7 +129,7 @@ macro_rules! ctrl {
128
129
129pub fn default() -> Keymaps {
130pub fn default() -> Keymaps {
130 hashmap!(
131 hashmap!(
131− state::Mode::Normal =>
132+ Mode::Normal =>
132 // as long as you cast the first item, rust is able to infer the other cases
133 // as long as you cast the first item, rust is able to infer the other cases
133 hashmap!(
134 hashmap!(
134 vec![key!('h')] => commands::move_char_left as Command,
135 vec![key!('h')] => commands::move_char_left as Command,
@@ -179,7 +180,7 @@ pub fn default() -> Keymaps {
179 vec![ctrl!('u')] => commands::half_page_up,
180 vec![ctrl!('u')] => commands::half_page_up,
180 vec![ctrl!('d')] => commands::half_page_down,
181 vec![ctrl!('d')] => commands::half_page_down,
181 ),
182 ),
182− state::Mode::Insert => hashmap!(
183+ Mode::Insert => hashmap!(
183 vec![Key {
184 vec![Key {
184 code: KeyCode::Esc,
185 code: KeyCode::Esc,
185 modifiers: Modifiers::NONE
186 modifiers: Modifiers::NONE
@@ -201,7 +202,7 @@ pub fn default() -> Keymaps {
201 modifiers: Modifiers::NONE
202 modifiers: Modifiers::NONE
202 }] => commands::insert::insert_tab,
203 }] => commands::insert::insert_tab,
203 ),
204 ),
204− state::Mode::Goto => hashmap!(
205+ Mode::Goto => hashmap!(
205 vec![Key {
206 vec![Key {
206 code: KeyCode::Esc,
207 code: KeyCode::Esc,
207 modifiers: Modifiers::NONE
208 modifiers: Modifiers::NONE
helix-view/src/lib.rs+2
@@ -1,10 +1,12 @@
1pub mod commands;
1pub mod commands;
2+pub mod document;
2pub mod editor;
3pub mod editor;
3pub mod keymap;
4pub mod keymap;
4pub mod prompt;
5pub mod prompt;
5pub mod theme;
6pub mod theme;
6pub mod view;
7pub mod view;
7
8
9+pub use document::Document;
8pub use editor::Editor;
10pub use editor::Editor;
9pub use theme::Theme;
11pub use theme::Theme;
10pub use view::View;
12pub use view::View;
helix-view/src/view.rs+29−11
@@ -2,10 +2,11 @@ use anyhow::Error;
2
2
3use std::borrow::Cow;
3use std::borrow::Cow;
4
4
5+use crate::Document;
5use helix_core::{
6use helix_core::{
6 graphemes::{grapheme_width, RopeGraphemes},
7 graphemes::{grapheme_width, RopeGraphemes},
7 indent::TAB_WIDTH,
8 indent::TAB_WIDTH,
8− History, Position, RopeSlice, State,
9+ Position, RopeSlice,
9};
10};
10use tui::layout::Rect;
11use tui::layout::Rect;
11
12
@@ -14,29 +15,25 @@ pub const PADDING: usize = 5;
14// TODO: view should be View { doc: Document(state, history,..) }
15// TODO: view should be View { doc: Document(state, history,..) }
15// since we can have multiple views into the same file
16// since we can have multiple views into the same file
16pub struct View {
17pub struct View {
17− pub state: State,
18+ pub doc: Document,
18 pub first_line: usize,
19 pub first_line: usize,
19 pub size: (u16, u16),
20 pub size: (u16, u16),
20−
21− // TODO: Doc fields
22− pub history: History,
23}
21}
24
22
25impl View {
23impl View {
26− pub fn new(state: State, size: (u16, u16)) -> Result<Self, Error> {
24+ pub fn new(doc: Document, size: (u16, u16)) -> Result<Self, Error> {
27 let view = Self {
25 let view = Self {
28− state,
26+ doc,
29 first_line: 0,
27 first_line: 0,
30 size,
28 size,
31− history: History::default(),
32 };
29 };
33
30
34 Ok(view)
31 Ok(view)
35 }
32 }
36
33
37 pub fn ensure_cursor_in_view(&mut self) {
34 pub fn ensure_cursor_in_view(&mut self) {
38− let cursor = self.state.selection().cursor();
35+ let cursor = self.doc.state.selection().cursor();
39− let line = self.state.doc().char_to_line(cursor);
36+ let line = self.doc.text().char_to_line(cursor);
40 let document_end = self.first_line + (self.size.1 as usize).saturating_sub(2);
37 let document_end = self.first_line + (self.size.1 as usize).saturating_sub(2);
41
38
42 // TODO: side scroll
39 // TODO: side scroll
@@ -56,7 +53,7 @@ impl View {
56 let viewport = Rect::new(6, 0, self.size.0, self.size.1 - 2); // - 2 for statusline and prompt
53 let viewport = Rect::new(6, 0, self.size.0, self.size.1 - 2); // - 2 for statusline and prompt
57 std::cmp::min(
54 std::cmp::min(
58 self.first_line + (viewport.height as usize),
55 self.first_line + (viewport.height as usize),
59− self.state.doc().len_lines() - 1,
56+ self.doc.text().len_lines() - 1,
60 )
57 )
61 }
58 }
62
59
@@ -88,4 +85,25 @@ impl View {
88
85
89 Some(Position::new(row, col))
86 Some(Position::new(row, col))
90 }
87 }
88+
89+ pub fn traverse<F>(&self, text: &RopeSlice, start: usize, end: usize, fun: F)
90+ where
91+ F: Fn(usize, usize),
92+ {
93+ let start = self.screen_coords_at_pos(text, start);
94+ let end = self.screen_coords_at_pos(text, end);
95+
96+ match (start, end) {
97+ // fully on screen
98+ (Some(start), Some(end)) => {
99+ // we want to calculate ends of lines for each char..
100+ }
101+ // from start to end of screen
102+ (Some(start), None) => {}
103+ // from start of screen to end
104+ (None, Some(end)) => {}
105+ // not on screen
106+ (None, None) => return,
107+ }
108+ }
91}
109}