From 67bf4250caf14d3a632abdbfa367c04b318d782c Mon Sep 17 00:00:00 2001 From: Ivan Tham Date: Thu, 25 Nov 2021 10:07:23 +0800 Subject: Optimize space for DocumentId with NonZeroUsize (#1097) Now Option uses one byte rather than two--- helix-view/src/editor.rs | 29 +++++++++++++++-------------- helix-view/src/lib.rs | 14 ++++++++++++-- 2 files changed, 27 insertions(+), 16 deletions(-) (limited to 'helix-view/src') diff --git a/helix-view/src/editor.rs b/helix-view/src/editor.rs index 1ce33760..725dc1b8 100644 --- a/helix-view/src/editor.rs +++ b/helix-view/src/editor.rs @@ -11,6 +11,7 @@ use futures_util::future; use std::{ collections::BTreeMap, io::stdin, + num::NonZeroUsize, path::{Path, PathBuf}, pin::Pin, sync::Arc, @@ -154,7 +155,7 @@ impl std::fmt::Debug for Motion { #[derive(Debug)] pub struct Editor { pub tree: Tree, - pub next_document_id: usize, + pub next_document_id: DocumentId, pub documents: BTreeMap, pub count: Option, pub selected_register: Option, @@ -198,7 +199,8 @@ impl Editor { Self { tree: Tree::new(area), - next_document_id: 0, + // Safety: 1 is non-zero + next_document_id: DocumentId::default(), documents: BTreeMap::new(), count: None, selected_register: None, @@ -367,16 +369,19 @@ impl Editor { self._refresh(); } - fn new_document(&mut self, mut document: Document) -> DocumentId { - let id = DocumentId(self.next_document_id); - self.next_document_id += 1; - document.id = id; - self.documents.insert(id, document); + /// Generate an id for a new document and register it. + fn new_document(&mut self, mut doc: Document) -> DocumentId { + let id = self.next_document_id; + // Safety: adding 1 from 1 is fine, probably impossible to reach usize max + self.next_document_id = + DocumentId(unsafe { NonZeroUsize::new_unchecked(self.next_document_id.0.get() + 1) }); + doc.id = id; + self.documents.insert(id, doc); id } - fn new_file_from_document(&mut self, action: Action, document: Document) -> DocumentId { - let id = self.new_document(document); + fn new_file_from_document(&mut self, action: Action, doc: Document) -> DocumentId { + let id = self.new_document(doc); self.switch(id, action); id } @@ -435,11 +440,7 @@ impl Editor { doc.set_language_server(Some(language_server)); } - let id = DocumentId(self.next_document_id); - self.next_document_id += 1; - doc.id = id; - self.documents.insert(id, doc); - id + self.new_document(doc) }; self.switch(id, action); diff --git a/helix-view/src/lib.rs b/helix-view/src/lib.rs index 3e779356..4d19ee2e 100644 --- a/helix-view/src/lib.rs +++ b/helix-view/src/lib.rs @@ -12,8 +12,18 @@ pub mod theme; pub mod tree; pub mod view; -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Debug)] -pub struct DocumentId(usize); +use std::num::NonZeroUsize; + +// uses NonZeroUsize so Option use a byte rather than two +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] +pub struct DocumentId(NonZeroUsize); + +impl Default for DocumentId { + fn default() -> DocumentId { + // Safety: 1 is non-zero + DocumentId(unsafe { NonZeroUsize::new_unchecked(1) }) + } +} slotmap::new_key_type! { pub struct ViewId; -- cgit v1.2.3-70-g09d2 From 6e62c3de47ff14df394c1c17fec103c134aa045c Mon Sep 17 00:00:00 2001 From: Blaž Hrastnik Date: Fri, 26 Nov 2021 18:26:22 +0900 Subject: Simplify some code in editor.rs --- helix-term/src/application.rs | 2 +- helix-view/src/editor.rs | 54 ++++++++++++++++++------------------------- 2 files changed, 24 insertions(+), 32 deletions(-) (limited to 'helix-view/src') diff --git a/helix-term/src/application.rs b/helix-term/src/application.rs index a795a56e..90330751 100644 --- a/helix-term/src/application.rs +++ b/helix-term/src/application.rs @@ -265,7 +265,7 @@ impl Application { use crate::commands::{insert::idle_completion, Context}; use helix_view::document::Mode; - if doc_mut!(self.editor).mode != Mode::Insert || !self.config.editor.auto_completion { + if doc!(self.editor).mode != Mode::Insert || !self.config.editor.auto_completion { return; } let editor_view = self diff --git a/helix-view/src/editor.rs b/helix-view/src/editor.rs index 725dc1b8..b93d8126 100644 --- a/helix-view/src/editor.rs +++ b/helix-view/src/editor.rs @@ -19,7 +19,7 @@ use std::{ use tokio::time::{sleep, Duration, Instant, Sleep}; -use anyhow::Error; +use anyhow::{bail, Context, Error}; pub use helix_core::diagnostic::Severity; pub use helix_core::register::Registers; @@ -188,8 +188,8 @@ pub enum Action { impl Editor { pub fn new( mut area: Rect, - themes: Arc, - config_loader: Arc, + theme_loader: Arc, + syn_loader: Arc, config: Config, ) -> Self { let language_servers = helix_lsp::Registry::new(); @@ -199,15 +199,14 @@ impl Editor { Self { tree: Tree::new(area), - // Safety: 1 is non-zero next_document_id: DocumentId::default(), documents: BTreeMap::new(), count: None, selected_register: None, - theme: themes.default(), + theme: theme_loader.default(), language_servers, - syn_loader: config_loader, - theme_loader: themes, + syn_loader, + theme_loader, registers: Registers::default(), clipboard_provider: get_clipboard_provider(), status_msg: None, @@ -264,7 +263,6 @@ impl Editor { } pub fn set_theme_from_name(&mut self, theme: &str) -> anyhow::Result<()> { - use anyhow::Context; let theme = self .theme_loader .load(theme.as_ref()) @@ -343,23 +341,22 @@ impl Editor { } Action::Load => { let view_id = view!(self).id; - if let Some(doc) = self.document_mut(id) { - if doc.selections().is_empty() { - doc.selections.insert(view_id, Selection::point(0)); - } + let doc = self.documents.get_mut(&id).unwrap(); + if doc.selections().is_empty() { + doc.selections.insert(view_id, Selection::point(0)); } return; } - Action::HorizontalSplit => { - let view = View::new(id); - let view_id = self.tree.split(view, Layout::Horizontal); - // initialize selection for view - let doc = self.documents.get_mut(&id).unwrap(); - doc.selections.insert(view_id, Selection::point(0)); - } - Action::VerticalSplit => { + Action::HorizontalSplit | Action::VerticalSplit => { let view = View::new(id); - let view_id = self.tree.split(view, Layout::Vertical); + let view_id = self.tree.split( + view, + match action { + Action::HorizontalSplit => Layout::Horizontal, + Action::VerticalSplit => Layout::Vertical, + _ => unreachable!(), + }, + ); // initialize selection for view let doc = self.documents.get_mut(&id).unwrap(); doc.selections.insert(view_id, Selection::point(0)); @@ -397,11 +394,7 @@ impl Editor { pub fn open(&mut self, path: PathBuf, action: Action) -> Result { let path = helix_core::path::get_canonicalized_path(&path)?; - - let id = self - .documents() - .find(|doc| doc.path() == Some(&path)) - .map(|doc| doc.id); + let id = self.document_by_path(&path).map(|doc| doc.id); let id = if let Some(id) = id { id @@ -463,11 +456,11 @@ impl Editor { pub fn close_document(&mut self, doc_id: DocumentId, force: bool) -> anyhow::Result<()> { let doc = match self.documents.get(&doc_id) { Some(doc) => doc, - None => anyhow::bail!("document does not exist"), + None => bail!("document does not exist"), }; if !force && doc.is_modified() { - anyhow::bail!( + bail!( "buffer {:?} is modified", doc.relative_path() .map(|path| path.to_string_lossy().to_string()) @@ -500,7 +493,7 @@ impl Editor { // If the document we removed was visible in all views, we will have no more views. We don't // want to close the editor just for a simple buffer close, so we need to create a new view // containing either an existing document, or a brand new document. - if self.tree.views().peekable().peek().is_none() { + if self.tree.views().next().is_none() { let doc_id = self .documents .iter() @@ -585,8 +578,7 @@ impl Editor { } pub fn cursor(&self) -> (Option, CursorKind) { - let view = view!(self); - let doc = &self.documents[&view.doc]; + let (view, doc) = current_ref!(self); let cursor = doc .selection(view.id) .primary() -- cgit v1.2.3-70-g09d2 From 103b5125e4bc51965d98a38cdbeed2151ed816fa Mon Sep 17 00:00:00 2001 From: RustyStriker Date: Sun, 28 Nov 2021 03:19:54 +0200 Subject: Detect filetype on :write (#1141) fixes #1136 * removed a log::info * removed temp.rs * cargo clippy no longer complains * new get_lang_server function * get_lang_server is now launch_language_server * launch_lang_server will now close the previous one * better code readability * remove resfresh_ls(and a wrong comment)--- helix-term/src/commands.rs | 7 +++- helix-view/src/editor.rs | 79 ++++++++++++++++++++++++++++------------------ 2 files changed, 54 insertions(+), 32 deletions(-) (limited to 'helix-view/src') diff --git a/helix-term/src/commands.rs b/helix-term/src/commands.rs index ff8d7a4f..8e57ef30 100644 --- a/helix-term/src/commands.rs +++ b/helix-term/src/commands.rs @@ -1907,7 +1907,7 @@ mod cmd { let jobs = &mut cx.jobs; let (_, doc) = current!(cx.editor); - if let Some(path) = path { + if let Some(ref path) = path { doc.set_path(Some(path.as_ref())) .context("invalid filepath")?; } @@ -1927,6 +1927,11 @@ mod cmd { }); let future = doc.format_and_save(fmt); cx.jobs.add(Job::new(future).wait_before_exiting()); + + if path.is_some() { + let id = doc.id(); + let _ = cx.editor.refresh_language_server(id); + } Ok(()) } diff --git a/helix-view/src/editor.rs b/helix-view/src/editor.rs index b93d8126..77cea783 100644 --- a/helix-view/src/editor.rs +++ b/helix-view/src/editor.rs @@ -271,6 +271,53 @@ impl Editor { Ok(()) } + /// Refreshes the language server for a given document + pub fn refresh_language_server(&mut self, doc_id: DocumentId) -> Option<()> { + let doc = self.documents.get_mut(&doc_id)?; + doc.detect_language(Some(&self.theme), &self.syn_loader); + Self::launch_language_server(&mut self.language_servers, doc) + } + + /// Launch a language server for a given document + fn launch_language_server(ls: &mut helix_lsp::Registry, doc: &mut Document) -> Option<()> { + // try to find a language server based on the language name + let language_server = doc.language.as_ref().and_then(|language| { + ls.get(language) + .map_err(|e| { + log::error!( + "Failed to initialize the LSP for `{}` {{ {} }}", + language.scope(), + e + ) + }) + .ok() + }); + if let Some(language_server) = language_server { + // only spawn a new lang server if the servers aren't the same + if Some(language_server.id()) != doc.language_server().map(|server| server.id()) { + if let Some(language_server) = doc.language_server() { + tokio::spawn(language_server.text_document_did_close(doc.identifier())); + } + let language_id = doc + .language() + .and_then(|s| s.split('.').last()) // source.rust + .map(ToOwned::to_owned) + .unwrap_or_default(); + + // TODO: this now races with on_init code if the init happens too quickly + tokio::spawn(language_server.text_document_did_open( + doc.url().unwrap(), + doc.version(), + doc.text(), + language_id, + )); + + doc.set_language_server(Some(language_server)); + } + } + Some(()) + } + fn _refresh(&mut self) { for (view, _) in self.tree.views_mut() { let doc = &self.documents[&view.doc]; @@ -401,37 +448,7 @@ impl Editor { } else { let mut doc = Document::open(&path, None, Some(&self.theme), Some(&self.syn_loader))?; - // try to find a language server based on the language name - let language_server = doc.language.as_ref().and_then(|language| { - self.language_servers - .get(language) - .map_err(|e| { - log::error!( - "Failed to initialize the LSP for `{}` {{ {} }}", - language.scope(), - e - ) - }) - .ok() - }); - - if let Some(language_server) = language_server { - let language_id = doc - .language() - .and_then(|s| s.split('.').last()) // source.rust - .map(ToOwned::to_owned) - .unwrap_or_default(); - - // TODO: this now races with on_init code if the init happens too quickly - tokio::spawn(language_server.text_document_did_open( - doc.url().unwrap(), - doc.version(), - doc.text(), - language_id, - )); - - doc.set_language_server(Some(language_server)); - } + let _ = Self::launch_language_server(&mut self.language_servers, &mut doc); self.new_document(doc) }; -- cgit v1.2.3-70-g09d2 From 30171416cb5b801086da69566a82462fca16ea14 Mon Sep 17 00:00:00 2001 From: Blaž Hrastnik Date: Fri, 24 Sep 2021 10:29:41 +0900 Subject: Gutter functions --- helix-core/src/diagnostic.rs | 4 +- helix-term/src/ui/editor.rs | 150 ++++++++++++++++++++++++++----------------- helix-view/src/editor.rs | 2 +- 3 files changed, 94 insertions(+), 62 deletions(-) (limited to 'helix-view/src') diff --git a/helix-core/src/diagnostic.rs b/helix-core/src/diagnostic.rs index ad1ba16a..4fcf51c9 100644 --- a/helix-core/src/diagnostic.rs +++ b/helix-core/src/diagnostic.rs @@ -1,7 +1,7 @@ //! LSP diagnostic utility types. /// Describes the severity level of a [`Diagnostic`]. -#[derive(Debug, Eq, PartialEq)] +#[derive(Debug, Clone, Copy, Eq, PartialEq)] pub enum Severity { Error, Warning, @@ -17,7 +17,7 @@ pub struct Range { } /// Corresponds to [`lsp_types::Diagnostic`](https://docs.rs/lsp-types/0.91.0/lsp_types/struct.Diagnostic.html) -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct Diagnostic { pub range: Range, pub line: usize, diff --git a/helix-term/src/ui/editor.rs b/helix-term/src/ui/editor.rs index 27d33d22..8c4ea9cc 100644 --- a/helix-term/src/ui/editor.rs +++ b/helix-term/src/ui/editor.rs @@ -17,7 +17,7 @@ use helix_core::{ }; use helix_view::{ document::{Mode, SCRATCH_BUFFER_NAME}, - editor::LineNumber, + editor::{Config, LineNumber}, graphics::{CursorKind, Modifier, Rect, Style}, info::Info, input::KeyEvent, @@ -412,22 +412,6 @@ impl EditorView { let text = doc.text().slice(..); let last_line = view.last_line(doc); - let linenr = theme.get("ui.linenr"); - let linenr_select: Style = theme.try_get("ui.linenr.selected").unwrap_or(linenr); - - let warning = theme.get("warning"); - let error = theme.get("error"); - let info = theme.get("info"); - let hint = theme.get("hint"); - - // Whether to draw the line number for the last line of the - // document or not. We only draw it if it's not an empty line. - let draw_last = text.line_to_byte(last_line) < text.len_bytes(); - - let current_line = doc - .text() - .char_to_line(doc.selection(view.id).primary().cursor(text)); - // it's used inside an iterator so the collect isn't needless: // https://github.com/rust-lang/rust-clippy/issues/6164 #[allow(clippy::needless_collect)] @@ -437,51 +421,99 @@ impl EditorView { .map(|range| range.cursor_line(text)) .collect(); - for (i, line) in (view.offset.row..(last_line + 1)).enumerate() { - use helix_core::diagnostic::Severity; - if let Some(diagnostic) = doc.diagnostics().iter().find(|d| d.line == line) { - surface.set_stringn( - viewport.x, - viewport.y + i as u16, - "●", - 1, - match diagnostic.severity { - Some(Severity::Error) => error, - Some(Severity::Warning) | None => warning, - Some(Severity::Info) => info, - Some(Severity::Hint) => hint, - }, - ); - } + fn diagnostic( + doc: &Document, + _view: &View, + theme: &Theme, + _config: &Config, + _is_focused: bool, + _width: usize, + ) -> GutterFn { + let warning = theme.get("warning"); + let error = theme.get("error"); + let info = theme.get("info"); + let hint = theme.get("hint"); + let diagnostics = doc.diagnostics().to_vec(); // TODO + + Box::new(move |line: usize, _selected: bool| { + use helix_core::diagnostic::Severity; + if let Some(diagnostic) = diagnostics.iter().find(|d| d.line == line) { + return Some(( + "●".to_string(), + match diagnostic.severity { + Some(Severity::Error) => error, + Some(Severity::Warning) | None => warning, + Some(Severity::Info) => info, + Some(Severity::Hint) => hint, + }, + )); + } + None + }) + } - let selected = cursors.contains(&line); + fn line_number( + doc: &Document, + view: &View, + theme: &Theme, + config: &Config, + is_focused: bool, + width: usize, + ) -> GutterFn { + let text = doc.text().slice(..); + let last_line = view.last_line(doc); + // Whether to draw the line number for the last line of the + // document or not. We only draw it if it's not an empty line. + let draw_last = text.line_to_byte(last_line) < text.len_bytes(); - let text = if line == last_line && !draw_last { - " ~".into() - } else { - let line = match config.line_number { - LineNumber::Absolute => line + 1, - LineNumber::Relative => { - if current_line == line { - line + 1 - } else { - abs_diff(current_line, line) - } - } - }; - format!("{:>5}", line) - }; - surface.set_stringn( - viewport.x + 1, - viewport.y + i as u16, - text, - 5, - if selected && is_focused { - linenr_select + let linenr = theme.get("ui.linenr"); + let linenr_select: Style = theme.try_get("ui.linenr.selected").unwrap_or(linenr); + + let current_line = doc + .text() + .char_to_line(doc.selection(view.id).primary().cursor(text)); + + let config = config.line_number; + + Box::new(move |line: usize, selected: bool| { + if line == last_line && !draw_last { + Some((format!("{:>1$}", '~', width), linenr)) } else { - linenr - }, - ); + let line = match config { + LineNumber::Absolute => line + 1, + LineNumber::Relative => { + if current_line == line { + line + 1 + } else { + abs_diff(current_line, line) + } + } + }; + let style = if selected && is_focused { + linenr_select + } else { + linenr + }; + Some((format!("{:>1$}", line, width), style)) + } + }) + } + + type GutterFn = Box Option<(String, Style)>>; + type Gutter = fn(&Document, &View, &Theme, &Config, bool, usize) -> GutterFn; + let gutters: &[(Gutter, usize)] = &[(diagnostic, 1), (line_number, 5)]; + + let mut offset = 0; + for (constructor, width) in gutters { + let gutter = constructor(doc, view, theme, config, is_focused, *width); + for (i, line) in (view.offset.row..(last_line + 1)).enumerate() { + let selected = cursors.contains(&line); + + if let Some((text, style)) = gutter(line, selected) { + surface.set_stringn(viewport.x + offset, viewport.y + i as u16, text, 5, style); + } + } + offset += *width as u16; } } diff --git a/helix-view/src/editor.rs b/helix-view/src/editor.rs index 77cea783..d5913a51 100644 --- a/helix-view/src/editor.rs +++ b/helix-view/src/editor.rs @@ -106,7 +106,7 @@ pub struct Config { pub file_picker: FilePickerConfig, } -#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +#[derive(Debug, Copy, Clone, PartialEq, Eq, Deserialize)] #[serde(rename_all = "kebab-case")] pub enum LineNumber { /// Show absolute line number -- cgit v1.2.3-70-g09d2 From 225e8ccf31ac554ae0977b4359c50edb2670594e Mon Sep 17 00:00:00 2001 From: Blaž Hrastnik Date: Tue, 23 Nov 2021 12:56:46 +0900 Subject: Extract gutters into helix-view --- helix-term/src/ui/editor.rs | 97 +-------------------------------------------- helix-view/src/gutter.rs | 95 ++++++++++++++++++++++++++++++++++++++++++++ helix-view/src/lib.rs | 1 + helix-view/src/view.rs | 24 +++++++++-- 4 files changed, 117 insertions(+), 100 deletions(-) create mode 100644 helix-view/src/gutter.rs (limited to 'helix-view/src') diff --git a/helix-term/src/ui/editor.rs b/helix-term/src/ui/editor.rs index 82fb8fbf..83be816f 100644 --- a/helix-term/src/ui/editor.rs +++ b/helix-term/src/ui/editor.rs @@ -17,7 +17,6 @@ use helix_core::{ }; use helix_view::{ document::{Mode, SCRATCH_BUFFER_NAME}, - editor::{Config, LineNumber}, graphics::{CursorKind, Modifier, Rect, Style}, info::Info, input::KeyEvent, @@ -421,97 +420,12 @@ impl EditorView { .map(|range| range.cursor_line(text)) .collect(); - use std::fmt::Write; - - fn diagnostic<'doc>( - doc: &'doc Document, - _view: &View, - theme: &Theme, - _config: &Config, - _is_focused: bool, - _width: usize, - ) -> GutterFn<'doc> { - let warning = theme.get("warning"); - let error = theme.get("error"); - let info = theme.get("info"); - let hint = theme.get("hint"); - let diagnostics = doc.diagnostics(); - - Box::new(move |line: usize, _selected: bool, out: &mut String| { - use helix_core::diagnostic::Severity; - if let Some(diagnostic) = diagnostics.iter().find(|d| d.line == line) { - write!(out, "●").unwrap(); - return Some(match diagnostic.severity { - Some(Severity::Error) => error, - Some(Severity::Warning) | None => warning, - Some(Severity::Info) => info, - Some(Severity::Hint) => hint, - }); - } - None - }) - } - - fn line_number<'doc>( - doc: &'doc Document, - view: &View, - theme: &Theme, - config: &Config, - is_focused: bool, - width: usize, - ) -> GutterFn<'doc> { - let text = doc.text().slice(..); - let last_line = view.last_line(doc); - // Whether to draw the line number for the last line of the - // document or not. We only draw it if it's not an empty line. - let draw_last = text.line_to_byte(last_line) < text.len_bytes(); - - let linenr = theme.get("ui.linenr"); - let linenr_select: Style = theme.try_get("ui.linenr.selected").unwrap_or(linenr); - - let current_line = doc - .text() - .char_to_line(doc.selection(view.id).primary().cursor(text)); - - let config = config.line_number; - - Box::new(move |line: usize, selected: bool, out: &mut String| { - if line == last_line && !draw_last { - write!(out, "{:>1$}", '~', width).unwrap(); - Some(linenr) - } else { - let line = match config { - LineNumber::Absolute => line + 1, - LineNumber::Relative => { - if current_line == line { - line + 1 - } else { - abs_diff(current_line, line) - } - } - }; - let style = if selected && is_focused { - linenr_select - } else { - linenr - }; - write!(out, "{:>1$}", line, width).unwrap(); - Some(style) - } - }) - } - - type GutterFn<'doc> = Box Option