Store Document on the Editor type, make View reference it.

imgbot
Blaž Hrastnik 4 years ago
parent 5e6716c89c
commit bf95ee27aa

@ -125,15 +125,16 @@ impl Application {
Notification::PublishDiagnostics(params) => { Notification::PublishDiagnostics(params) => {
let path = Some(params.uri.to_file_path().unwrap()); let path = Some(params.uri.to_file_path().unwrap());
let view = self let doc = self
.editor .editor
.tree .documents
.views() .iter_mut()
.map(|(view, _key)| view) .find(|(_, doc)| doc.borrow().path() == path.as_ref());
.find(|view| view.doc.path() == path.as_ref());
if let Some((_, doc)) = doc {
let mut doc = doc.borrow_mut();
let text = doc.text();
if let Some(view) = view {
let doc = view.doc.text();
let diagnostics = params let diagnostics = params
.diagnostics .diagnostics
.into_iter() .into_iter()
@ -144,8 +145,8 @@ impl Application {
}; };
use helix_lsp::{lsp, util::lsp_pos_to_pos}; use helix_lsp::{lsp, util::lsp_pos_to_pos};
use lsp::DiagnosticSeverity; use lsp::DiagnosticSeverity;
let start = lsp_pos_to_pos(doc, diagnostic.range.start); let start = lsp_pos_to_pos(text, diagnostic.range.start);
let end = lsp_pos_to_pos(doc, diagnostic.range.end); let end = lsp_pos_to_pos(text, diagnostic.range.end);
Diagnostic { Diagnostic {
range: Range { start, end }, range: Range { start, end },
@ -165,8 +166,8 @@ impl Application {
}) })
.collect(); .collect();
view.doc.diagnostics = diagnostics; doc.diagnostics = diagnostics;
drop(doc);
// TODO: we want to process all the events in queue, then render. publishDiagnostic tends to send a whole bunch of events // TODO: we want to process all the events in queue, then render. publishDiagnostic tends to send a whole bunch of events
self.render(); self.render();
} }

@ -10,7 +10,7 @@ use helix_core::{
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use crate::{ use crate::{
compositor::Compositor, compositor::{Callback, Compositor},
ui::{self, Popup, Prompt, PromptEvent}, ui::{self, Popup, Prompt, PromptEvent},
}; };
@ -41,8 +41,8 @@ impl<'a> Context<'a> {
} }
#[inline] #[inline]
pub fn doc(&mut self) -> &mut Document { pub fn doc(&mut self) -> std::cell::RefMut<Document> {
&mut self.editor.view_mut().doc self.editor.view().doc.borrow_mut()
} }
/// Push a new component onto the compositor. /// Push a new component onto the compositor.
@ -72,7 +72,7 @@ pub type Command = fn(cx: &mut Context);
pub fn move_char_left(cx: &mut Context) { pub fn move_char_left(cx: &mut Context) {
let count = cx.count; let count = cx.count;
let doc = cx.doc(); let mut doc = cx.doc();
let text = doc.text().slice(..); let text = doc.text().slice(..);
let selection = doc.selection().transform(|range| { let selection = doc.selection().transform(|range| {
movement::move_horizontally( movement::move_horizontally(
@ -88,7 +88,7 @@ pub fn move_char_left(cx: &mut Context) {
pub fn move_char_right(cx: &mut Context) { pub fn move_char_right(cx: &mut Context) {
let count = cx.count; let count = cx.count;
let doc = cx.doc(); let mut doc = cx.doc();
let text = doc.text().slice(..); let text = doc.text().slice(..);
let selection = doc.selection().transform(|range| { let selection = doc.selection().transform(|range| {
movement::move_horizontally( movement::move_horizontally(
@ -104,7 +104,7 @@ pub fn move_char_right(cx: &mut Context) {
pub fn move_line_up(cx: &mut Context) { pub fn move_line_up(cx: &mut Context) {
let count = cx.count; let count = cx.count;
let doc = cx.doc(); let mut doc = cx.doc();
let text = doc.text().slice(..); let text = doc.text().slice(..);
let selection = doc.selection().transform(|range| { let selection = doc.selection().transform(|range| {
movement::move_vertically( movement::move_vertically(
@ -120,7 +120,7 @@ pub fn move_line_up(cx: &mut Context) {
pub fn move_line_down(cx: &mut Context) { pub fn move_line_down(cx: &mut Context) {
let count = cx.count; let count = cx.count;
let doc = cx.doc(); let mut doc = cx.doc();
let text = doc.text().slice(..); let text = doc.text().slice(..);
let selection = doc.selection().transform(|range| { let selection = doc.selection().transform(|range| {
movement::move_vertically( movement::move_vertically(
@ -135,7 +135,7 @@ pub fn move_line_down(cx: &mut Context) {
} }
pub fn move_line_end(cx: &mut Context) { pub fn move_line_end(cx: &mut Context) {
let doc = cx.doc(); let mut doc = cx.doc();
let lines = selection_lines(doc.text(), doc.selection()); let lines = selection_lines(doc.text(), doc.selection());
let positions = lines let positions = lines
@ -155,7 +155,7 @@ pub fn move_line_end(cx: &mut Context) {
} }
pub fn move_line_start(cx: &mut Context) { pub fn move_line_start(cx: &mut Context) {
let doc = cx.doc(); let mut doc = cx.doc();
let lines = selection_lines(doc.text(), doc.selection()); let lines = selection_lines(doc.text(), doc.selection());
let positions = lines let positions = lines
@ -177,7 +177,7 @@ pub fn move_line_start(cx: &mut Context) {
pub fn move_next_word_start(cx: &mut Context) { pub fn move_next_word_start(cx: &mut Context) {
let count = cx.count; let count = cx.count;
let doc = cx.doc(); let mut doc = cx.doc();
let text = doc.text().slice(..); let text = doc.text().slice(..);
let selection = doc.selection().transform(|range| { let selection = doc.selection().transform(|range| {
@ -190,7 +190,7 @@ pub fn move_next_word_start(cx: &mut Context) {
pub fn move_prev_word_start(cx: &mut Context) { pub fn move_prev_word_start(cx: &mut Context) {
let count = cx.count; let count = cx.count;
let doc = cx.doc(); let mut doc = cx.doc();
let text = doc.text().slice(..); let text = doc.text().slice(..);
let selection = doc.selection().transform(|range| { let selection = doc.selection().transform(|range| {
@ -203,7 +203,7 @@ pub fn move_prev_word_start(cx: &mut Context) {
pub fn move_next_word_end(cx: &mut Context) { pub fn move_next_word_end(cx: &mut Context) {
let count = cx.count; let count = cx.count;
let doc = cx.doc(); let mut doc = cx.doc();
let text = doc.text().slice(..); let text = doc.text().slice(..);
let selection = doc.selection().transform(|range| { let selection = doc.selection().transform(|range| {
@ -215,14 +215,14 @@ pub fn move_next_word_end(cx: &mut Context) {
} }
pub fn move_file_start(cx: &mut Context) { pub fn move_file_start(cx: &mut Context) {
let doc = cx.doc(); let mut doc = cx.doc();
doc.set_selection(Selection::point(0)); doc.set_selection(Selection::point(0));
doc.mode = Mode::Normal; doc.mode = Mode::Normal;
} }
pub fn move_file_end(cx: &mut Context) { pub fn move_file_end(cx: &mut Context) {
let doc = cx.doc(); let mut doc = cx.doc();
let text = doc.text(); let text = doc.text();
let last_line = text.line_to_char(text.len_lines().saturating_sub(2)); let last_line = text.line_to_char(text.len_lines().saturating_sub(2));
doc.set_selection(Selection::point(last_line)); doc.set_selection(Selection::point(last_line));
@ -232,7 +232,7 @@ pub fn move_file_end(cx: &mut Context) {
pub fn extend_next_word_start(cx: &mut Context) { pub fn extend_next_word_start(cx: &mut Context) {
let count = cx.count; let count = cx.count;
let doc = cx.doc(); let mut doc = cx.doc();
let text = doc.text().slice(..); let text = doc.text().slice(..);
let selection = doc.selection().transform(|mut range| { let selection = doc.selection().transform(|mut range| {
@ -245,7 +245,7 @@ pub fn extend_next_word_start(cx: &mut Context) {
pub fn extend_prev_word_start(cx: &mut Context) { pub fn extend_prev_word_start(cx: &mut Context) {
let count = cx.count; let count = cx.count;
let doc = cx.doc(); let mut doc = cx.doc();
let text = doc.text().slice(..); let text = doc.text().slice(..);
let selection = doc.selection().transform(|mut range| { let selection = doc.selection().transform(|mut range| {
@ -257,7 +257,7 @@ pub fn extend_prev_word_start(cx: &mut Context) {
pub fn extend_next_word_end(cx: &mut Context) { pub fn extend_next_word_end(cx: &mut Context) {
let count = cx.count; let count = cx.count;
let doc = cx.doc(); let mut doc = cx.doc();
let text = doc.text().slice(..); let text = doc.text().slice(..);
let selection = doc.selection().transform(|mut range| { let selection = doc.selection().transform(|mut range| {
@ -286,7 +286,7 @@ where
.. ..
} = event } = event
{ {
let doc = cx.doc(); let mut doc = cx.doc();
let text = doc.text().slice(..); let text = doc.text().slice(..);
let selection = doc.selection().transform(|mut range| { let selection = doc.selection().transform(|mut range| {
@ -382,11 +382,13 @@ pub fn extend_prev_char(cx: &mut Context) {
fn scroll(view: &mut View, offset: usize, direction: Direction) { fn scroll(view: &mut View, offset: usize, direction: Direction) {
use Direction::*; use Direction::*;
let text = view.doc.text().slice(..); // we use short lived borrows since view's methods read from doc too
let doc = view.doc.borrow();
let text = doc.text().slice(..);
let cursor = coords_at_pos(doc.text().slice(..), doc.selection().cursor());
let doc_last_line = doc.text().len_lines() - 1;
let last_line = view.last_line(); let last_line = view.last_line();
let cursor = coords_at_pos(text, view.doc.selection().cursor());
let doc_last_line = text.len_lines() - 1;
if direction == Backward && view.first_line == 0 if direction == Backward && view.first_line == 0
|| direction == Forward && last_line == doc_last_line || direction == Forward && last_line == doc_last_line
@ -412,7 +414,8 @@ fn scroll(view: &mut View, offset: usize, direction: Direction) {
); );
let pos = pos_at_coords(text, Position::new(line, cursor.col)); // this func will properly truncate to line end let pos = pos_at_coords(text, Position::new(line, cursor.col)); // this func will properly truncate to line end
view.doc.set_selection(Selection::point(pos)); drop(doc); // upgrade to mutable borrow
view.doc.borrow_mut().set_selection(Selection::point(pos));
} }
pub fn page_up(cx: &mut Context) { pub fn page_up(cx: &mut Context) {
@ -437,7 +440,7 @@ pub fn half_page_down(cx: &mut Context) {
pub fn extend_char_left(cx: &mut Context) { pub fn extend_char_left(cx: &mut Context) {
let count = cx.count; let count = cx.count;
let doc = cx.doc(); let mut doc = cx.doc();
let text = doc.text().slice(..); let text = doc.text().slice(..);
let selection = doc.selection().transform(|range| { let selection = doc.selection().transform(|range| {
movement::move_horizontally( movement::move_horizontally(
@ -453,7 +456,7 @@ pub fn extend_char_left(cx: &mut Context) {
pub fn extend_char_right(cx: &mut Context) { pub fn extend_char_right(cx: &mut Context) {
let count = cx.count; let count = cx.count;
let doc = cx.doc(); let mut doc = cx.doc();
let text = doc.text().slice(..); let text = doc.text().slice(..);
let selection = doc.selection().transform(|range| { let selection = doc.selection().transform(|range| {
movement::move_horizontally( movement::move_horizontally(
@ -469,7 +472,7 @@ pub fn extend_char_right(cx: &mut Context) {
pub fn extend_line_up(cx: &mut Context) { pub fn extend_line_up(cx: &mut Context) {
let count = cx.count; let count = cx.count;
let doc = cx.doc(); let mut doc = cx.doc();
let text = doc.text().slice(..); let text = doc.text().slice(..);
let selection = doc.selection().transform(|range| { let selection = doc.selection().transform(|range| {
movement::move_vertically( movement::move_vertically(
@ -485,7 +488,7 @@ pub fn extend_line_up(cx: &mut Context) {
pub fn extend_line_down(cx: &mut Context) { pub fn extend_line_down(cx: &mut Context) {
let count = cx.count; let count = cx.count;
let doc = cx.doc(); let mut doc = cx.doc();
let text = doc.text().slice(..); let text = doc.text().slice(..);
let selection = doc.selection().transform(|range| { let selection = doc.selection().transform(|range| {
movement::move_vertically( movement::move_vertically(
@ -500,12 +503,10 @@ pub fn extend_line_down(cx: &mut Context) {
} }
pub fn select_all(cx: &mut Context) { pub fn select_all(cx: &mut Context) {
let doc = cx.doc(); let mut doc = cx.doc();
doc.set_selection(Selection::single( let end = doc.text().len_chars().saturating_sub(1);
0, doc.set_selection(Selection::single(0, end))
doc.text().len_chars().saturating_sub(1),
))
} }
pub fn select_regex(cx: &mut Context) { pub fn select_regex(cx: &mut Context) {
@ -530,7 +531,7 @@ pub fn split_selection(cx: &mut Context) {
} }
pub fn split_selection_on_newline(cx: &mut Context) { pub fn split_selection_on_newline(cx: &mut Context) {
let doc = cx.doc(); let mut doc = cx.doc();
let text = doc.text().slice(..); let text = doc.text().slice(..);
// only compile the regex once // only compile the regex once
#[allow(clippy::trivial_regex)] #[allow(clippy::trivial_regex)]
@ -562,13 +563,14 @@ fn _search(doc: &mut Document, contents: &str, regex: &Regex) {
// TODO: use one function for search vs extend // TODO: use one function for search vs extend
pub fn search(cx: &mut Context) { pub fn search(cx: &mut Context) {
let doc = cx.doc(); let mut doc = cx.doc();
// TODO: could probably share with select_on_matches? // TODO: could probably share with select_on_matches?
// HAXX: sadly we can't avoid allocating a single string for the whole buffer since we can't // HAXX: sadly we can't avoid allocating a single string for the whole buffer since we can't
// feed chunks into the regex yet // feed chunks into the regex yet
let contents = doc.text().slice(..).to_string(); let contents = doc.text().slice(..).to_string();
drop(doc);
let prompt = ui::regex_prompt(cx, "search:".to_string(), move |doc, regex| { let prompt = ui::regex_prompt(cx, "search:".to_string(), move |doc, regex| {
let text = doc.text(); let text = doc.text();
@ -585,19 +587,20 @@ pub fn search(cx: &mut Context) {
pub fn search_next(cx: &mut Context) { pub fn search_next(cx: &mut Context) {
if let Some(query) = register::get('\\') { if let Some(query) = register::get('\\') {
let query = query.first().unwrap(); let query = query.first().unwrap();
let doc = cx.doc(); let mut doc = cx.doc();
let contents = doc.text().slice(..).to_string(); let contents = doc.text().slice(..).to_string();
let regex = Regex::new(&query).unwrap(); let regex = Regex::new(&query).unwrap();
_search(doc, &contents, &regex); _search(&mut doc, &contents, &regex);
} }
} }
pub fn search_selection(cx: &mut Context) { pub fn search_selection(cx: &mut Context) {
let doc = cx.doc(); let mut doc = cx.doc();
let contents = doc.text().slice(..); let contents = doc.text().slice(..);
let query = doc.selection().primary().fragment(contents); let query = doc.selection().primary().fragment(contents);
let regex = regex::escape(&query); let regex = regex::escape(&query);
register::set('\\', vec![regex]); register::set('\\', vec![regex]);
drop(doc);
search_next(cx); search_next(cx);
} }
@ -609,7 +612,7 @@ pub fn search_selection(cx: &mut Context) {
pub fn select_line(cx: &mut Context) { pub fn select_line(cx: &mut Context) {
let count = cx.count; let count = cx.count;
let doc = cx.doc(); let mut doc = cx.doc();
let pos = doc.selection().primary(); let pos = doc.selection().primary();
let text = doc.text(); let text = doc.text();
@ -622,7 +625,7 @@ pub fn select_line(cx: &mut Context) {
} }
pub fn extend_line(cx: &mut Context) { pub fn extend_line(cx: &mut Context) {
let count = cx.count; let count = cx.count;
let doc = cx.doc(); let mut doc = cx.doc();
let pos = doc.selection().primary(); let pos = doc.selection().primary();
let text = doc.text(); let text = doc.text();
@ -650,20 +653,21 @@ fn _delete_selection(doc: &mut Document) {
} }
pub fn delete_selection(cx: &mut Context) { pub fn delete_selection(cx: &mut Context) {
let doc = cx.doc(); let mut doc = cx.doc();
_delete_selection(doc); _delete_selection(&mut doc);
doc.append_changes_to_history(); doc.append_changes_to_history();
} }
pub fn change_selection(cx: &mut Context) { pub fn change_selection(cx: &mut Context) {
let doc = cx.doc(); let mut doc = cx.doc();
_delete_selection(doc); _delete_selection(&mut doc);
drop(doc);
insert_mode(cx); insert_mode(cx);
} }
pub fn collapse_selection(cx: &mut Context) { pub fn collapse_selection(cx: &mut Context) {
let doc = cx.doc(); let mut doc = cx.doc();
let selection = doc let selection = doc
.selection() .selection()
.transform(|range| Range::new(range.head, range.head)); .transform(|range| Range::new(range.head, range.head));
@ -672,7 +676,7 @@ pub fn collapse_selection(cx: &mut Context) {
} }
pub fn flip_selections(cx: &mut Context) { pub fn flip_selections(cx: &mut Context) {
let doc = cx.doc(); let mut doc = cx.doc();
let selection = doc let selection = doc
.selection() .selection()
.transform(|range| Range::new(range.head, range.anchor)); .transform(|range| Range::new(range.head, range.anchor));
@ -686,8 +690,8 @@ fn enter_insert_mode(doc: &mut Document) {
// inserts at the start of each selection // inserts at the start of each selection
pub fn insert_mode(cx: &mut Context) { pub fn insert_mode(cx: &mut Context) {
let doc = cx.doc(); let mut doc = cx.doc();
enter_insert_mode(doc); enter_insert_mode(&mut doc);
let selection = doc let selection = doc
.selection() .selection()
@ -697,8 +701,8 @@ pub fn insert_mode(cx: &mut Context) {
// inserts at the end of each selection // inserts at the end of each selection
pub fn append_mode(cx: &mut Context) { pub fn append_mode(cx: &mut Context) {
let doc = cx.doc(); let mut doc = cx.doc();
enter_insert_mode(doc); enter_insert_mode(&mut doc);
doc.restore_cursor = true; doc.restore_cursor = true;
let text = doc.text().slice(..); let text = doc.text().slice(..);
@ -765,7 +769,7 @@ pub fn command_mode(cx: &mut Context) {
} }
["w"] | ["write"] => { ["w"] | ["write"] => {
// TODO: non-blocking via save() command // TODO: non-blocking via save() command
smol::block_on(editor.view_mut().doc.save()); smol::block_on(editor.view().doc.borrow().save());
} }
_ => (), _ => (),
@ -800,16 +804,18 @@ fn selection_lines(doc: &Rope, selection: &Selection) -> Vec<usize> {
// I inserts at the start of each line with a selection // I inserts at the start of each line with a selection
pub fn prepend_to_line(cx: &mut Context) { pub fn prepend_to_line(cx: &mut Context) {
let doc = cx.doc(); let mut doc = cx.doc();
enter_insert_mode(doc); enter_insert_mode(&mut doc);
drop(doc);
move_line_start(cx); move_line_start(cx);
} }
// A inserts at the end of each line with a selection // A inserts at the end of each line with a selection
pub fn append_to_line(cx: &mut Context) { pub fn append_to_line(cx: &mut Context) {
let doc = cx.doc(); let mut doc = cx.doc();
enter_insert_mode(doc); enter_insert_mode(&mut doc);
drop(doc);
move_line_end(cx); move_line_end(cx);
} }
@ -817,8 +823,8 @@ pub fn append_to_line(cx: &mut Context) {
// o inserts a new line after each line with a selection // o inserts a new line after each line with a selection
pub fn open_below(cx: &mut Context) { pub fn open_below(cx: &mut Context) {
let count = cx.count; let count = cx.count;
let doc = cx.doc(); let mut doc = cx.doc();
enter_insert_mode(doc); enter_insert_mode(&mut doc);
let lines = selection_lines(doc.text(), doc.selection()); let lines = selection_lines(doc.text(), doc.selection());
@ -875,7 +881,7 @@ pub fn open_below(cx: &mut Context) {
// O inserts a new line before each line with a selection // O inserts a new line before each line with a selection
pub fn normal_mode(cx: &mut Context) { pub fn normal_mode(cx: &mut Context) {
let doc = cx.doc(); let mut doc = cx.doc();
doc.mode = Mode::Normal; doc.mode = Mode::Normal;
@ -909,14 +915,12 @@ pub fn exit_select_mode(cx: &mut Context) {
} }
fn goto(cx: &mut Context, locations: Vec<lsp::Location>) { fn goto(cx: &mut Context, locations: Vec<lsp::Location>) {
let doc = cx.doc(); cx.doc().mode = Mode::Normal;
doc.mode = Mode::Normal;
match locations.as_slice() { match locations.as_slice() {
[location] => { [location] => {
cx.editor.open(PathBuf::from(location.uri.path())); cx.editor.open(PathBuf::from(location.uri.path()));
let doc = cx.doc(); let mut doc = cx.doc();
let definition_pos = location.range.start; let definition_pos = location.range.start;
let new_pos = helix_lsp::util::lsp_pos_to_pos(doc.text(), definition_pos); let new_pos = helix_lsp::util::lsp_pos_to_pos(doc.text(), definition_pos);
doc.set_selection(Selection::point(new_pos)); doc.set_selection(Selection::point(new_pos));
@ -932,7 +936,8 @@ fn goto(cx: &mut Context, locations: Vec<lsp::Location>) {
}, },
move |editor: &mut Editor, item| { move |editor: &mut Editor, item| {
editor.open(PathBuf::from(item.uri.path())); editor.open(PathBuf::from(item.uri.path()));
let mut doc = &mut editor.view_mut().doc; // TODO: issues with doc already being broo
let mut doc = &mut editor.view().doc.borrow_mut();
let definition_pos = item.range.start; let definition_pos = item.range.start;
let new_pos = helix_lsp::util::lsp_pos_to_pos(doc.text(), definition_pos); let new_pos = helix_lsp::util::lsp_pos_to_pos(doc.text(), definition_pos);
doc.set_selection(Selection::point(new_pos)); doc.set_selection(Selection::point(new_pos));
@ -944,7 +949,7 @@ fn goto(cx: &mut Context, locations: Vec<lsp::Location>) {
} }
pub fn goto_definition(cx: &mut Context) { pub fn goto_definition(cx: &mut Context) {
let doc = cx.doc(); let mut doc = cx.doc();
let language_server = match doc.language_server() { let language_server = match doc.language_server() {
Some(language_server) => language_server, Some(language_server) => language_server,
None => return, None => return,
@ -956,11 +961,12 @@ pub fn goto_definition(cx: &mut Context) {
// TODO: handle fails // TODO: handle fails
let res = let res =
smol::block_on(language_server.goto_definition(doc.identifier(), pos)).unwrap_or_default(); smol::block_on(language_server.goto_definition(doc.identifier(), pos)).unwrap_or_default();
drop(doc);
goto(cx, res); goto(cx, res);
} }
pub fn goto_type_definition(cx: &mut Context) { pub fn goto_type_definition(cx: &mut Context) {
let doc = cx.doc(); let mut doc = cx.doc();
let language_server = match doc.language_server() { let language_server = match doc.language_server() {
Some(language_server) => language_server, Some(language_server) => language_server,
None => return, None => return,
@ -972,11 +978,12 @@ pub fn goto_type_definition(cx: &mut Context) {
// TODO: handle fails // TODO: handle fails
let res = smol::block_on(language_server.goto_type_definition(doc.identifier(), pos)) let res = smol::block_on(language_server.goto_type_definition(doc.identifier(), pos))
.unwrap_or_default(); .unwrap_or_default();
drop(doc);
goto(cx, res); goto(cx, res);
} }
pub fn goto_implementation(cx: &mut Context) { pub fn goto_implementation(cx: &mut Context) {
let doc = cx.doc(); let mut doc = cx.doc();
let language_server = match doc.language_server() { let language_server = match doc.language_server() {
Some(language_server) => language_server, Some(language_server) => language_server,
None => return, None => return,
@ -988,11 +995,12 @@ pub fn goto_implementation(cx: &mut Context) {
// TODO: handle fails // TODO: handle fails
let res = smol::block_on(language_server.goto_implementation(doc.identifier(), pos)) let res = smol::block_on(language_server.goto_implementation(doc.identifier(), pos))
.unwrap_or_default(); .unwrap_or_default();
drop(doc);
goto(cx, res); goto(cx, res);
} }
pub fn goto_reference(cx: &mut Context) { pub fn goto_reference(cx: &mut Context) {
let doc = cx.doc(); let mut doc = cx.doc();
let language_server = match doc.language_server() { let language_server = match doc.language_server() {
Some(language_server) => language_server, Some(language_server) => language_server,
None => return, None => return,
@ -1004,6 +1012,7 @@ pub fn goto_reference(cx: &mut Context) {
// TODO: handle fails // TODO: handle fails
let res = let res =
smol::block_on(language_server.goto_reference(doc.identifier(), pos)).unwrap_or_default(); smol::block_on(language_server.goto_reference(doc.identifier(), pos)).unwrap_or_default();
drop(doc);
goto(cx, res); goto(cx, res);
} }
@ -1017,7 +1026,7 @@ pub mod insert {
// TODO: insert means add text just before cursor, on exit we should be on the last letter. // TODO: insert means add text just before cursor, on exit we should be on the last letter.
pub fn insert_char(cx: &mut Context, c: char) { pub fn insert_char(cx: &mut Context, c: char) {
let doc = cx.doc(); let mut doc = cx.doc();
// run through insert hooks, stopping on the first one that returns Some(t) // run through insert hooks, stopping on the first one that returns Some(t)
for hook in HOOKS { for hook in HOOKS {
@ -1034,7 +1043,7 @@ pub mod insert {
} }
pub fn insert_tab(cx: &mut Context) { pub fn insert_tab(cx: &mut Context) {
let doc = cx.doc(); let mut doc = cx.doc();
// TODO: round out to nearest indentation level (for example a line with 3 spaces should // TODO: round out to nearest indentation level (for example a line with 3 spaces should
// indent by one to reach 4 spaces). // indent by one to reach 4 spaces).
@ -1044,7 +1053,7 @@ pub mod insert {
} }
pub fn insert_newline(cx: &mut Context) { pub fn insert_newline(cx: &mut Context) {
let doc = cx.doc(); let mut doc = cx.doc();
let text = doc.text().slice(..); let text = doc.text().slice(..);
let transaction = Transaction::change_by_selection(doc.text(), doc.selection(), |range| { let transaction = Transaction::change_by_selection(doc.text(), doc.selection(), |range| {
let indent_level = let indent_level =
@ -1061,7 +1070,7 @@ pub mod insert {
// TODO: handle indent-aware delete // TODO: handle indent-aware delete
pub fn delete_char_backward(cx: &mut Context) { pub fn delete_char_backward(cx: &mut Context) {
let count = cx.count; let count = cx.count;
let doc = cx.doc(); let mut doc = cx.doc();
let text = doc.text().slice(..); let text = doc.text().slice(..);
let transaction = Transaction::change_by_selection(doc.text(), doc.selection(), |range| { let transaction = Transaction::change_by_selection(doc.text(), doc.selection(), |range| {
( (
@ -1075,7 +1084,7 @@ pub mod insert {
pub fn delete_char_forward(cx: &mut Context) { pub fn delete_char_forward(cx: &mut Context) {
let count = cx.count; let count = cx.count;
let doc = cx.doc(); let mut doc = cx.doc();
let text = doc.text().slice(..); let text = doc.text().slice(..);
let transaction = Transaction::change_by_selection(doc.text(), doc.selection(), |range| { let transaction = Transaction::change_by_selection(doc.text(), doc.selection(), |range| {
( (
@ -1105,7 +1114,7 @@ pub fn redo(cx: &mut Context) {
pub fn yank(cx: &mut Context) { pub fn yank(cx: &mut Context) {
// TODO: should selections be made end inclusive? // TODO: should selections be made end inclusive?
let doc = cx.doc(); let mut doc = cx.doc();
let values = doc let values = doc
.selection() .selection()
.fragments(doc.text().slice(..)) .fragments(doc.text().slice(..))
@ -1146,7 +1155,7 @@ pub fn paste(cx: &mut Context) {
let mut values = values.into_iter().map(Tendril::from).chain(repeat); let mut values = values.into_iter().map(Tendril::from).chain(repeat);
let doc = cx.doc(); let mut doc = cx.doc();
let transaction = if linewise { let transaction = if linewise {
// paste on the next line // paste on the next line
@ -1185,8 +1194,8 @@ fn get_lines(doc: &Document) -> Vec<usize> {
} }
pub fn indent(cx: &mut Context) { pub fn indent(cx: &mut Context) {
let doc = cx.doc(); let mut doc = cx.doc();
let lines = get_lines(doc); let lines = get_lines(&mut doc);
// Indent by one level // Indent by one level
let indent = Tendril::from(doc.indent_unit()); let indent = Tendril::from(doc.indent_unit());
@ -1203,8 +1212,8 @@ pub fn indent(cx: &mut Context) {
} }
pub fn unindent(cx: &mut Context) { pub fn unindent(cx: &mut Context) {
let doc = cx.doc(); let mut doc = cx.doc();
let lines = get_lines(doc); let lines = get_lines(&mut doc);
let mut changes = Vec::with_capacity(lines.len()); let mut changes = Vec::with_capacity(lines.len());
let tab_width = doc.tab_width(); let tab_width = doc.tab_width();
@ -1238,7 +1247,7 @@ pub fn unindent(cx: &mut Context) {
pub fn format_selections(cx: &mut Context) { pub fn format_selections(cx: &mut Context) {
use helix_lsp::lsp; use helix_lsp::lsp;
let doc = cx.doc(); let mut doc = cx.doc();
// via lsp if available // via lsp if available
// else via tree-sitter indentation calculations // else via tree-sitter indentation calculations
@ -1276,7 +1285,7 @@ pub fn format_selections(cx: &mut Context) {
pub fn join_selections(cx: &mut Context) { pub fn join_selections(cx: &mut Context) {
use movement::skip_over_next; use movement::skip_over_next;
let doc = cx.doc(); let mut doc = cx.doc();
let text = doc.text(); let text = doc.text();
let slice = doc.text().slice(..); let slice = doc.text().slice(..);
@ -1319,7 +1328,6 @@ pub fn join_selections(cx: &mut Context) {
} }
pub fn keep_selections(cx: &mut Context) { pub fn keep_selections(cx: &mut Context) {
let doc = cx.doc();
// keep selections matching regex // keep selections matching regex
let prompt = ui::regex_prompt(cx, "keep:".to_string(), |doc, regex| { let prompt = ui::regex_prompt(cx, "keep:".to_string(), |doc, regex| {
let text = doc.text().slice(..); let text = doc.text().slice(..);
@ -1333,7 +1341,7 @@ pub fn keep_selections(cx: &mut Context) {
} }
pub fn keep_primary_selection(cx: &mut Context) { pub fn keep_primary_selection(cx: &mut Context) {
let doc = cx.doc(); let mut doc = cx.doc();
let range = doc.selection().primary(); let range = doc.selection().primary();
let selection = Selection::single(range.anchor, range.head); let selection = Selection::single(range.anchor, range.head);
@ -1350,7 +1358,7 @@ pub fn save(cx: &mut Context) {
} }
pub fn completion(cx: &mut Context) { pub fn completion(cx: &mut Context) {
let doc = cx.doc(); let mut doc = cx.doc();
let language_server = match doc.language_server() { let language_server = match doc.language_server() {
Some(language_server) => language_server, Some(language_server) => language_server,
@ -1364,6 +1372,8 @@ pub fn completion(cx: &mut Context) {
let res = smol::block_on(language_server.completion(doc.identifier(), pos)).unwrap_or_default(); let res = smol::block_on(language_server.completion(doc.identifier(), pos)).unwrap_or_default();
drop(doc);
// TODO: if no completion, show some message or something // TODO: if no completion, show some message or something
if !res.is_empty() { if !res.is_empty() {
// let snapshot = doc.state.clone(); // let snapshot = doc.state.clone();
@ -1379,11 +1389,11 @@ pub fn completion(cx: &mut Context) {
match event { match event {
PromptEvent::Abort => { PromptEvent::Abort => {
// revert state // revert state
let doc = &mut editor.view_mut().doc; let doc = &mut editor.view().doc.borrow_mut();
// doc.state = snapshot.clone(); // doc.state = snapshot.clone();
} }
PromptEvent::Validate => { PromptEvent::Validate => {
let doc = &mut editor.view_mut().doc; let doc = &mut editor.view().doc.borrow_mut();
// revert state to what it was before the last update // revert state to what it was before the last update
// doc.state = snapshot.clone(); // doc.state = snapshot.clone();
@ -1449,7 +1459,7 @@ pub fn completion(cx: &mut Context) {
pub fn hover(cx: &mut Context) { pub fn hover(cx: &mut Context) {
use helix_lsp::lsp; use helix_lsp::lsp;
let doc = cx.doc(); let mut doc = cx.doc();
let language_server = match doc.language_server() { let language_server = match doc.language_server() {
Some(language_server) => language_server, Some(language_server) => language_server,
@ -1466,6 +1476,8 @@ pub fn hover(cx: &mut Context) {
let res = smol::block_on(language_server.text_document_hover(doc.identifier(), pos)) let res = smol::block_on(language_server.text_document_hover(doc.identifier(), pos))
.unwrap_or_default(); .unwrap_or_default();
drop(doc);
if let Some(hover) = res { if let Some(hover) = res {
// hover.contents / .range <- used for visualizing // hover.contents / .range <- used for visualizing
let contents = match hover.contents { let contents = match hover.contents {
@ -1491,12 +1503,12 @@ pub fn hover(cx: &mut Context) {
// view movements // view movements
pub fn next_view(cx: &mut Context) { pub fn next_view(cx: &mut Context) {
cx.editor.tree.focus_next() cx.editor.focus_next()
} }
// comments // comments
pub fn toggle_comments(cx: &mut Context) { pub fn toggle_comments(cx: &mut Context) {
let doc = cx.doc(); let mut doc = cx.doc();
let transaction = comment::toggle_line_comments(doc.text(), doc.selection()); let transaction = comment::toggle_line_comments(doc.text(), doc.selection());
doc.apply(&transaction); doc.apply(&transaction);
@ -1506,7 +1518,7 @@ pub fn toggle_comments(cx: &mut Context) {
// tree sitter node selection // tree sitter node selection
pub fn expand_selection(cx: &mut Context) { pub fn expand_selection(cx: &mut Context) {
let doc = cx.doc(); let mut doc = cx.doc();
if let Some(syntax) = doc.syntax() { if let Some(syntax) = doc.syntax() {
let text = doc.text().slice(..); let text = doc.text().slice(..);

@ -57,7 +57,8 @@ impl EditorView {
// TODO: this seems to prevent setting style later // TODO: this seems to prevent setting style later
// surface.set_style(viewport, theme.get("ui.background")); // surface.set_style(viewport, theme.get("ui.background"));
self.render_diagnostics(&view.doc, area, surface, theme, is_focused); let doc = view.doc.borrow();
self.render_diagnostics(&doc, area, surface, theme, is_focused);
let area = Rect::new( let area = Rect::new(
viewport.x, viewport.x,
@ -65,7 +66,7 @@ impl EditorView {
viewport.width, viewport.width,
1, 1,
); );
self.render_statusline(&view.doc, area, surface, theme, is_focused); self.render_statusline(&doc, area, surface, theme, is_focused);
} }
pub fn render_buffer( pub fn render_buffer(
@ -76,7 +77,8 @@ impl EditorView {
theme: &Theme, theme: &Theme,
is_focused: bool, is_focused: bool,
) { ) {
let text = view.doc.text(); let doc = view.doc.borrow();
let text = doc.text().slice(..);
let last_line = view.last_line(); let last_line = view.last_line();
@ -91,7 +93,7 @@ impl EditorView {
// TODO: range doesn't actually restrict source, just highlight range // TODO: range doesn't actually restrict source, just highlight range
// TODO: cache highlight results // TODO: cache highlight results
// TODO: only recalculate when state.doc is actually modified // TODO: only recalculate when state.doc is actually modified
let highlights: Vec<_> = match view.doc.syntax() { let highlights: Vec<_> = match doc.syntax() {
Some(syntax) => { Some(syntax) => {
syntax syntax
.highlight_iter(text.slice(..), Some(range), None, |_| None) .highlight_iter(text.slice(..), Some(range), None, |_| None)
@ -105,7 +107,7 @@ impl EditorView {
let mut spans = Vec::new(); let mut spans = Vec::new();
let mut visual_x = 0; let mut visual_x = 0;
let mut line = 0u16; let mut line = 0u16;
let tab_width = view.doc.tab_width(); let tab_width = doc.tab_width();
'outer: for event in highlights { 'outer: for event in highlights {
match event.unwrap() { match event.unwrap() {
@ -167,7 +169,7 @@ impl EditorView {
let width = grapheme_width(&grapheme) as u16; let width = grapheme_width(&grapheme) as u16;
// ugh,interleave highlight spans with diagnostic spans // ugh,interleave highlight spans with diagnostic spans
let is_diagnostic = view.doc.diagnostics.iter().any(|diagnostic| { let is_diagnostic = doc.diagnostics.iter().any(|diagnostic| {
diagnostic.range.start <= char_index diagnostic.range.start <= char_index
&& diagnostic.range.end > char_index && diagnostic.range.end > char_index
}); });
@ -202,7 +204,6 @@ impl EditorView {
let end = text.line_to_char(last_line + 1); let end = text.line_to_char(last_line + 1);
Range::new(start, end) Range::new(start, end)
}; };
let text = text.slice(..);
let cursor_style = Style::default() let cursor_style = Style::default()
// .bg(Color::Rgb(255, 255, 255)) // .bg(Color::Rgb(255, 255, 255))
.add_modifier(Modifier::REVERSED); .add_modifier(Modifier::REVERSED);
@ -212,6 +213,7 @@ impl EditorView {
for selection in view for selection in view
.doc .doc
.borrow()
.selection() .selection()
.iter() .iter()
.filter(|range| range.overlaps(&screen)) .filter(|range| range.overlaps(&screen))
@ -293,7 +295,7 @@ impl EditorView {
let last_line = view.last_line(); let last_line = view.last_line();
for (i, line) in (view.first_line..last_line).enumerate() { for (i, line) in (view.first_line..last_line).enumerate() {
use helix_core::diagnostic::Severity; use helix_core::diagnostic::Severity;
if let Some(diagnostic) = view.doc.diagnostics.iter().find(|d| d.line == line) { if let Some(diagnostic) = doc.diagnostics.iter().find(|d| d.line == line) {
surface.set_stringn( surface.set_stringn(
viewport.x - OFFSET, viewport.x - OFFSET,
viewport.y + i as u16, viewport.y + i as u16,
@ -433,9 +435,8 @@ impl Component for EditorView {
EventResult::Consumed(None) EventResult::Consumed(None)
} }
Event::Key(event) => { Event::Key(event) => {
let view = cx.editor.view_mut(); let mode = cx.editor.view().doc.borrow().mode();
let mode = view.doc.mode();
let mut cxt = commands::Context { let mut cxt = commands::Context {
editor: &mut cx.editor, editor: &mut cx.editor,
count: 1, count: 1,

@ -39,9 +39,8 @@ pub fn regex_prompt(
move |editor: &mut Editor, input: &str, event: PromptEvent| { move |editor: &mut Editor, input: &str, event: PromptEvent| {
match event { match event {
PromptEvent::Abort => { PromptEvent::Abort => {
// TODO: also revert doc
// TODO: also revert text // TODO: also revert text
let doc = &mut editor.view_mut().doc; let doc = &mut editor.view().doc.borrow_mut();
doc.set_selection(snapshot.clone()); doc.set_selection(snapshot.clone());
} }
PromptEvent::Validate => { PromptEvent::Validate => {
@ -56,13 +55,15 @@ pub fn regex_prompt(
match Regex::new(input) { match Regex::new(input) {
Ok(regex) => { Ok(regex) => {
let view = &mut editor.view_mut(); let view = &mut editor.view_mut();
let doc = &mut view.doc; let mut doc = view.doc.borrow_mut();
// revert state to what it was before the last update // revert state to what it was before the last update
// TODO: also revert text // TODO: also revert text
doc.set_selection(snapshot.clone()); doc.set_selection(snapshot.clone());
fun(doc, regex); fun(&mut doc, regex);
drop(doc);
view.ensure_cursor_in_view(); view.ensure_cursor_in_view();
} }

@ -1,14 +1,15 @@
use crate::{theme::Theme, tree::Tree, Document, View}; use crate::{theme::Theme, tree::Tree, Document, DocumentId, View};
use std::path::PathBuf; use std::path::PathBuf;
use std::{cell::RefCell, rc::Rc};
use slotmap::DefaultKey as Key; use slotmap::{DefaultKey as Key, SlotMap};
use anyhow::Error; use anyhow::Error;
pub struct Editor { pub struct Editor {
pub tree: Tree, pub tree: Tree,
// pub documents: Vec<Document>, pub documents: SlotMap<DocumentId, Rc<RefCell<Document>>>,
pub count: Option<usize>, pub count: Option<usize>,
pub theme: Theme, pub theme: Theme,
pub language_servers: helix_lsp::Registry, pub language_servers: helix_lsp::Registry,
@ -25,6 +26,7 @@ impl Editor {
Self { Self {
tree: Tree::new(area), tree: Tree::new(area),
documents: SlotMap::with_key(),
count: None, count: None,
theme, theme,
language_servers, language_servers,
@ -33,10 +35,12 @@ impl Editor {
} }
pub fn open(&mut self, path: PathBuf) -> Result<(), Error> { pub fn open(&mut self, path: PathBuf) -> Result<(), Error> {
// TODO: issues with doc already being borrowed if called from inside goto()
let existing_view = self let existing_view = self
.tree .tree
.views() .views()
.find(|(view, _)| view.doc.path() == Some(&path)); .find(|(view, _)| view.doc.borrow().path() == Some(&path));
if let Some((view, _)) = existing_view { if let Some((view, _)) = existing_view {
self.tree.focus = view.id; self.tree.focus = view.id;
@ -69,6 +73,10 @@ impl Editor {
.unwrap(); .unwrap();
} }
let doc = Rc::new(RefCell::new(doc));
// TODO: store id as doc.id
let id = self.documents.insert(doc.clone());
let view = View::new(doc)?; let view = View::new(doc)?;
self.tree.insert(view); self.tree.insert(view);
Ok(()) Ok(())
@ -80,7 +88,7 @@ impl Editor {
let language_servers = &mut self.language_servers; let language_servers = &mut self.language_servers;
let executor = self.executor; let executor = self.executor;
let doc = &view.doc; let doc = view.doc.borrow();
let language_server = doc let language_server = doc
.language .language
@ -90,7 +98,19 @@ impl Editor {
if let Some(language_server) = language_server { if let Some(language_server) = language_server {
smol::block_on(language_server.text_document_did_close(doc.identifier())).unwrap(); smol::block_on(language_server.text_document_did_close(doc.identifier())).unwrap();
} }
self.tree.remove(id)
drop(doc); // to stop borrowing self.tree
// self.documents.remove(view.doc);
self.tree.remove(id);
}
pub fn resize(&mut self) {
self.tree.focus_next();
}
pub fn focus_next(&mut self) {
self.tree.focus_next();
} }
pub fn should_close(&self) -> bool { pub fn should_close(&self) -> bool {
@ -108,8 +128,9 @@ impl Editor {
pub fn cursor_position(&self) -> Option<helix_core::Position> { pub fn cursor_position(&self) -> Option<helix_core::Position> {
const OFFSET: u16 = 7; // 1 diagnostic + 5 linenr + 1 gutter const OFFSET: u16 = 7; // 1 diagnostic + 5 linenr + 1 gutter
let view = self.view(); let view = self.view();
let cursor = view.doc.selection().cursor(); let doc = view.doc.borrow();
if let Some(mut pos) = view.screen_coords_at_pos(view.doc.text().slice(..), cursor) { let cursor = doc.selection().cursor();
if let Some(mut pos) = view.screen_coords_at_pos(doc.text().slice(..), cursor) {
pos.col += view.area.x as usize + OFFSET as usize; pos.col += view.area.x as usize + OFFSET as usize;
pos.row += view.area.y as usize; pos.row += view.area.y as usize;
return Some(pos); return Some(pos);

@ -4,6 +4,9 @@ pub mod theme;
pub mod tree; pub mod tree;
pub mod view; pub mod view;
use slotmap::new_key_type;
new_key_type! { pub struct DocumentId; }
pub use document::Document; pub use document::Document;
pub use editor::Editor; pub use editor::Editor;
pub use theme::Theme; pub use theme::Theme;

@ -1,8 +1,9 @@
use anyhow::Error; use anyhow::Error;
use std::borrow::Cow; use std::borrow::Cow;
use std::{cell::RefCell, rc::Rc};
use crate::Document; use crate::{Document, DocumentId};
use helix_core::{ use helix_core::{
graphemes::{grapheme_width, RopeGraphemes}, graphemes::{grapheme_width, RopeGraphemes},
Position, RopeSlice, Position, RopeSlice,
@ -14,13 +15,13 @@ pub const PADDING: usize = 5;
pub struct View { pub struct View {
pub id: Key, pub id: Key,
pub doc: Document, pub doc: Rc<RefCell<Document>>,
pub first_line: usize, pub first_line: usize,
pub area: Rect, pub area: Rect,
} }
impl View { impl View {
pub fn new(doc: Document) -> Result<Self, Error> { pub fn new(doc: Rc<RefCell<Document>>) -> Result<Self, Error> {
let view = Self { let view = Self {
id: Key::default(), id: Key::default(),
doc, doc,
@ -32,8 +33,9 @@ impl View {
} }
pub fn ensure_cursor_in_view(&mut self) { pub fn ensure_cursor_in_view(&mut self) {
let cursor = self.doc.selection().cursor(); let doc = self.doc.borrow();
let line = self.doc.text().char_to_line(cursor); let cursor = doc.selection().cursor();
let line = doc.text().char_to_line(cursor);
let document_end = self.first_line + (self.area.height as usize).saturating_sub(2); let document_end = self.first_line + (self.area.height as usize).saturating_sub(2);
// TODO: side scroll // TODO: side scroll
@ -50,10 +52,11 @@ impl View {
/// Calculates the last visible line on screen /// Calculates the last visible line on screen
#[inline] #[inline]
pub fn last_line(&self) -> usize { pub fn last_line(&self) -> usize {
let doc = self.doc.borrow();
let height = self.area.height.saturating_sub(1); // - 1 for statusline let height = self.area.height.saturating_sub(1); // - 1 for statusline
std::cmp::min( std::cmp::min(
self.first_line + height as usize, self.first_line + height as usize,
self.doc.text().len_lines() - 1, doc.text().len_lines() - 1,
) )
} }
@ -71,7 +74,7 @@ impl View {
let line_start = text.line_to_char(line); let line_start = text.line_to_char(line);
let line_slice = text.slice(line_start..pos); let line_slice = text.slice(line_start..pos);
let mut col = 0; let mut col = 0;
let tab_width = self.doc.tab_width(); let tab_width = self.doc.borrow().tab_width();
for grapheme in RopeGraphemes::new(line_slice) { for grapheme in RopeGraphemes::new(line_slice) {
if grapheme == "\t" { if grapheme == "\t" {

Loading…
Cancel
Save