Drop refcell use, make view simply ref doc.id.

pull/11/head
Blaž Hrastnik 4 years ago
parent 3f9a94fd43
commit 8328fe926d

@ -129,10 +129,9 @@ impl Application {
.editor .editor
.documents .documents
.iter_mut() .iter_mut()
.find(|(_, doc)| doc.borrow().path() == path.as_ref()); .find(|(_, doc)| doc.path() == path.as_ref());
if let Some((_, doc)) = doc { if let Some((_, doc)) = doc {
let mut doc = doc.borrow_mut();
let text = doc.text(); let text = doc.text();
let diagnostics = params let diagnostics = params
@ -167,7 +166,6 @@ impl Application {
.collect(); .collect();
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();
} }

@ -41,8 +41,9 @@ impl<'a> Context<'a> {
} }
#[inline] #[inline]
pub fn doc(&mut self) -> std::cell::RefMut<Document> { pub fn doc(&mut self) -> &mut Document {
self.editor.view().doc.borrow_mut() let id = self.editor.view().doc;
&mut self.editor.documents[id]
} }
/// Push a new component onto the compositor. /// Push a new component onto the compositor.
@ -72,7 +73,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 mut doc = cx.doc(); let 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 +89,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 mut doc = cx.doc(); let 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 +105,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 mut doc = cx.doc(); let 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 +121,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 mut doc = cx.doc(); let 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 +136,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 mut doc = cx.doc(); let 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 +156,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 mut doc = cx.doc(); let 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 +178,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 mut doc = cx.doc(); let 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 +191,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 mut doc = cx.doc(); let 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 +204,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 mut doc = cx.doc(); let 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 +216,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 mut doc = cx.doc(); let 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 mut doc = cx.doc(); let 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 +233,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 mut doc = cx.doc(); let 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 +246,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 mut doc = cx.doc(); let 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 +258,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 mut doc = cx.doc(); let 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 +287,7 @@ where
.. ..
} = event } = event
{ {
let mut doc = cx.doc(); let 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| {
@ -390,7 +391,7 @@ pub fn replace(cx: &mut Context) {
{ {
let text = Tendril::from_char(ch); let text = Tendril::from_char(ch);
let mut doc = cx.doc(); let doc = cx.doc();
let transaction = let transaction =
Transaction::change_by_selection(doc.text(), doc.selection(), |range| { Transaction::change_by_selection(doc.text(), doc.selection(), |range| {
@ -403,15 +404,14 @@ pub fn replace(cx: &mut Context) {
}) })
} }
fn scroll(view: &mut View, offset: usize, direction: Direction) { fn scroll(cx: &mut Context, offset: usize, direction: Direction) {
use Direction::*; use Direction::*;
// we use short lived borrows since view's methods read from doc too let view = cx.editor.view();
let doc = view.doc.borrow(); let doc = cx.editor.document(view.doc).unwrap();
let text = doc.text().slice(..);
let cursor = coords_at_pos(doc.text().slice(..), doc.selection().cursor()); let cursor = coords_at_pos(doc.text().slice(..), doc.selection().cursor());
let doc_last_line = doc.text().len_lines() - 1; let doc_last_line = doc.text().len_lines() - 1;
let last_line = view.last_line(); let last_line = view.last_line(doc);
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
@ -424,6 +424,9 @@ fn scroll(view: &mut View, offset: usize, direction: Direction) {
// cursor visual offset // cursor visual offset
let cursor_off = cursor.row - view.first_line; let cursor_off = cursor.row - view.first_line;
// upgrade to mut reference
let view = cx.editor.view_mut();
view.first_line = match direction { view.first_line = match direction {
Forward => view.first_line + offset, Forward => view.first_line + offset,
Backward => view.first_line.saturating_sub(offset), Backward => view.first_line.saturating_sub(offset),
@ -433,37 +436,47 @@ fn scroll(view: &mut View, offset: usize, direction: Direction) {
// clamp into viewport // clamp into viewport
let line = (view.first_line + cursor_off).clamp( let line = (view.first_line + cursor_off).clamp(
view.first_line + scrolloff, view.first_line + scrolloff,
view.last_line().saturating_sub(scrolloff), last_line.saturating_sub(scrolloff),
); );
// view drops here
// upgrade to mut reference
let doc = cx.doc();
let text = doc.text().slice(..);
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
drop(doc); // upgrade to mutable borrow
view.doc.borrow_mut().set_selection(Selection::point(pos)); doc.set_selection(Selection::point(pos));
} }
pub fn page_up(cx: &mut Context) { pub fn page_up(cx: &mut Context) {
let view = cx.view(); let view = cx.view();
scroll(view, view.area.height as usize, Direction::Backward); let offset = view.area.height as usize;
scroll(cx, offset, Direction::Backward);
} }
pub fn page_down(cx: &mut Context) { pub fn page_down(cx: &mut Context) {
let view = cx.view(); let view = cx.view();
scroll(view, view.area.height as usize, Direction::Forward); let offset = view.area.height as usize;
scroll(cx, offset, Direction::Forward);
} }
pub fn half_page_up(cx: &mut Context) { pub fn half_page_up(cx: &mut Context) {
let view = cx.view(); let view = cx.view();
scroll(view, view.area.height as usize / 2, Direction::Backward); let offset = view.area.height as usize / 2;
scroll(cx, offset, Direction::Backward);
} }
pub fn half_page_down(cx: &mut Context) { pub fn half_page_down(cx: &mut Context) {
let view = cx.view(); let view = cx.view();
scroll(view, view.area.height as usize / 2, Direction::Forward); let offset = view.area.height as usize / 2;
scroll(cx, offset, Direction::Forward);
} }
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 mut doc = cx.doc(); let 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(
@ -479,7 +492,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 mut doc = cx.doc(); let 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(
@ -495,7 +508,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 mut doc = cx.doc(); let 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(
@ -511,7 +524,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 mut doc = cx.doc(); let 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(
@ -526,7 +539,7 @@ pub fn extend_line_down(cx: &mut Context) {
} }
pub fn select_all(cx: &mut Context) { pub fn select_all(cx: &mut Context) {
let mut doc = cx.doc(); let doc = cx.doc();
let end = doc.text().len_chars().saturating_sub(1); let end = doc.text().len_chars().saturating_sub(1);
doc.set_selection(Selection::single(0, end)) doc.set_selection(Selection::single(0, end))
@ -554,7 +567,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 mut doc = cx.doc(); let 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)]
@ -586,14 +599,13 @@ 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 mut doc = cx.doc(); let 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();
@ -610,20 +622,19 @@ 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 mut doc = cx.doc(); let 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(&mut doc, &contents, &regex); _search(doc, &contents, &regex);
} }
} }
pub fn search_selection(cx: &mut Context) { pub fn search_selection(cx: &mut Context) {
let mut doc = cx.doc(); let 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);
} }
@ -635,7 +646,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 mut doc = cx.doc(); let doc = cx.doc();
let pos = doc.selection().primary(); let pos = doc.selection().primary();
let text = doc.text(); let text = doc.text();
@ -648,7 +659,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 mut doc = cx.doc(); let doc = cx.doc();
let pos = doc.selection().primary(); let pos = doc.selection().primary();
let text = doc.text(); let text = doc.text();
@ -676,21 +687,20 @@ fn _delete_selection(doc: &mut Document) {
} }
pub fn delete_selection(cx: &mut Context) { pub fn delete_selection(cx: &mut Context) {
let mut doc = cx.doc(); let doc = cx.doc();
_delete_selection(&mut doc); _delete_selection(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 mut doc = cx.doc(); let doc = cx.doc();
_delete_selection(&mut doc); _delete_selection(doc);
drop(doc);
insert_mode(cx); insert_mode(cx);
} }
pub fn collapse_selection(cx: &mut Context) { pub fn collapse_selection(cx: &mut Context) {
let mut doc = cx.doc(); let 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));
@ -699,7 +709,7 @@ pub fn collapse_selection(cx: &mut Context) {
} }
pub fn flip_selections(cx: &mut Context) { pub fn flip_selections(cx: &mut Context) {
let mut doc = cx.doc(); let 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));
@ -713,8 +723,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 mut doc = cx.doc(); let doc = cx.doc();
enter_insert_mode(&mut doc); enter_insert_mode(doc);
let selection = doc let selection = doc
.selection() .selection()
@ -724,8 +734,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 mut doc = cx.doc(); let doc = cx.doc();
enter_insert_mode(&mut doc); enter_insert_mode(doc);
doc.restore_cursor = true; doc.restore_cursor = true;
let text = doc.text().slice(..); let text = doc.text().slice(..);
@ -792,7 +802,9 @@ 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().doc.borrow().save()); let id = editor.view().doc;
let doc = &mut editor.document(id).unwrap();
smol::block_on(doc.save());
} }
_ => (), _ => (),
@ -807,8 +819,9 @@ pub fn file_picker(cx: &mut Context) {
} }
pub fn buffer_picker(cx: &mut Context) { pub fn buffer_picker(cx: &mut Context) {
unimplemented!() // let documents = cx.editor.documents.iter().map(||).collect();
// let picker = ui::buffer_picker(&editor.views, editor.focus); // (document_id, relative_path/name) mappings
// let picker = ui::buffer_picker(&documents, editor.focus);
// cx.push_layer(Box::new(picker)); // cx.push_layer(Box::new(picker));
} }
@ -827,18 +840,16 @@ 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 mut doc = cx.doc(); let doc = cx.doc();
enter_insert_mode(&mut doc); enter_insert_mode(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 mut doc = cx.doc(); let doc = cx.doc();
enter_insert_mode(&mut doc); enter_insert_mode(doc);
drop(doc);
move_line_end(cx); move_line_end(cx);
} }
@ -846,8 +857,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 mut doc = cx.doc(); let doc = cx.doc();
enter_insert_mode(&mut doc); enter_insert_mode(doc);
let lines = selection_lines(doc.text(), doc.selection()); let lines = selection_lines(doc.text(), doc.selection());
@ -897,8 +908,8 @@ 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 open_above(cx: &mut Context) { pub fn open_above(cx: &mut Context) {
let count = cx.count; let count = cx.count;
let mut doc = cx.doc(); let doc = cx.doc();
enter_insert_mode(&mut doc); enter_insert_mode(doc);
let lines = selection_lines(doc.text(), doc.selection()); let lines = selection_lines(doc.text(), doc.selection());
@ -947,7 +958,7 @@ pub fn open_above(cx: &mut Context) {
} }
pub fn normal_mode(cx: &mut Context) { pub fn normal_mode(cx: &mut Context) {
let mut doc = cx.doc(); let doc = cx.doc();
doc.mode = Mode::Normal; doc.mode = Mode::Normal;
@ -986,7 +997,7 @@ fn goto(cx: &mut Context, locations: Vec<lsp::Location>) {
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 mut doc = cx.doc(); let 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));
@ -1003,7 +1014,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()));
// TODO: issues with doc already being broo // TODO: issues with doc already being broo
let mut doc = &mut editor.view().doc.borrow_mut(); let id = editor.view().doc;
let doc = &mut editor.documents[id];
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));
@ -1015,7 +1027,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 mut doc = cx.doc(); let 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,
@ -1027,12 +1039,11 @@ 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 mut doc = cx.doc(); let 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,
@ -1044,12 +1055,11 @@ 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 mut doc = cx.doc(); let 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,
@ -1061,12 +1071,11 @@ 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 mut doc = cx.doc(); let 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,
@ -1078,7 +1087,6 @@ 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);
} }
@ -1092,7 +1100,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 mut doc = cx.doc(); let 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 {
@ -1109,7 +1117,7 @@ pub mod insert {
} }
pub fn insert_tab(cx: &mut Context) { pub fn insert_tab(cx: &mut Context) {
let mut doc = cx.doc(); let 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).
@ -1119,7 +1127,7 @@ pub mod insert {
} }
pub fn insert_newline(cx: &mut Context) { pub fn insert_newline(cx: &mut Context) {
let mut doc = cx.doc(); let 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 =
@ -1136,7 +1144,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 mut doc = cx.doc(); let 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| {
( (
@ -1150,7 +1158,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 mut doc = cx.doc(); let 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| {
( (
@ -1180,7 +1188,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 mut doc = cx.doc(); let doc = cx.doc();
let values = doc let values = doc
.selection() .selection()
.fragments(doc.text().slice(..)) .fragments(doc.text().slice(..))
@ -1221,7 +1229,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 mut doc = cx.doc(); let doc = cx.doc();
let transaction = if linewise { let transaction = if linewise {
// paste on the next line // paste on the next line
@ -1260,8 +1268,8 @@ fn get_lines(doc: &Document) -> Vec<usize> {
} }
pub fn indent(cx: &mut Context) { pub fn indent(cx: &mut Context) {
let mut doc = cx.doc(); let doc = cx.doc();
let lines = get_lines(&mut doc); let lines = get_lines(doc);
// Indent by one level // Indent by one level
let indent = Tendril::from(doc.indent_unit()); let indent = Tendril::from(doc.indent_unit());
@ -1278,8 +1286,8 @@ pub fn indent(cx: &mut Context) {
} }
pub fn unindent(cx: &mut Context) { pub fn unindent(cx: &mut Context) {
let mut doc = cx.doc(); let doc = cx.doc();
let lines = get_lines(&mut doc); let lines = get_lines(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();
@ -1313,7 +1321,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 mut doc = cx.doc(); let doc = cx.doc();
// via lsp if available // via lsp if available
// else via tree-sitter indentation calculations // else via tree-sitter indentation calculations
@ -1351,7 +1359,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 mut doc = cx.doc(); let doc = cx.doc();
let text = doc.text(); let text = doc.text();
let slice = doc.text().slice(..); let slice = doc.text().slice(..);
@ -1407,7 +1415,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 mut doc = cx.doc(); let 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);
@ -1424,7 +1432,7 @@ pub fn save(cx: &mut Context) {
} }
pub fn completion(cx: &mut Context) { pub fn completion(cx: &mut Context) {
let mut doc = cx.doc(); let 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,
@ -1438,8 +1446,6 @@ 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();
@ -1455,11 +1461,13 @@ pub fn completion(cx: &mut Context) {
match event { match event {
PromptEvent::Abort => { PromptEvent::Abort => {
// revert state // revert state
let doc = &mut editor.view().doc.borrow_mut(); // let id = editor.view().doc;
// let doc = &mut editor.documents[id];
// doc.state = snapshot.clone(); // doc.state = snapshot.clone();
} }
PromptEvent::Validate => { PromptEvent::Validate => {
let doc = &mut editor.view().doc.borrow_mut(); let id = editor.view().doc;
let doc = &mut editor.documents[id];
// 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();
@ -1525,7 +1533,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 mut doc = cx.doc(); let 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,
@ -1542,8 +1550,6 @@ 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 {
@ -1574,7 +1580,7 @@ pub fn next_view(cx: &mut Context) {
// comments // comments
pub fn toggle_comments(cx: &mut Context) { pub fn toggle_comments(cx: &mut Context) {
let mut doc = cx.doc(); let 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);
@ -1584,7 +1590,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 mut doc = cx.doc(); let 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(..);
@ -1594,7 +1600,7 @@ pub fn expand_selection(cx: &mut Context) {
} }
pub fn match_brackets(cx: &mut Context) { pub fn match_brackets(cx: &mut Context) {
let mut doc = cx.doc(); let doc = cx.doc();
if let Some(syntax) = doc.syntax() { if let Some(syntax) = doc.syntax() {
let pos = doc.selection().cursor(); let pos = doc.selection().cursor();

@ -39,6 +39,7 @@ impl EditorView {
} }
pub fn render_view( pub fn render_view(
&self, &self,
doc: &Document,
view: &View, view: &View,
viewport: Rect, viewport: Rect,
surface: &mut Surface, surface: &mut Surface,
@ -51,13 +52,12 @@ impl EditorView {
viewport.width - OFFSET, viewport.width - OFFSET,
viewport.height.saturating_sub(1), viewport.height.saturating_sub(1),
); // - 1 for statusline ); // - 1 for statusline
self.render_buffer(view, area, surface, theme, is_focused); self.render_buffer(&doc, view, area, surface, theme, is_focused);
// clear with background color // clear with background color
// 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"));
let doc = view.doc.borrow();
self.render_diagnostics(&doc, area, surface, theme, is_focused); self.render_diagnostics(&doc, area, surface, theme, is_focused);
let area = Rect::new( let area = Rect::new(
@ -71,16 +71,16 @@ impl EditorView {
pub fn render_buffer( pub fn render_buffer(
&self, &self,
doc: &Document,
view: &View, view: &View,
viewport: Rect, viewport: Rect,
surface: &mut Surface, surface: &mut Surface,
theme: &Theme, theme: &Theme,
is_focused: bool, is_focused: bool,
) { ) {
let doc = view.doc.borrow();
let text = doc.text().slice(..); let text = doc.text().slice(..);
let last_line = view.last_line(); let last_line = view.last_line(doc);
let range = { let range = {
// calculate viewport byte ranges // calculate viewport byte ranges
@ -211,16 +211,14 @@ impl EditorView {
// let selection_style = Style::default().bg(Color::Rgb(94, 0, 128)); // let selection_style = Style::default().bg(Color::Rgb(94, 0, 128));
let selection_style = Style::default().bg(Color::Rgb(84, 0, 153)); let selection_style = Style::default().bg(Color::Rgb(84, 0, 153));
for selection in view for selection in doc
.doc
.borrow()
.selection() .selection()
.iter() .iter()
.filter(|range| range.overlaps(&screen)) .filter(|range| range.overlaps(&screen))
{ {
// TODO: render also if only one of the ranges is in viewport // TODO: render also if only one of the ranges is in viewport
let mut start = view.screen_coords_at_pos(text, selection.anchor); let mut start = view.screen_coords_at_pos(doc, text, selection.anchor);
let mut end = view.screen_coords_at_pos(text, selection.head); let mut end = view.screen_coords_at_pos(doc, text, selection.head);
// cursor // cursor
if let Some(end) = end { if let Some(end) = end {
@ -292,7 +290,6 @@ impl EditorView {
let info: Style = theme.get("info"); let info: Style = theme.get("info");
let hint: Style = theme.get("hint"); let hint: Style = theme.get("hint");
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) = doc.diagnostics.iter().find(|d| d.line == line) { if let Some(diagnostic) = doc.diagnostics.iter().find(|d| d.line == line) {
@ -431,11 +428,12 @@ impl Component for EditorView {
match event { match event {
Event::Resize(width, height) => { Event::Resize(width, height) => {
// HAXX: offset the render area height by 1 to account for prompt/commandline // HAXX: offset the render area height by 1 to account for prompt/commandline
cx.editor.tree.resize(Rect::new(0, 0, width, height - 1)); cx.editor.resize(Rect::new(0, 0, width, height - 1));
EventResult::Consumed(None) EventResult::Consumed(None)
} }
Event::Key(event) => { Event::Key(event) => {
let mode = cx.editor.view().doc.borrow().mode(); let id = cx.editor.view().doc;
let mode = cx.editor.document(id).unwrap().mode();
let mut cxt = commands::Context { let mut cxt = commands::Context {
editor: &mut cx.editor, editor: &mut cx.editor,
@ -491,7 +489,7 @@ impl Component for EditorView {
// appease borrowck // appease borrowck
let callback = cxt.callback.take(); let callback = cxt.callback.take();
drop(cxt); drop(cxt);
cx.editor.view_mut().ensure_cursor_in_view(); cx.editor.ensure_cursor_in_view(cx.editor.tree.focus);
EventResult::Consumed(callback) EventResult::Consumed(callback)
} }
@ -501,7 +499,8 @@ impl Component for EditorView {
fn render(&self, mut area: Rect, surface: &mut Surface, cx: &mut Context) { fn render(&self, mut area: Rect, surface: &mut Surface, cx: &mut Context) {
for (view, is_focused) in cx.editor.tree.views() { for (view, is_focused) in cx.editor.tree.views() {
self.render_view(view, view.area, surface, &cx.editor.theme, is_focused); let doc = cx.editor.document(view.doc).unwrap();
self.render_view(doc, view, view.area, surface, &cx.editor.theme, is_focused);
} }
} }

@ -40,7 +40,8 @@ pub fn regex_prompt(
match event { match event {
PromptEvent::Abort => { PromptEvent::Abort => {
// TODO: also revert text // TODO: also revert text
let doc = &mut editor.view().doc.borrow_mut(); let id = editor.view().doc;
let doc = &mut editor.documents[id];
doc.set_selection(snapshot.clone()); doc.set_selection(snapshot.clone());
} }
PromptEvent::Validate => { PromptEvent::Validate => {
@ -54,18 +55,17 @@ 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 mut doc = view.doc.borrow_mut(); let id = editor.view().doc;
let doc = &mut editor.documents[id];
// 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(&mut doc, regex); fun(doc, regex);
drop(doc); editor.ensure_cursor_in_view(editor.view().id);
view.ensure_cursor_in_view();
} }
Err(_err) => (), // TODO: mark command line as error Err(_err) => (), // TODO: mark command line as error
} }
@ -101,40 +101,39 @@ pub fn file_picker(root: &str) -> Picker<PathBuf> {
path.strip_prefix("./").unwrap().to_str().unwrap().into() path.strip_prefix("./").unwrap().to_str().unwrap().into()
}, },
move |editor: &mut Editor, path: &PathBuf| { move |editor: &mut Editor, path: &PathBuf| {
editor.open(path.into()); let document_id = editor.open(path.into()).expect("editor.open failed");
}, },
) )
} }
use helix_view::View; use helix_view::View;
pub fn buffer_picker(views: &[View], current: usize) -> Picker<(Option<PathBuf>, usize)> { pub fn buffer_picker(buffers: &[Document], current: usize) -> Picker<(Option<PathBuf>, usize)> {
unimplemented!(); use helix_view::Editor;
// use helix_view::Editor; Picker::new(
// Picker::new( buffers
// views .iter()
// .iter() .enumerate()
// .enumerate() .map(|(i, doc)| (doc.relative_path().map(Path::to_path_buf), i))
// .map(|(i, view)| (view.doc.relative_path().map(Path::to_path_buf), i)) .collect(),
// .collect(), move |(path, index): &(Option<PathBuf>, usize)| {
// move |(path, index): &(Option<PathBuf>, usize)| { // format_fn
// // format_fn match path {
// match path { Some(path) => {
// Some(path) => { if *index == current {
// if *index == current { format!("{} (*)", path.to_str().unwrap()).into()
// format!("{} (*)", path.to_str().unwrap()).into() } else {
// } else { path.to_str().unwrap().into()
// path.to_str().unwrap().into() }
// } }
// } None => "[NEW]".into(),
// None => "[NEW]".into(), }
// } },
// }, |editor: &mut Editor, &(_, index): &(Option<PathBuf>, usize)| {
// |editor: &mut Editor, &(_, index): &(Option<PathBuf>, usize)| { // if index < editor.views.len() {
// if index < editor.views.len() { // editor.focus = index;
// editor.focus = index; // }
// } },
// }, )
// )
} }
pub mod completers { pub mod completers {

@ -8,6 +8,8 @@ use helix_core::{
ChangeSet, Diagnostic, History, Rope, Selection, State, Syntax, Transaction, ChangeSet, Diagnostic, History, Rope, Selection, State, Syntax, Transaction,
}; };
use crate::DocumentId;
#[derive(Copy, Clone, PartialEq, Eq, Hash)] #[derive(Copy, Clone, PartialEq, Eq, Hash)]
pub enum Mode { pub enum Mode {
Normal, Normal,
@ -18,6 +20,7 @@ pub enum Mode {
pub struct Document { pub struct Document {
// rope + selection // rope + selection
pub(crate) id: DocumentId,
state: State, state: State,
path: Option<PathBuf>, path: Option<PathBuf>,
@ -66,6 +69,7 @@ impl Document {
let old_state = None; let old_state = None;
Self { Self {
id: DocumentId::default(),
path: None, path: None,
state: State::new(text), state: State::new(text),
mode: Mode::Normal, mode: Mode::Normal,

@ -1,7 +1,7 @@
use crate::{theme::Theme, tree::Tree, Document, DocumentId, View}; use crate::{theme::Theme, tree::Tree, Document, DocumentId, View};
use tui::layout::Rect;
use std::path::PathBuf; use std::path::PathBuf;
use std::{cell::RefCell, rc::Rc};
use slotmap::{DefaultKey as Key, SlotMap}; use slotmap::{DefaultKey as Key, SlotMap};
@ -9,7 +9,7 @@ use anyhow::Error;
pub struct Editor { pub struct Editor {
pub tree: Tree, pub tree: Tree,
pub documents: SlotMap<DocumentId, Rc<RefCell<Document>>>, pub documents: SlotMap<DocumentId, 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,
@ -34,18 +34,25 @@ impl Editor {
} }
} }
pub fn open(&mut self, path: PathBuf) -> Result<(), Error> { fn _refresh(&mut self) {
// TODO: issues with doc already being borrowed if called from inside goto() for (view, _) in self.tree.views_mut() {
let doc = &self.documents[view.doc];
view.ensure_cursor_in_view(doc)
}
}
let existing_view = self pub fn open(&mut self, path: PathBuf) -> Result<DocumentId, Error> {
.tree let existing_view = self.documents().find(|doc| doc.path() == Some(&path));
.views()
.find(|(view, _)| view.doc.borrow().path() == Some(&path));
if let Some((view, _)) = existing_view { // TODO:
self.tree.focus = view.id; // if view with doc, focus it
return Ok(()); // else open new split
}
// if let Some((view, _)) = existing_view {
// let id = view.doc.id;
// self.tree.focus = view.id;
// return Ok(id);
// }
let mut doc = Document::load(path, self.theme.scopes())?; let mut doc = Document::load(path, self.theme.scopes())?;
@ -73,13 +80,14 @@ impl Editor {
.unwrap(); .unwrap();
} }
let doc = Rc::new(RefCell::new(doc)); let id = self.documents.insert(doc);
// TODO: store id as doc.id self.documents[id].id = id;
let id = self.documents.insert(doc.clone());
let view = View::new(doc)?; let view = View::new(id)?;
self.tree.insert(view); self.tree.insert(view);
Ok(()) self._refresh();
Ok(id)
} }
pub fn close(&mut self, id: Key) { pub fn close(&mut self, id: Key) {
@ -88,7 +96,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.borrow(); let doc = &self.documents[view.doc];
let language_server = doc let language_server = doc
.language .language
@ -99,14 +107,14 @@ impl Editor {
smol::block_on(language_server.text_document_did_close(doc.identifier())).unwrap(); smol::block_on(language_server.text_document_did_close(doc.identifier())).unwrap();
} }
drop(doc); // to stop borrowing self.tree
// self.documents.remove(view.doc); // self.documents.remove(view.doc);
self.tree.remove(id); self.tree.remove(id);
self._refresh();
} }
pub fn resize(&mut self) { pub fn resize(&mut self, area: Rect) {
self.tree.focus_next(); self.tree.resize(area);
self._refresh();
} }
pub fn focus_next(&mut self) { pub fn focus_next(&mut self) {
@ -125,12 +133,26 @@ impl Editor {
self.tree.get_mut(self.tree.focus) self.tree.get_mut(self.tree.focus)
} }
pub fn ensure_cursor_in_view(&mut self, id: Key) {
let view = self.tree.get_mut(id);
let doc = &self.documents[view.doc];
view.ensure_cursor_in_view(doc)
}
pub fn document(&self, id: DocumentId) -> Option<&Document> {
self.documents.get(id)
}
pub fn documents(&self) -> impl Iterator<Item = &Document> {
self.documents.iter().map(|(_id, doc)| doc)
}
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 doc = view.doc.borrow(); let doc = &self.documents[view.doc];
let cursor = doc.selection().cursor(); let cursor = doc.selection().cursor();
if let Some(mut pos) = view.screen_coords_at_pos(doc.text().slice(..), cursor) { if let Some(mut pos) = view.screen_coords_at_pos(doc, 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);

@ -164,7 +164,18 @@ impl Tree {
self.recalculate() self.recalculate()
} }
pub fn views(&mut self) -> impl Iterator<Item = (&mut View, bool)> { pub fn views(&self) -> impl Iterator<Item = (&View, bool)> {
let focus = self.focus;
self.nodes.iter().filter_map(move |(key, node)| match node {
Node {
content: Content::View(view),
..
} => Some((view.as_ref(), focus == key)),
_ => None,
})
}
pub fn views_mut(&mut self) -> impl Iterator<Item = (&mut View, bool)> {
let focus = self.focus; let focus = self.focus;
self.nodes self.nodes
.iter_mut() .iter_mut()
@ -231,7 +242,6 @@ impl Tree {
Content::View(view) => { Content::View(view) => {
// debug!!("setting view area {:?}", area); // debug!!("setting view area {:?}", area);
view.area = area; view.area = area;
view.ensure_cursor_in_view();
} // TODO: call f() } // TODO: call f()
Content::Container(container) => { Content::Container(container) => {
// debug!!("setting container area {:?}", area); // debug!!("setting container area {:?}", area);

@ -1,7 +1,6 @@
use anyhow::Error; use anyhow::Error;
use std::borrow::Cow; use std::borrow::Cow;
use std::{cell::RefCell, rc::Rc};
use crate::{Document, DocumentId}; use crate::{Document, DocumentId};
use helix_core::{ use helix_core::{
@ -15,13 +14,13 @@ pub const PADDING: usize = 5;
pub struct View { pub struct View {
pub id: Key, pub id: Key,
pub doc: Rc<RefCell<Document>>, pub doc: DocumentId,
pub first_line: usize, pub first_line: usize,
pub area: Rect, pub area: Rect,
} }
impl View { impl View {
pub fn new(doc: Rc<RefCell<Document>>) -> Result<Self, Error> { pub fn new(doc: DocumentId) -> Result<Self, Error> {
let view = Self { let view = Self {
id: Key::default(), id: Key::default(),
doc, doc,
@ -32,8 +31,7 @@ impl View {
Ok(view) Ok(view)
} }
pub fn ensure_cursor_in_view(&mut self) { pub fn ensure_cursor_in_view(&mut self, doc: &Document) {
let doc = self.doc.borrow();
let cursor = doc.selection().cursor(); let cursor = doc.selection().cursor();
let line = doc.text().char_to_line(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);
@ -51,8 +49,7 @@ 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, doc: &Document) -> 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,
@ -63,10 +60,15 @@ impl View {
/// Translates a document position to an absolute position in the terminal. /// Translates a document position to an absolute position in the terminal.
/// Returns a (line, col) position if the position is visible on screen. /// Returns a (line, col) position if the position is visible on screen.
// TODO: Could return width as well for the character width at cursor. // TODO: Could return width as well for the character width at cursor.
pub fn screen_coords_at_pos(&self, text: RopeSlice, pos: usize) -> Option<Position> { pub fn screen_coords_at_pos(
&self,
doc: &Document,
text: RopeSlice,
pos: usize,
) -> Option<Position> {
let line = text.char_to_line(pos); let line = text.char_to_line(pos);
if line < self.first_line || line > self.last_line() { if line < self.first_line || line > self.last_line(doc) {
// Line is not visible on screen // Line is not visible on screen
return None; return None;
} }
@ -74,7 +76,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.borrow().tab_width(); let tab_width = doc.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