@@ -1,17 +1,13 @@
1use clap::ArgMatches as Args;
1use clap::ArgMatches as Args;
2−use helix_core::{indent::TAB_WIDTH, syntax::HighlightEvent, Position, Range, State};
2+
6− keymap::{self, Keymaps},
8− Document, Editor, Theme, View,
3+use helix_view::{document::Mode, Document, Editor, Theme, View};
5+use crate::compositor::Compositor;
11use log::{debug, info};
8use log::{debug, info};
15 io::{self, stdout, Stdout, Write},
11 io::{self, stdout, Stdout, Write},
16 path::PathBuf,
12 path::PathBuf,
17 time::Duration,
13 time::Duration,
@@ -22,366 +18,44 @@ use smol::prelude::*;
22use anyhow::Error;
18use anyhow::Error;
24use crossterm::{
20use crossterm::{
26− event::{read, Event, EventStream, KeyCode, KeyEvent},
21+ event::{Event, EventStream},
27− execute, queue,
22+ execute, terminal,
28− terminal::{self, disable_raw_mode, enable_raw_mode},
32− backend::CrosstermBackend,
25+use tui::{backend::CrosstermBackend, layout::Rect};
33− buffer::Buffer as Surface,
35− style::{Color, Modifier, Style},
38−const OFFSET: u16 = 7; // 1 diagnostic + 5 linenr + 1 gutter
40−type Terminal = tui::Terminal<CrosstermBackend<std::io::Stdout>>;
42−const BASE_WIDTH: u16 = 30;
27+type Terminal = crate::terminal::Terminal<CrosstermBackend<std::io::Stdout>>;
44−pub struct Application<'a> {
29+pub struct Application {
30+ compositor: Compositor,
45 editor: Editor,
31 editor: Editor,
46− prompt: Option<Prompt>,
47− terminal: Renderer,
32+ terminal: Terminal,
50− executor: &'a smol::Executor<'a>,
34+ executor: &'static smol::Executor<'static>,
51 language_server: helix_lsp::Client,
35 language_server: helix_lsp::Client,
54−struct Renderer {
38+impl Application {
63− pub fn new() -> Result<Self, Error> {
39+ pub fn new(mut args: Args, executor: &'static smol::Executor<'static>) -> Result<Self, Error> {
64 let backend = CrosstermBackend::new(stdout());
40 let backend = CrosstermBackend::new(stdout());
65 let mut terminal = Terminal::new(backend)?;
41 let mut terminal = Terminal::new(backend)?;
66− let size = terminal::size().unwrap();
67− let text_color: Style = Style::default().fg(Color::Rgb(219, 191, 239)); // lilac
69− let area = Rect::new(0, 0, size.0, size.1);
74− surface: Surface::empty(area),
75− cache: Surface::empty(area),
80− pub fn resize(&mut self, width: u16, height: u16) {
81− self.size = (width, height);
82− let area = Rect::new(0, 0, width, height);
83− self.surface = Surface::empty(area);
84− self.cache = Surface::empty(area);
87− pub fn render_view(&mut self, view: &mut View, viewport: Rect, theme: &Theme) {
88− self.render_buffer(view, viewport, theme);
89− self.render_statusline(view, theme);
92− // TODO: ideally not &mut View but highlights require it because of cursor cache
93− pub fn render_buffer(&mut self, view: &mut View, viewport: Rect, theme: &Theme) {
94− let area = Rect::new(0, 0, self.size.0, self.size.1);
95− self.surface.reset(); // reset is faster than allocating new empty surface
97− // clear with background color
98− self.surface.set_style(area, theme.get("ui.background"));
100− // TODO: inefficient, should feed chunks.iter() to tree_sitter.parse_with(|offset, pos|)
101− let source_code = view.doc.text().to_string();
103− let last_line = view.last_line();
106− // calculate viewport byte ranges
107− let start = view.doc.text().line_to_byte(view.first_line);
108− let end = view.doc.text().line_to_byte(last_line)
109− + view.doc.text().line(last_line).len_bytes();
114− // TODO: range doesn't actually restrict source, just highlight range
115− // TODO: cache highlight results
116− // TODO: only recalculate when state.doc is actually modified
117− let highlights: Vec<_> = match view.doc.syntax.as_mut() {
120− .highlight_iter(source_code.as_bytes(), Some(range), None, |_| None)
122− .collect() // TODO: we collect here to avoid double borrow, fix later
124− None => vec![Ok(HighlightEvent::Source {
129− let mut spans = Vec::new();
130− let mut visual_x = 0;
131− let mut line = 0u16;
132− let visible_selections: Vec<Range> = view
138− // TODO: limit selection to one in viewport
139− // .filter(|range| !range.is_empty()) // && range.overlaps(&Range::new(start, end + 1))
143− 'outer: for event in highlights {
144− match event.unwrap() {
145− HighlightEvent::HighlightStart(span) => {
148− HighlightEvent::HighlightEnd => {
151− HighlightEvent::Source { start, end } => {
152− // TODO: filter out spans out of viewport for now..
154− let start = view.doc.text().byte_to_char(start);
155− let end = view.doc.text().byte_to_char(end); // <-- index 744, len 743
157− let text = view.doc.text().slice(start..end);
159− use helix_core::graphemes::{grapheme_width, RopeGraphemes};
161− let style = match spans.first() {
162− Some(span) => theme.get(theme.scopes()[span.0].as_str()),
163− None => Style::default().fg(Color::Rgb(164, 160, 232)), // lavender
166− // TODO: we could render the text to a surface, then cache that, that
167− // way if only the selection/cursor changes we can copy from cache
168− // and paint the new cursor.
170− let mut char_index = start;
172− // iterate over range char by char
173− for grapheme in RopeGraphemes::new(&text) {
174− // TODO: track current char_index
176− if grapheme == "\n" {
180− // TODO: with proper iter this shouldn't be necessary
181− if line >= viewport.height {
184− } else if grapheme == "\t" {
185− visual_x += (TAB_WIDTH as u16);
187− // Cow will prevent allocations if span contained in a single slice
188− // which should really be the majority case
189− let grapheme = Cow::from(grapheme);
190− let width = grapheme_width(&grapheme) as u16;
192− // TODO: this should really happen as an after pass
193− let style = if visible_selections
195− .any(|range| range.contains(char_index))
198− style.clone().bg(Color::Rgb(128, 47, 0))
203− let style = if visible_selections
205− .any(|range| range.head == char_index)
207− style.clone().bg(Color::Rgb(255, 255, 255))
212− // ugh, improve with a traverse method
213− // or interleave highlight spans with selection and diagnostic spans
214− let style = if view.doc.diagnostics.iter().any(|diagnostic| {
215− diagnostic.range.0 <= char_index && diagnostic.range.1 > char_index
217− style.clone().add_modifier(Modifier::UNDERLINED)
222− // TODO: paint cursor heads except primary
225− .set_string(OFFSET + visual_x, line, grapheme, style);
236− let style: Style = theme.get("ui.linenr");
237− let warning: Style = theme.get("warning");
238− let last_line = view.last_line();
239− for (i, line) in (view.first_line..last_line).enumerate() {
240− if view.doc.diagnostics.iter().any(|d| d.line == line) {
241− self.surface.set_stringn(0, i as u16, "●", 1, warning);
245− .set_stringn(1, i as u16, format!("{:>5}", line + 1), 5, style);
249− pub fn render_statusline(&mut self, view: &View, theme: &Theme) {
250− let mode = match view.doc.mode() {
251− Mode::Insert => "INS",
252− Mode::Normal => "NOR",
253− Mode::Goto => "GOTO",
256− self.surface.set_style(
257− Rect::new(0, self.size.1 - 2, self.size.0, 1),
258− theme.get("ui.statusline"),
261− .set_string(1, self.size.1 - 2, mode, self.text_color);
263− self.surface.set_string(
266− format!("{}", view.doc.diagnostics.len()),
271− pub fn render_prompt(&mut self, view: &View, prompt: &Prompt, theme: &Theme) {
273− if !prompt.completion.is_empty() {
274− // TODO: find out better way of clearing individual lines of the screen
277− let max_col = self.size.0 / BASE_WIDTH;
278− let col_height = ((prompt.completion.len() as u16 + max_col - 1) / max_col);
280− for i in (3..col_height + 3) {
281− self.surface.set_string(
283− self.size.1 - i as u16,
284− " ".repeat(self.size.0 as usize),
288− self.surface.set_style(
289− Rect::new(0, self.size.1 - col_height - 2, self.size.0, col_height),
290− theme.get("ui.statusline"),
292− for (i, command) in prompt.completion.iter().enumerate() {
293− let color = if prompt.completion_selection_index.is_some()
294− && i == prompt.completion_selection_index.unwrap()
296− Style::default().bg(Color::Rgb(104, 060, 232))
300− self.surface.set_stringn(
301− 1 + col * BASE_WIDTH,
302− self.size.1 - col_height - 2 + row,
304− BASE_WIDTH as usize - 1,
308− if row > col_height - 1 {
317− // render buffer text
319− .set_string(1, self.size.1 - 1, &prompt.prompt, self.text_color);
321− .set_string(2, self.size.1 - 1, &prompt.line, self.text_color);
324− pub fn draw(&mut self) {
325− use tui::backend::Backend;
326− // TODO: theres probably a better place for this
329− .draw(self.cache.diff(&self.surface).into_iter());
331− std::mem::swap(&mut self.surface, &mut self.cache);
334− pub fn render_cursor(&mut self, view: &View, prompt: Option<&Prompt>, viewport: Rect) {
335− let mut stdout = stdout();
336− match view.doc.mode() {
337− Mode::Insert => write!(stdout, "\x1B[6 q"),
338− mode => write!(stdout, "\x1B[2 q"),
340− let pos = if let Some(prompt) = prompt {
341− Position::new(self.size.0 as usize, 2 + prompt.cursor)
343− if let Some(path) = view.doc.path() {
344− self.surface.set_string(
347− path.to_string_lossy(),
352− let cursor = view.doc.state.selection().cursor();
355− .screen_coords_at_pos(&view.doc.text().slice(..), cursor)
356− .expect("Cursor is out of bounds.");
357− pos.col += viewport.x as usize;
358− pos.row += viewport.y as usize;
362− execute!(stdout, cursor::MoveTo(pos.col as u16, pos.row as u16));
366−impl<'a> Application<'a> {
367− pub fn new(mut args: Args, executor: &'a smol::Executor<'a>) -> Result<Self, Error> {
368− let terminal = Renderer::new()?;
369 let mut editor = Editor::new();
42 let mut editor = Editor::new();
43+ let size = terminal.size()?;
371 if let Some(file) = args.values_of_t::<PathBuf>("files").unwrap().pop() {
45 if let Some(file) = args.values_of_t::<PathBuf>("files").unwrap().pop() {
372− editor.open(file, terminal.size)?;
46+ editor.open(file, (size.width, size.height))?;
49+ let mut compositor = Compositor::new();
50+ compositor.push(Box::new(ui::EditorView::new()));
375 let language_server = helix_lsp::Client::start(&executor, "rust-analyzer", &[]);
52 let language_server = helix_lsp::Client::start(&executor, "rust-analyzer", &[]);
377 let mut app = Self {
54 let mut app = Self {
379 terminal,
56 terminal,
380− // TODO; move to state
57+ compositor,
384− keymap: keymap::default(),
385 executor,
59 executor,
386 language_server,
60 language_server,
@@ -390,27 +64,18 @@ impl<'a> Application<'a> {
392 fn render(&mut self) {
66 fn render(&mut self) {
393− let viewport = Rect::new(OFFSET, 0, self.terminal.size.0, self.terminal.size.1 - 2); // - 2 for statusline and prompt
67+ let executor = &self.executor;
394−
68+ let editor = &mut self.editor;
395− // SAFETY: we cheat around the view_mut() borrow because it doesn't allow us to also borrow
69+ let compositor = &self.compositor;
396− // theme. Theme is immutable mutating view won't disrupt theme_ref.
397− let theme_ref = unsafe { &*(&self.editor.theme as *const Theme) };
398− if let Some(view) = self.editor.view_mut() {
399− self.terminal.render_view(view, viewport, theme_ref);
400− if let Some(prompt) = &self.prompt {
401− if prompt.should_close {
404− self.terminal.render_prompt(view, prompt, theme_ref);
71+ let mut cx = crate::compositor::Context { editor, executor };
409− self.terminal.draw();
72+ let area = self.terminal.size().unwrap();
411− // TODO: drop unwrap
74+ compositor.render(area, self.terminal.current_buffer_mut(), &mut cx);
75+ let pos = compositor.cursor_position(area, &mut cx);
412− self.terminal
77+ self.terminal.draw();
413− .render_cursor(self.editor.view().unwrap(), self.prompt.as_ref(), viewport);
78+ self.terminal.set_cursor(pos.col as u16, pos.row as u16);
416 pub async fn event_loop(&mut self) {
81 pub async fn event_loop(&mut self) {
@@ -418,10 +83,11 @@ impl<'a> Application<'a> {
419 // initialize lsp
84 // initialize lsp
420 self.language_server.initialize().await.unwrap();
85 self.language_server.initialize().await.unwrap();
421− self.language_server
87+ // self.language_server
422− .text_document_did_open(&self.editor.view().unwrap().doc)
88+ // .text_document_did_open(&cx.editor.view().unwrap().doc)
424− .unwrap();
90+ // .unwrap();
426 self.render();
92 self.render();
@@ -433,7 +99,7 @@ impl<'a> Application<'a> {
433 use futures_util::{select, FutureExt};
99 use futures_util::{select, FutureExt};
434 select! {
100 select! {
435 event = reader.next().fuse() => {
101 event = reader.next().fuse() => {
436− self.handle_terminal_events(event).await
102+ self.handle_terminal_events(event)
438 call = self.language_server.incoming.next().fuse() => {
104 call = self.language_server.incoming.next().fuse() => {
439 self.handle_language_server_message(call).await
105 self.handle_language_server_message(call).await
@@ -442,151 +108,28 @@ impl<'a> Application<'a> {
445− pub async fn handle_terminal_events(
447− event: Option<Result<Event, crossterm::ErrorKind>>,
111+ pub fn handle_terminal_events(&mut self, event: Option<Result<Event, crossterm::ErrorKind>>) {
448− ) {
112+ let mut cx = crate::compositor::Context {
113+ editor: &mut self.editor,
114+ executor: &self.executor,
449 // Handle key events
116 // Handle key events
450− match event {
117+ let should_redraw = match event {
451 Some(Ok(Event::Resize(width, height))) => {
118 Some(Ok(Event::Resize(width, height))) => {
452− self.terminal.resize(width, height);
119+ self.terminal.resize(Rect::new(0, 0, width, height));
454− // TODO: simplistic ensure cursor in view for now
455− // TODO: loop over views
456− if let Some(view) = self.editor.view_mut() {
457− view.size = self.terminal.size;
458− view.ensure_cursor_in_view()
461− self.render();
121+ self.compositor
462− }
122+ .handle_event(Event::Resize(width, height), &mut cx)
463− Some(Ok(Event::Key(event))) => {
464− // if there's a prompt, it takes priority
465− if let Some(prompt) = &mut self.prompt {
469− .handle_input(event, &mut self.editor);
472− } else if let Some(view) = self.editor.view_mut() {
473− let keys = vec![event];
474− // TODO: sequences (`gg`)
475− // TODO: handle count other than 1
476− match view.doc.mode() {
478− if let Some(command) = self.keymap[&Mode::Insert].get(&keys) {
479− let mut cx = helix_view::commands::Context {
481− executor: self.executor,
486− } else if let KeyEvent {
487− code: KeyCode::Char(c),
491− let mut cx = helix_view::commands::Context {
493− executor: self.executor,
496− commands::insert::insert_char(&mut cx, c);
498− view.ensure_cursor_in_view();
502− code: KeyCode::Char(':'),
504− }] = keys.as_slice()
506− let prompt = Prompt::new(
509− // TODO: i need this duplicate list right now to avoid borrow checker issues
510− let command_list = vec![
512− String::from("aaa"),
513− String::from("bbb"),
514− String::from("ccc"),
515− String::from("ddd"),
516− String::from("eee"),
517− String::from("averylongcommandaverylongcommandaverylongcommandaverylongcommandaverylongcommand"),
519− String::from("aaa"),
520− String::from("bbb"),
521− String::from("ccc"),
522− String::from("ddd"),
523− String::from("eee"),
525− String::from("aaa"),
526− String::from("bbb"),
527− String::from("ccc"),
528− String::from("ddd"),
529− String::from("eee"),
531− String::from("aaa"),
532− String::from("bbb"),
533− String::from("ccc"),
534− String::from("ddd"),
535− String::from("eee"),
537− String::from("aaa"),
538− String::from("bbb"),
539− String::from("ccc"),
540− String::from("ddd"),
541− String::from("eee"),
545− .filter(|command| command.contains(_input))
548− |editor: &mut Editor, input: &str| match input {
549− "q" => editor.should_close = true,
554− self.prompt = Some(prompt);
556− // HAXX: special casing for command mode
557− } else if let Some(command) = self.keymap[&Mode::Normal].get(&keys) {
558− let mut cx = helix_view::commands::Context {
560− executor: self.executor,
565− // TODO: simplistic ensure cursor in view for now
566− view.ensure_cursor_in_view();
570− if let Some(command) = self.keymap[&mode].get(&keys) {
571− let mut cx = helix_view::commands::Context {
573− executor: self.executor,
578− // TODO: simplistic ensure cursor in view for now
579− view.ensure_cursor_in_view();
586− Some(Ok(Event::Mouse(_))) => (), // unhandled
124+ Some(Ok(event)) => self.compositor.handle_event(event, &mut cx),
587 Some(Err(x)) => panic!(x),
125 Some(Err(x)) => panic!(x),
588 None => panic!(),
126 None => panic!(),
131+ // calling render twice here fixes it for some reason
592 pub async fn handle_language_server_message(&mut self, call: Option<helix_lsp::Call>) {
135 pub async fn handle_language_server_message(&mut self, call: Option<helix_lsp::Call>) {
@@ -599,11 +142,13 @@ impl<'a> Application<'a> {
599 match notification {
142 match notification {
600 Notification::PublishDiagnostics(params) => {
143 Notification::PublishDiagnostics(params) => {
601 let path = Some(params.uri.to_file_path().unwrap());
144 let path = Some(params.uri.to_file_path().unwrap());
602− let view = self
145+ let view: Option<&mut helix_view::View> = None;
603− .editor
148+ // .editor
604− .views
149+ // .views
605− .iter_mut()
150+ // .iter_mut()
606− .find(|view| view.doc.path == path);
151+ // .find(|view| view.doc.path == path);
608 if let Some(view) = view {
153 if let Some(view) = view {
609 let doc = view.doc.text().slice(..);
154 let doc = view.doc.text().slice(..);
@@ -653,7 +198,7 @@ impl<'a> Application<'a> {
655 pub async fn run(&mut self) -> Result<(), Error> {
200 pub async fn run(&mut self) -> Result<(), Error> {
656− enable_raw_mode()?;
201+ terminal::enable_raw_mode()?;
658 let mut stdout = stdout();
203 let mut stdout = stdout();
@@ -663,7 +208,7 @@ impl<'a> Application<'a> {
663 let hook = std::panic::take_hook();
208 let hook = std::panic::take_hook();
664 std::panic::set_hook(Box::new(move |info| {
209 std::panic::set_hook(Box::new(move |info| {
665 execute!(std::io::stdout(), terminal::LeaveAlternateScreen);
210 execute!(std::io::stdout(), terminal::LeaveAlternateScreen);
666− disable_raw_mode();
211+ terminal::disable_raw_mode();
667 hook(info);
212 hook(info);
@@ -674,7 +219,7 @@ impl<'a> Application<'a> {
675 execute!(stdout, terminal::LeaveAlternateScreen)?;
220 execute!(stdout, terminal::LeaveAlternateScreen)?;
677− disable_raw_mode()?;
222+ terminal::disable_raw_mode()?;