on master help sign in
Refactor: Document type as a wrapper around barebones State.
commitb39849dde1b1277d14dbc4e2e1604e5d020db43d authorBlaž Hrastnik <blaz@mxxn.io> dateThu 22 Oct 2020, 14:35 (6 years ago) parent81ccca0
15 files changed+396−295
Cargo.lock+2 helix-core/src/indent.rs+17−12 helix-core/src/state.rs−81 helix-core/src/syntax.rs+1−1 helix-core/src/transaction.rs+6−30 helix-lsp/Cargo.toml+1 helix-lsp/src/client.rs+11−10 helix-term/src/application.rs+25−23 helix-view/Cargo.toml+1 helix-view/src/commands.rs+136−119 helix-view/src/document.rs+157 helix-view/src/editor.rs+3−4 helix-view/src/keymap.rs+5−4 helix-view/src/lib.rs+2 helix-view/src/view.rs+29−11
Cargo.lock+2
@@ -447,6 +447,7 @@ dependencies = [
447447 "futures-util",
448448 "glob",
449449 "helix-core",
450+ "helix-view",
450451 "jsonrpc-core",
451452 "lsp-types",
452453 "pathdiff",
@@ -491,6 +492,7 @@ dependencies = [
491492 "helix-core",
492493 "once_cell",
493494 "tui",
495+ "url",
494496]
495497
496498[[package]]
helix-core/src/indent.rs+17−12
@@ -111,17 +111,17 @@ fn find_first_non_whitespace_char(state: &State, line_num: usize) -> usize {
111111 start
112112}
113113
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 {
115115 let line = state.doc.line(line_num);
116116 let current = indent_level_for_line(line);
117117
118118 let start = find_first_non_whitespace_char(state, line_num);
119119
120− suggested_indent_for_pos(state, start)
120+ suggested_indent_for_pos(syntax, state, start)
121121}
122122
123−pub fn suggested_indent_for_pos(state: &State, pos: usize) -> usize {
124− if let Some(syntax) = &state.syntax {
123+pub fn suggested_indent_for_pos(syntax: Option<&Syntax>, state: &State, pos: usize) -> usize {
124+ if let Some(syntax) = syntax {
125125 let byte_start = state.doc.char_to_byte(pos);
126126 let node = get_highest_syntax_node_at_bytepos(syntax, byte_start);
127127
@@ -163,13 +163,18 @@ mod test {
163163",
164164 );
165165
166− let mut state = State::new(doc);
167− state.set_language("source.rust", &[]);
168−
169− assert_eq!(suggested_indent_for_line(&state, 0), 0); // mod
170− assert_eq!(suggested_indent_for_line(&state, 1), 1); // fn
171− assert_eq!(suggested_indent_for_line(&state, 2), 2); // 1 + 1
172− assert_eq!(suggested_indent_for_line(&state, 4), 1); // }
173− assert_eq!(suggested_indent_for_line(&state, 5), 0); // }
166+ let state = State::new(doc);
167+ // TODO: set_language
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+
174+ assert_eq!(suggested_indent_for_line(Some(&syntax), &state, 0), 0); // mod
175+ assert_eq!(suggested_indent_for_line(Some(&syntax), &state, 1), 1); // fn
176+ assert_eq!(suggested_indent_for_line(Some(&syntax), &state, 2), 2); // 1 + 1
177+ assert_eq!(suggested_indent_for_line(Some(&syntax), &state, 4), 1); // }
178+ assert_eq!(suggested_indent_for_line(Some(&syntax), &state, 5), 0); // }
174179 }
175180}
helix-core/src/state.rs−81
@@ -3,34 +3,11 @@ use crate::syntax::LOADER;
33use crate::{ChangeSet, Diagnostic, Position, Range, Rope, RopeSlice, Selection, Syntax};
44use anyhow::Error;
55
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−
156/// A state represents the current editor state of a single buffer.
167pub struct State {
178 // TODO: fields should be private but we need to refactor commands.rs first
18− /// Path to file on disk.
19− pub path: Option<PathBuf>,
209 pub doc: Rope,
2110 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>,
3411}
3512
3613#[derive(Copy, Clone, PartialEq, Eq)]
@@ -49,60 +26,12 @@ pub enum Granularity {
4926impl State {
5027 #[must_use]
5128 pub fn new(doc: Rope) -> Self {
52− let changes = ChangeSet::new(&doc);
53− let old_state = Some((doc.clone(), Selection::single(0, 0)));
54−
5529 Self {
56− path: None,
5730 doc,
5831 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,
6632 }
6733 }
6834
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−
10635 // TODO: doc/selection accessors
10736
10837 // TODO: be able to take either Rope or RopeSlice
@@ -116,16 +45,6 @@ impl State {
11645 &self.selection
11746 }
11847
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−
12948 // pub fn doc<R>(&self, range: R) -> RopeSlice
13049 // where
13150 // R: std::ops::RangeBounds<usize>,
helix-core/src/syntax.rs+1−1
@@ -66,7 +66,7 @@ impl LanguageConfiguration {
6666
6767use once_cell::sync::Lazy;
6868
69−pub(crate) static LOADER: Lazy<Loader> = Lazy::new(Loader::init);
69+pub static LOADER: Lazy<Loader> = Lazy::new(Loader::init);
7070
7171pub struct Loader {
7272 // highlight_names ?
helix-core/src/transaction.rs+6−30
@@ -351,22 +351,6 @@ pub struct Transaction {
351351 // scroll_into_view
352352}
353353
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−
370354impl Transaction {
371355 /// Create a new, empty transaction.
372356 pub fn new(state: &mut State) -> Self {
@@ -376,29 +360,21 @@ impl Transaction {
376360 }
377361 }
378362
363+ pub fn changes(&self) -> &ChangeSet {
364+ &self.changes
365+ }
366+
379367 /// Returns true if applied successfully.
380368 pub fn apply(&self, state: &mut State) -> bool {
381369 if !self.changes.is_empty() {
382− // TODO: also avoid mapping the selection if not necessary
383−
384− let old_doc = state.doc().clone();
385−
386370 // apply changes to the document
387371 if !self.changes.apply(&mut state.doc) {
388372 return false;
389373 }
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− }
400374 }
401375
376+ // TODO: also avoid mapping the selection if not necessary
377+
402378 // update the selection: either take the selection specified in the transaction, or map the
403379 // current selection through changes.
404380 state.selection = self
helix-lsp/Cargo.toml+1
@@ -8,6 +8,7 @@ edition = "2018"
88
99[dependencies]
1010helix-core = { path = "../helix-core" }
11+helix-view = { path = "../helix-view" }
1112
1213lsp-types = { version = "0.82", features = ["proposed"] }
1314smol = "1.2"
helix-lsp/src/client.rs+11−10
@@ -6,6 +6,7 @@ use crate::{
66type Result<T> = core::result::Result<T, Error>;
77
88use helix_core::{State, Transaction};
9+use helix_view::Document;
910
1011// use std::collections::HashMap;
1112
@@ -190,13 +191,13 @@ impl Client {
190191 // Text document
191192 // -------------------------------------------------------------------------------------------
192193
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<()> {
194195 self.notify::<lsp::notification::DidOpenTextDocument>(lsp::DidOpenTextDocumentParams {
195196 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(),
197198 language_id: "rust".to_string(), // TODO: hardcoded for now
198− version: state.version,
199− text: String::from(&state.doc),
199+ version: doc.version,
200+ text: String::from(doc.text()),
200201 },
201202 })
202203 .await
@@ -205,13 +206,13 @@ impl Client {
205206 // TODO: trigger any time history.commit_revision happens
206207 pub async fn text_document_did_change(
207208 &mut self,
208− state: &State,
209+ doc: &Document,
209210 transaction: &Transaction,
210211 ) -> Result<()> {
211212 self.notify::<lsp::notification::DidChangeTextDocument>(lsp::DidChangeTextDocumentParams {
212213 text_document: lsp::VersionedTextDocumentIdentifier::new(
213− lsp::Url::from_file_path(state.path().unwrap()).unwrap(),
214− state.version,
214+ lsp::Url::from_file_path(doc.path().unwrap()).unwrap(),
215+ doc.version,
215216 ),
216217 content_changes: vec![lsp::TextDocumentContentChangeEvent {
217218 // range = None -> whole document
@@ -223,12 +224,12 @@ impl Client {
223224 .await
224225 }
225226
226− // TODO: impl into() TextDocumentIdentifier / VersionedTextDocumentIdentifier for State.
227+ // TODO: impl into() TextDocumentIdentifier / VersionedTextDocumentIdentifier for Document.
227228
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<()> {
229230 self.notify::<lsp::notification::DidCloseTextDocument>(lsp::DidCloseTextDocumentParams {
230231 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(),
232233 ),
233234 })
234235 .await
helix-term/src/application.rs+25−23
@@ -1,10 +1,11 @@
11use 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};
33use helix_view::{
44 commands,
5+ document::Mode,
56 keymap::{self, Keymaps},
67 prompt::Prompt,
7− Editor, Theme, View,
8+ Document, Editor, Theme, View,
89};
910
1011use std::{
@@ -95,15 +96,15 @@ impl Renderer {
9596 self.surface.set_style(area, theme.get("ui.background"));
9697
9798 // 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();
99100
100101 let last_line = view.last_line();
101102
102103 let range = {
103104 // calculate viewport byte ranges
104− let start = view.state.doc().line_to_byte(view.first_line);
105− let end = view.state.doc().line_to_byte(last_line)
106− + view.state.doc().line(last_line).len_bytes();
105+ let start = view.doc.text().line_to_byte(view.first_line);
106+ let end = view.doc.text().line_to_byte(last_line)
107+ + view.doc.text().line(last_line).len_bytes();
107108
108109 start..end
109110 };
@@ -111,7 +112,7 @@ impl Renderer {
111112 // TODO: range doesn't actually restrict source, just highlight range
112113 // TODO: cache highlight results
113114 // 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() {
115116 Some(syntax) => {
116117 syntax
117118 .highlight_iter(source_code.as_bytes(), Some(range), None, |_| None)
@@ -127,6 +128,7 @@ impl Renderer {
127128 let mut visual_x = 0;
128129 let mut line = 0u16;
129130 let visible_selections: Vec<Range> = view
131+ .doc
130132 .state
131133 .selection()
132134 .ranges()
@@ -147,10 +149,10 @@ impl Renderer {
147149 HighlightEvent::Source { start, end } => {
148150 // TODO: filter out spans out of viewport for now..
149151
150− let start = view.state.doc().byte_to_char(start);
151− let end = view.state.doc().byte_to_char(end); // <-- index 744, len 743
152+ let start = view.doc.text().byte_to_char(start);
153+ let end = view.doc.text().byte_to_char(end); // <-- index 744, len 743
152154
153− let text = view.state.doc().slice(start..end);
155+ let text = view.doc.text().slice(start..end);
154156
155157 use helix_core::graphemes::{grapheme_width, RopeGraphemes};
156158
@@ -207,7 +209,7 @@ impl Renderer {
207209
208210 // ugh, improve with a traverse method
209211 // 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| {
211213 diagnostic.range.0 <= char_index && diagnostic.range.1 > char_index
212214 }) {
213215 style.clone().add_modifier(Modifier::UNDERLINED)
@@ -233,7 +235,7 @@ impl Renderer {
233235 let warning: Style = theme.get("warning");
234236 let last_line = view.last_line();
235237 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) {
237239 self.surface.set_stringn(0, i as u16, "●", 1, warning);
238240 }
239241
@@ -243,7 +245,7 @@ impl Renderer {
243245 }
244246
245247 pub fn render_statusline(&mut self, view: &View, theme: &Theme) {
246− let mode = match view.state.mode() {
248+ let mode = match view.doc.mode() {
247249 Mode::Insert => "INS",
248250 Mode::Normal => "NOR",
249251 Mode::Goto => "GOTO",
@@ -259,7 +261,7 @@ impl Renderer {
259261 self.surface.set_string(
260262 self.size.0 - 10,
261263 self.size.1 - 2,
262− format!("{}", view.state.diagnostics.len()),
264+ format!("{}", view.doc.diagnostics.len()),
263265 self.text_color,
264266 );
265267 }
@@ -329,14 +331,14 @@ impl Renderer {
329331
330332 pub fn render_cursor(&mut self, view: &View, prompt: Option<&Prompt>, viewport: Rect) {
331333 let mut stdout = stdout();
332− match view.state.mode() {
334+ match view.doc.mode() {
333335 Mode::Insert => write!(stdout, "\x1B[6 q"),
334336 mode => write!(stdout, "\x1B[2 q"),
335337 };
336338 let pos = if let Some(prompt) = prompt {
337339 Position::new(self.size.0 as usize, 2 + prompt.cursor)
338340 } else {
339− if let Some(path) = view.state.path() {
341+ if let Some(path) = view.doc.path() {
340342 self.surface.set_string(
341343 6,
342344 self.size.1 - 1,
@@ -345,10 +347,10 @@ impl Renderer {
345347 );
346348 }
347349
348− let cursor = view.state.selection().cursor();
350+ let cursor = view.doc.state.selection().cursor();
349351
350352 let mut pos = view
351− .screen_coords_at_pos(&view.state.doc().slice(..), cursor)
353+ .screen_coords_at_pos(&view.doc.text().slice(..), cursor)
352354 .expect("Cursor is out of bounds.");
353355 pos.col += viewport.x as usize;
354356 pos.row += viewport.y as usize;
@@ -416,7 +418,7 @@ impl<'a> Application<'a> {
416418 let res = self.lsp.initialize().await;
417419 let res = self
418420 .lsp
419− .text_document_did_open(&self.editor.view().unwrap().state)
421+ .text_document_did_open(&self.editor.view().unwrap().doc)
420422 .await;
421423
422424 self.render();
@@ -469,7 +471,7 @@ impl<'a> Application<'a> {
469471 let keys = vec![event];
470472 // TODO: sequences (`gg`)
471473 // TODO: handle count other than 1
472− match view.state.mode() {
474+ match view.doc.mode() {
473475 Mode::Insert => {
474476 if let Some(command) = self.keymap[&Mode::Insert].get(&keys) {
475477 command(view, 1);
@@ -573,10 +575,10 @@ impl<'a> Application<'a> {
573575 .editor
574576 .views
575577 .iter_mut()
576− .find(|view| view.state.path == path);
578+ .find(|view| view.doc.path == path);
577579
578580 if let Some(view) = view {
579− let doc = view.state.doc().slice(..);
581+ let doc = view.doc.text().slice(..);
580582 let diagnostics = params
581583 .diagnostics
582584 .into_iter()
@@ -596,7 +598,7 @@ impl<'a> Application<'a> {
596598 })
597599 .collect();
598600
599− view.state.diagnostics = diagnostics;
601+ view.doc.diagnostics = diagnostics;
600602
601603 self.render();
602604 }
helix-view/Cargo.toml+1
@@ -19,3 +19,4 @@ helix-core = { path = "../helix-core" }
1919tui = { git = "https://github.com/fdehau/tui-rs", default-features = false, features = ["crossterm"], optional = true}
2020crossterm = { version = "0.18", features = ["event-stream"], optional = true}
2121once_cell = "1.4"
22+url = "2"
helix-view/src/commands.rs+136−119
@@ -3,12 +3,13 @@ use helix_core::{
33 indent::TAB_WIDTH,
44 regex::Regex,
55 register, selection,
6− state::{Direction, Granularity, Mode, State},
6+ state::{Direction, Granularity, State},
77 ChangeSet, Range, Selection, Tendril, Transaction,
88};
99use once_cell::sync::Lazy;
1010
1111use crate::{
12+ document::Mode,
1213 prompt::Prompt,
1314 view::{View, PADDING},
1415};
@@ -19,36 +20,40 @@ pub type Command = fn(view: &mut View, count: usize);
1920
2021pub fn move_char_left(view: &mut View, count: usize) {
2122 // TODO: use a transaction
22− let selection = view
23− .state
24− .move_selection(Direction::Backward, Granularity::Character, count);
25− view.state.selection = selection;
23+ let selection =
24+ view.doc
25+ .state
26+ .move_selection(Direction::Backward, Granularity::Character, count);
27+ view.doc.state.selection = selection;
2628}
2729
2830pub fn move_char_right(view: &mut View, count: usize) {
2931 // TODO: use a transaction
30− view.state.selection =
31− view.state
32+ view.doc.state.selection =
33+ view.doc
34+ .state
3235 .move_selection(Direction::Forward, Granularity::Character, count);
3336}
3437
3538pub fn move_line_up(view: &mut View, count: usize) {
3639 // TODO: use a transaction
37− view.state.selection = view
38− .state
39− .move_selection(Direction::Backward, Granularity::Line, count);
40+ view.doc.state.selection =
41+ view.doc
42+ .state
43+ .move_selection(Direction::Backward, Granularity::Line, count);
4044}
4145
4246pub fn move_line_down(view: &mut View, count: usize) {
4347 // TODO: use a transaction
44− view.state.selection = view
45− .state
46− .move_selection(Direction::Forward, Granularity::Line, count);
48+ view.doc.state.selection =
49+ view.doc
50+ .state
51+ .move_selection(Direction::Forward, Granularity::Line, count);
4752}
4853
4954pub fn move_line_end(view: &mut View, _count: usize) {
5055 // TODO: use a transaction
51− let lines = selection_lines(&view.state);
56+ let lines = selection_lines(&view.doc.state);
5257
5358 let positions = lines
5459 .into_iter()
@@ -57,89 +62,89 @@ pub fn move_line_end(view: &mut View, _count: usize) {
5762
5863 // Line end is pos at the start of next line - 1
5964 // 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)
6166 })
6267 .map(|pos| Range::new(pos, pos));
6368
6469 let selection = Selection::new(positions.collect(), 0);
6570
66− let transaction = Transaction::new(&mut view.state).with_selection(selection);
71+ let transaction = Transaction::new(&mut view.doc.state).with_selection(selection);
6772
68− transaction.apply(&mut view.state);
73+ view.doc.apply(&transaction);
6974}
7075
7176pub fn move_line_start(view: &mut View, _count: usize) {
72− let lines = selection_lines(&view.state);
77+ let lines = selection_lines(&view.doc.state);
7378
7479 let positions = lines
7580 .into_iter()
7681 .map(|index| {
7782 // 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)
7984 })
8085 .map(|pos| Range::new(pos, pos));
8186
8287 let selection = Selection::new(positions.collect(), 0);
8388
84− let transaction = Transaction::new(&mut view.state).with_selection(selection);
89+ let transaction = Transaction::new(&mut view.doc.state).with_selection(selection);
8590
86− transaction.apply(&mut view.state);
91+ view.doc.apply(&transaction);
8792}
8893
8994pub fn move_next_word_start(view: &mut View, count: usize) {
90− let pos = view.state.move_pos(
91− view.state.selection.cursor(),
95+ let pos = view.doc.state.move_pos(
96+ view.doc.state.selection.cursor(),
9297 Direction::Forward,
9398 Granularity::Word,
9499 count,
95100 );
96101
97102 // TODO: use a transaction
98− view.state.selection = Selection::single(pos, pos);
103+ view.doc.state.selection = Selection::single(pos, pos);
99104}
100105
101106pub fn move_prev_word_start(view: &mut View, count: usize) {
102− let pos = view.state.move_pos(
103− view.state.selection.cursor(),
107+ let pos = view.doc.state.move_pos(
108+ view.doc.state.selection.cursor(),
104109 Direction::Backward,
105110 Granularity::Word,
106111 count,
107112 );
108113
109114 // TODO: use a transaction
110− view.state.selection = Selection::single(pos, pos);
115+ view.doc.state.selection = Selection::single(pos, pos);
111116}
112117
113118pub fn move_next_word_end(view: &mut View, count: usize) {
114119 let pos = State::move_next_word_end(
115− &view.state.doc().slice(..),
116− view.state.selection.cursor(),
120+ &view.doc.text().slice(..),
121+ view.doc.state.selection.cursor(),
117122 count,
118123 );
119124
120125 // TODO: use a transaction
121− view.state.selection = Selection::single(pos, pos);
126+ view.doc.state.selection = Selection::single(pos, pos);
122127}
123128
124129pub fn move_file_start(view: &mut View, _count: usize) {
125130 // TODO: use a transaction
126− view.state.selection = Selection::single(0, 0);
131+ view.doc.state.selection = Selection::single(0, 0);
127132
128− view.state.mode = Mode::Normal;
133+ view.doc.mode = Mode::Normal;
129134}
130135
131136pub fn move_file_end(view: &mut View, _count: usize) {
132137 // TODO: use a transaction
133− let text = &view.state.doc;
138+ let text = &view.doc.text();
134139 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);
136141
137− view.state.mode = Mode::Normal;
142+ view.doc.mode = Mode::Normal;
138143}
139144
140145pub fn check_cursor_in_view(view: &mut View) -> bool {
141− let cursor = view.state.selection().cursor();
142− let line = view.state.doc().char_to_line(cursor);
146+ let cursor = view.doc.state.selection().cursor();
147+ let line = view.doc.text().char_to_line(cursor);
143148 let document_end = view.first_line + view.size.1.saturating_sub(1) as usize;
144149
145150 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) {
156161 view.first_line = view.first_line.saturating_sub(view.size.1 as usize);
157162
158163 if !check_cursor_in_view(view) {
159− let text = view.state.doc();
164+ let text = view.doc.text();
160165 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);
162167 }
163168}
164169
165170pub fn page_down(view: &mut View, _count: usize) {
166171 view.first_line += view.size.1 as usize + PADDING;
167172
168− if view.first_line < view.state.doc().len_lines() {
169− let text = view.state.doc();
173+ if view.first_line < view.doc.text().len_lines() {
174+ let text = view.doc.text();
170175 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);
172177 }
173178}
174179
@@ -180,79 +185,84 @@ pub fn half_page_up(view: &mut View, _count: usize) {
180185 view.first_line = view.first_line.saturating_sub(view.size.1 as usize / 2);
181186
182187 if !check_cursor_in_view(view) {
183− let text = &view.state.doc;
188+ let text = &view.doc.text();
184189 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);
186191 }
187192}
188193
189194pub 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();
191196 if view.first_line < lines.saturating_sub(view.size.1 as usize) {
192197 view.first_line += view.size.1 as usize / 2;
193198 }
194199 if !check_cursor_in_view(view) {
195− let text = view.state.doc();
200+ let text = view.doc.text();
196201 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);
198203 }
199204}
200205// avoid select by default by having a visual mode switch that makes movements into selects
201206
202207pub fn extend_char_left(view: &mut View, count: usize) {
203208 // TODO: use a transaction
204− let selection = view
205− .state
206− .extend_selection(Direction::Backward, Granularity::Character, count);
207− view.state.selection = selection;
209+ let selection =
210+ view.doc
211+ .state
212+ .extend_selection(Direction::Backward, Granularity::Character, count);
213+ view.doc.state.selection = selection;
208214}
209215
210216pub fn extend_char_right(view: &mut View, count: usize) {
211217 // TODO: use a transaction
212− view.state.selection =
213− view.state
218+ view.doc.state.selection =
219+ view.doc
220+ .state
214221 .extend_selection(Direction::Forward, Granularity::Character, count);
215222}
216223
217224pub fn extend_line_up(view: &mut View, count: usize) {
218225 // TODO: use a transaction
219− view.state.selection =
220− view.state
226+ view.doc.state.selection =
227+ view.doc
228+ .state
221229 .extend_selection(Direction::Backward, Granularity::Line, count);
222230}
223231
224232pub fn extend_line_down(view: &mut View, count: usize) {
225233 // TODO: use a transaction
226− view.state.selection =
227− view.state
234+ view.doc.state.selection =
235+ view.doc
236+ .state
228237 .extend_selection(Direction::Forward, Granularity::Line, count);
229238}
230239
231240pub fn split_selection_on_newline(view: &mut View, _count: usize) {
232− let text = &view.state.doc.slice(..);
241+ let text = &view.doc.text().slice(..);
233242 // only compile the regex once
234243 #[allow(clippy::trivial_regex)]
235244 static REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(r"\n").unwrap());
236245 // 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)
238247}
239248
240249pub fn select_line(view: &mut View, _count: usize) {
241250 // TODO: count
242− let pos = view.state.selection().primary();
243− let text = view.state.doc();
251+ let pos = view.doc.state.selection().primary();
252+ let text = view.doc.text();
244253 let line = text.char_to_line(pos.head);
245254 let start = text.line_to_char(line);
246255 let end = text.line_to_char(line + 1).saturating_sub(1);
247256
248257 // TODO: use a transaction
249− view.state.selection = Selection::single(start, end);
258+ view.doc.state.selection = Selection::single(start, end);
250259}
251260
252261pub 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));
255− transaction.apply(&mut view.state);
262+ let transaction = Transaction::change_by_selection(&view.doc.state, |range| {
263+ (range.from(), range.to() + 1, None)
264+ });
265+ view.doc.apply(&transaction);
256266
257267 append_changes_to_history(view);
258268}
@@ -263,21 +273,23 @@ pub fn change_selection(view: &mut View, count: usize) {
263273}
264274
265275pub fn collapse_selection(view: &mut View, _count: usize) {
266− view.state.selection = view
276+ view.doc.state.selection = view
277+ .doc
267278 .state
268279 .selection
269280 .transform(|range| Range::new(range.head, range.head))
270281}
271282
272283pub fn flip_selections(view: &mut View, _count: usize) {
273− view.state.selection = view
284+ view.doc.state.selection = view
285+ .doc
274286 .state
275287 .selection
276288 .transform(|range| Range::new(range.head, range.anchor))
277289}
278290
279291fn enter_insert_mode(view: &mut View) {
280− view.state.mode = Mode::Insert;
292+ view.doc.mode = Mode::Insert;
281293
282294 append_changes_to_history(view);
283295}
@@ -285,7 +297,8 @@ fn enter_insert_mode(view: &mut View) {
285297pub fn insert_mode(view: &mut View, _count: usize) {
286298 enter_insert_mode(view);
287299
288− view.state.selection = view
300+ view.doc.state.selection = view
301+ .doc
289302 .state
290303 .selection
291304 .transform(|range| Range::new(range.to(), range.from()))
@@ -294,11 +307,11 @@ pub fn insert_mode(view: &mut View, _count: usize) {
294307// inserts at the end of each selection
295308pub fn append_mode(view: &mut View, _count: usize) {
296309 enter_insert_mode(view);
297− view.state.restore_cursor = true;
310+ view.doc.restore_cursor = true;
298311
299312 // TODO: as transaction
300− let text = &view.state.doc.slice(..);
301− view.state.selection = view.state.selection.transform(|range| {
313+ let text = &view.doc.text().slice(..);
314+ view.doc.state.selection = view.doc.state.selection.transform(|range| {
302315 // TODO: to() + next char
303316 Range::new(
304317 range.from(),
@@ -346,13 +359,13 @@ pub fn append_to_line(view: &mut View, count: usize) {
346359pub fn open_below(view: &mut View, _count: usize) {
347360 enter_insert_mode(view);
348361
349− let lines = selection_lines(&view.state);
362+ let lines = selection_lines(&view.doc.state);
350363
351364 let positions: Vec<_> = lines
352365 .into_iter()
353366 .map(|index| {
354367 // 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)
356369 })
357370 .collect();
358371
@@ -373,63 +386,63 @@ pub fn open_below(view: &mut View, _count: usize) {
373386 0,
374387 );
375388
376− let transaction = Transaction::change(&view.state, changes).with_selection(selection);
389+ let transaction = Transaction::change(&view.doc.state, changes).with_selection(selection);
377390
378− transaction.apply(&mut view.state);
391+ view.doc.apply(&transaction);
379392}
380393
381394// O inserts a new line before each line with a selection
382395
383396fn append_changes_to_history(view: &mut View) {
384− if view.state.changes.is_empty() {
397+ if view.doc.changes.is_empty() {
385398 return;
386399 }
387400
388− let new_changeset = ChangeSet::new(view.state.doc());
389− let changes = std::mem::replace(&mut view.state.changes, new_changeset);
401+ let new_changeset = ChangeSet::new(view.doc.text());
402+ let changes = std::mem::replace(&mut view.doc.changes, new_changeset);
390403 // Instead of doing this messy merge we could always commit, and based on transaction
391404 // 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());
393406
394407 // increment document version
395408 // TODO: needs to happen on undo/redo too
396− view.state.version += 1;
409+ view.doc.version += 1;
397410
398411 // TODO: trigger lsp/documentDidChange with changes
399412
400413 // 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();
402415 let mut old_state = State::new(doc);
403416 old_state.selection = selection;
404417
405418 // TODO: take transaction by value?
406− view.history.commit_revision(&transaction, &old_state);
419+ view.doc.history.commit_revision(&transaction, &old_state);
407420
408421 // 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()));
410423}
411424
412425pub fn normal_mode(view: &mut View, _count: usize) {
413− view.state.mode = Mode::Normal;
426+ view.doc.mode = Mode::Normal;
414427
415428 append_changes_to_history(view);
416429
417430 // if leaving append mode, move cursor back by 1
418− if view.state.restore_cursor {
419− let text = &view.state.doc.slice(..);
420− view.state.selection = view.state.selection.transform(|range| {
431+ if view.doc.restore_cursor {
432+ let text = &view.doc.text().slice(..);
433+ view.doc.state.selection = view.doc.state.selection.transform(|range| {
421434 Range::new(
422435 range.from(),
423436 graphemes::prev_grapheme_boundary(text, range.to()),
424437 )
425438 });
426439
427− view.state.restore_cursor = false;
440+ view.doc.restore_cursor = false;
428441 }
429442}
430443
431444pub fn goto_mode(view: &mut View, _count: usize) {
432− view.state.mode = Mode::Goto;
445+ view.doc.mode = Mode::Goto;
433446}
434447
435448// NOTE: Transactions in this module get appended to history when we switch back to normal mode.
@@ -438,9 +451,9 @@ pub mod insert {
438451 // TODO: insert means add text just before cursor, on exit we should be on the last letter.
439452 pub fn insert_char(view: &mut View, c: char) {
440453 let c = Tendril::from_char(c);
441− let transaction = Transaction::insert(&view.state, c);
454+ let transaction = Transaction::insert(&view.doc.state, c);
442455
443− transaction.apply(&mut view.state);
456+ view.doc.apply(&transaction);
444457 }
445458
446459 pub fn insert_tab(view: &mut View, _count: usize) {
@@ -448,41 +461,44 @@ pub mod insert {
448461 }
449462
450463 pub fn insert_newline(view: &mut View, _count: usize) {
451− let transaction = Transaction::change_by_selection(&view.state, |range| {
452− let indent_level =
453− helix_core::indent::suggested_indent_for_pos(&view.state, range.head);
464+ let transaction = Transaction::change_by_selection(&view.doc.state, |range| {
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+ );
454470 let indent = " ".repeat(TAB_WIDTH).repeat(indent_level);
455471 let mut text = String::with_capacity(1 + indent.len());
456472 text.push('\n');
457473 text.push_str(&indent);
458474 (range.head, range.head, Some(text.into()))
459475 });
460− transaction.apply(&mut view.state);
476+ view.doc.apply(&transaction);
461477 }
462478
463479 // TODO: handle indent-aware delete
464480 pub fn delete_char_backward(view: &mut View, count: usize) {
465− let text = &view.state.doc.slice(..);
466− let transaction = Transaction::change_by_selection(&view.state, |range| {
481+ let text = &view.doc.text().slice(..);
482+ let transaction = Transaction::change_by_selection(&view.doc.state, |range| {
467483 (
468484 graphemes::nth_prev_grapheme_boundary(text, range.head, count),
469485 range.head,
470486 None,
471487 )
472488 });
473− transaction.apply(&mut view.state);
489+ view.doc.apply(&transaction);
474490 }
475491
476492 pub fn delete_char_forward(view: &mut View, count: usize) {
477− let text = &view.state.doc.slice(..);
478− let transaction = Transaction::change_by_selection(&view.state, |range| {
493+ let text = &view.doc.text().slice(..);
494+ let transaction = Transaction::change_by_selection(&view.doc.state, |range| {
479495 (
480496 range.head,
481497 graphemes::nth_next_grapheme_boundary(text, range.head, count),
482498 None,
483499 )
484500 });
485− transaction.apply(&mut view.state);
501+ view.doc.apply(&transaction);
486502 }
487503}
488504
@@ -493,13 +509,13 @@ pub fn insert_char_prompt(prompt: &mut Prompt, c: char) {
493509// Undo / Redo
494510
495511pub fn undo(view: &mut View, _count: usize) {
496− view.history.undo(&mut view.state);
512+ view.doc.history.undo(&mut view.doc.state);
497513
498514 // TODO: each command could simply return a Option<transaction>, then the higher level handles storing it?
499515}
500516
501517pub fn redo(view: &mut View, _count: usize) {
502− view.history.redo(&mut view.state);
518+ view.doc.history.redo(&mut view.doc.state);
503519}
504520
505521// Yank / Paste
@@ -507,9 +523,10 @@ pub fn redo(view: &mut View, _count: usize) {
507523pub fn yank(view: &mut View, _count: usize) {
508524 // TODO: should selections be made end inclusive?
509525 let values = view
526+ .doc
510527 .state
511528 .selection()
512− .fragments(&view.state.doc().slice(..))
529+ .fragments(&view.doc.text().slice(..))
513530 .map(|cow| cow.into_owned())
514531 .collect();
515532
@@ -550,18 +567,18 @@ pub fn paste(view: &mut View, _count: usize) {
550567 let transaction = if linewise {
551568 // paste on the next line
552569 // TODO: can simply take a range + modifier and compute the right pos without ifs
553− let text = view.state.doc();
554− Transaction::change_by_selection(&view.state, |range| {
570+ let text = view.doc.text();
571+ Transaction::change_by_selection(&view.doc.state, |range| {
555572 let line_end = text.line_to_char(text.char_to_line(range.head) + 1);
556573 (line_end, line_end, Some(values.next().unwrap()))
557574 })
558575 } else {
559− Transaction::change_by_selection(&view.state, |range| {
576+ Transaction::change_by_selection(&view.doc.state, |range| {
560577 (range.head + 1, range.head + 1, Some(values.next().unwrap()))
561578 })
562579 };
563580
564− transaction.apply(&mut view.state);
581+ view.doc.apply(&transaction);
565582 append_changes_to_history(view);
566583 }
567584}
@@ -570,9 +587,9 @@ fn get_lines(view: &View) -> Vec<usize> {
570587 let mut lines = Vec::new();
571588
572589 // Get all line numbers
573− for range in view.state.selection.ranges() {
574− let start = view.state.doc.char_to_line(range.from());
575− let end = view.state.doc.char_to_line(range.to());
590+ for range in view.doc.state.selection.ranges() {
591+ let start = view.doc.text().char_to_line(range.from());
592+ let end = view.doc.text().char_to_line(range.to());
576593
577594 for line in start..=end {
578595 lines.push(line)
@@ -590,13 +607,13 @@ pub fn indent(view: &mut View, _count: usize) {
590607 let indent = Tendril::from(" ".repeat(TAB_WIDTH));
591608
592609 let transaction = Transaction::change(
593− &view.state,
610+ &view.doc.state,
594611 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);
596613 (pos, pos, Some(indent.clone()))
597614 }),
598615 );
599− transaction.apply(&mut view.state);
616+ view.doc.apply(&transaction);
600617 append_changes_to_history(view);
601618}
602619
@@ -605,7 +622,7 @@ pub fn unindent(view: &mut View, _count: usize) {
605622 let mut changes = Vec::with_capacity(lines.len());
606623
607624 for line_idx in lines {
608− let line = view.state.doc.line(line_idx);
625+ let line = view.doc.text().line(line_idx);
609626 let mut width = 0;
610627
611628 for ch in line.chars() {
@@ -621,14 +638,14 @@ pub fn unindent(view: &mut View, _count: usize) {
621638 }
622639
623640 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);
625642 changes.push((start, start + width, None))
626643 }
627644 }
628645
629− let transaction = Transaction::change(&view.state, changes.into_iter());
646+ let transaction = Transaction::change(&view.doc.state, changes.into_iter());
630647
631− transaction.apply(&mut view.state);
648+ view.doc.apply(&transaction);
632649 append_changes_to_history(view);
633650}
634651
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 @@
11use crate::theme::Theme;
2−use crate::View;
3−use helix_core::State;
2+use crate::{Document, View};
43
54use std::path::PathBuf;
65
@@ -27,8 +26,8 @@ impl Editor {
2726
2827 pub fn open(&mut self, path: PathBuf, size: (u16, u16)) -> Result<(), Error> {
2928 let pos = self.views.len();
30− let state = State::load(path, self.theme.scopes())?;
31− self.views.push(View::new(state, size)?);
29+ let doc = Document::load(path, self.theme.scopes())?;
30+ self.views.push(View::new(doc, size)?);
3231 self.focus = pos;
3332 Ok(())
3433 }
helix-view/src/keymap.rs+5−4
@@ -1,4 +1,5 @@
11use crate::commands::{self, Command};
2+use crate::document::Mode;
23use helix_core::{hashmap, state};
34use std::collections::HashMap;
45
@@ -88,7 +89,7 @@ pub use crossterm::event::{KeyCode, KeyEvent as Key, KeyModifiers as Modifiers};
8889
8990// TODO: could be trie based
9091pub type Keymap = HashMap<Vec<Key>, Command>;
91−pub type Keymaps = HashMap<state::Mode, Keymap>;
92+pub type Keymaps = HashMap<Mode, Keymap>;
9293
9394macro_rules! key {
9495 ($ch:expr) => {
@@ -128,7 +129,7 @@ macro_rules! ctrl {
128129
129130pub fn default() -> Keymaps {
130131 hashmap!(
131− state::Mode::Normal =>
132+ Mode::Normal =>
132133 // as long as you cast the first item, rust is able to infer the other cases
133134 hashmap!(
134135 vec![key!('h')] => commands::move_char_left as Command,
@@ -179,7 +180,7 @@ pub fn default() -> Keymaps {
179180 vec![ctrl!('u')] => commands::half_page_up,
180181 vec![ctrl!('d')] => commands::half_page_down,
181182 ),
182− state::Mode::Insert => hashmap!(
183+ Mode::Insert => hashmap!(
183184 vec![Key {
184185 code: KeyCode::Esc,
185186 modifiers: Modifiers::NONE
@@ -201,7 +202,7 @@ pub fn default() -> Keymaps {
201202 modifiers: Modifiers::NONE
202203 }] => commands::insert::insert_tab,
203204 ),
204− state::Mode::Goto => hashmap!(
205+ Mode::Goto => hashmap!(
205206 vec![Key {
206207 code: KeyCode::Esc,
207208 modifiers: Modifiers::NONE
helix-view/src/lib.rs+2
@@ -1,10 +1,12 @@
11pub mod commands;
2+pub mod document;
23pub mod editor;
34pub mod keymap;
45pub mod prompt;
56pub mod theme;
67pub mod view;
78
9+pub use document::Document;
810pub use editor::Editor;
911pub use theme::Theme;
1012pub use view::View;
helix-view/src/view.rs+29−11
@@ -2,10 +2,11 @@ use anyhow::Error;
22
33use std::borrow::Cow;
44
5+use crate::Document;
56use helix_core::{
67 graphemes::{grapheme_width, RopeGraphemes},
78 indent::TAB_WIDTH,
8− History, Position, RopeSlice, State,
9+ Position, RopeSlice,
910};
1011use tui::layout::Rect;
1112
@@ -14,29 +15,25 @@ pub const PADDING: usize = 5;
1415// TODO: view should be View { doc: Document(state, history,..) }
1516// since we can have multiple views into the same file
1617pub struct View {
17− pub state: State,
18+ pub doc: Document,
1819 pub first_line: usize,
1920 pub size: (u16, u16),
20−
21− // TODO: Doc fields
22− pub history: History,
2321}
2422
2523impl 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> {
2725 let view = Self {
28− state,
26+ doc,
2927 first_line: 0,
3028 size,
31− history: History::default(),
3229 };
3330
3431 Ok(view)
3532 }
3633
3734 pub fn ensure_cursor_in_view(&mut self) {
38− let cursor = self.state.selection().cursor();
39− let line = self.state.doc().char_to_line(cursor);
35+ let cursor = self.doc.state.selection().cursor();
36+ let line = self.doc.text().char_to_line(cursor);
4037 let document_end = self.first_line + (self.size.1 as usize).saturating_sub(2);
4138
4239 // TODO: side scroll
@@ -56,7 +53,7 @@ impl View {
5653 let viewport = Rect::new(6, 0, self.size.0, self.size.1 - 2); // - 2 for statusline and prompt
5754 std::cmp::min(
5855 self.first_line + (viewport.height as usize),
59− self.state.doc().len_lines() - 1,
56+ self.doc.text().len_lines() - 1,
6057 )
6158 }
6259
@@ -88,4 +85,25 @@ impl View {
8885
8986 Some(Position::new(row, col))
9087 }
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+ }
91109}