on d9d59cd help sign in
helix/helix-term/src/editor.rs
428 lines 17 kB history raw
1use clap::ArgMatches as Args;
2use helix_core::{state::coords_at_pos, state::Mode, syntax::HighlightEvent, Range, State};
3use helix_view::{commands, keymap, View};
5use std::{
6 borrow::Cow,
7 io::{self, stdout, Write},
8 path::PathBuf,
9 time::Duration,
10};
12use smol::prelude::*;
14use anyhow::Error;
16use crossterm::{
17 cursor,
18 cursor::position,
19 event::{self, read, Event, EventStream, KeyCode, KeyEvent},
20 execute, queue,
21 style::{Color, Print, SetForegroundColor},
22 terminal::{self, disable_raw_mode, enable_raw_mode},
23};
25use tui::{backend::CrosstermBackend, buffer::Buffer as Surface, layout::Rect, style::Style};
27type Terminal = tui::Terminal<CrosstermBackend<std::io::Stdout>>;
29static EX: smol::Executor = smol::Executor::new();
31pub struct Editor {
32 terminal: Terminal,
33 view: Option<View>,
34 size: (u16, u16),
35 surface: Surface,
36 cache: Surface,
39impl Editor {
40 pub fn new(mut args: Args) -> Result<Self, Error> {
41 let backend = CrosstermBackend::new(stdout());
43 let mut terminal = Terminal::new(backend)?;
44 let size = terminal::size().unwrap();
45 let area = Rect::new(0, 0, size.0, size.1);
47 let mut editor = Editor {
48 terminal,
49 view: None,
50 size,
51 surface: Surface::empty(area),
52 cache: Surface::empty(area),
53 // TODO; move to state
54 };
56 if let Some(file) = args.values_of_t::<PathBuf>("files").unwrap().pop() {
57 editor.open(file)?;
58 }
60 Ok(editor)
61 }
63 pub fn open(&mut self, path: PathBuf) -> Result<(), Error> {
64 self.view = Some(View::open(path, self.size)?);
65 Ok(())
66 }
68 fn render(&mut self) {
69 use tui::backend::Backend;
70 use tui::style::Color;
71 // TODO: ideally not mut but highlights require it because of cursor cache
72 match &mut self.view {
73 Some(view) => {
74 let area = Rect::new(0, 0, self.size.0, self.size.1);
75 let mut stdout = stdout();
76 self.surface.reset(); // reset is faster than allocating new empty surface
78 // clear with background color
79 self.surface
80 .set_style(area, view.theme.get("ui.background"));
82 let offset = 5 + 1; // 5 linenr + 1 gutter
83 let viewport = Rect::new(offset, 0, self.size.0, self.size.1 - 1); // - 1 for statusline
85 // TODO: inefficient, should feed chunks.iter() to tree_sitter.parse_with(|offset, pos|)
86 let source_code = view.state.doc().to_string();
88 let last_line = std::cmp::min(
89 (view.first_line + viewport.height - 1) as usize,
90 view.state.doc().len_lines() - 1,
91 );
93 let range = {
94 // calculate viewport byte ranges
95 let start = view.state.doc().line_to_byte(view.first_line.into());
96 let end = view.state.doc().line_to_byte(last_line)
97 + view.state.doc().line(last_line).len_bytes();
99 start..end
100 };
102 // TODO: range doesn't actually restrict source, just highlight range
104 // TODO: cache highlight results
105 // TODO: only recalculate when state.doc is actually modified
106 let highlights: Vec<_> = match view.state.syntax.as_mut() {
107 Some(syntax) => {
108 syntax
109 .highlight_iter(source_code.as_bytes(), Some(range), None, |_| None)
110 .unwrap()
111 .collect() // TODO: we collect here to avoid double borrow, fix later
112 }
113 None => vec![Ok(HighlightEvent::Source {
114 start: range.start,
115 end: range.end,
116 })],
117 };
119 let mut spans = Vec::new();
121 let mut visual_x = 0;
122 let mut line = 0u16;
124 let visible_selections: Vec<Range> = view
125 .state
126 .selection()
127 .ranges()
128 .iter()
129 // TODO: limit selection to one in viewport
130 .filter(|range| !range.is_empty()) // && range.overlaps(&Range::new(start, end + 1))
131 .copied()
132 .collect();
134 'outer: for event in highlights {
135 match event.unwrap() {
136 HighlightEvent::HighlightStart(span) => {
137 spans.push(span);
138 }
139 HighlightEvent::HighlightEnd => {
140 spans.pop();
141 }
142 HighlightEvent::Source { start, end } => {
143 // TODO: filter out spans out of viewport for now..
145 let start = view.state.doc().byte_to_char(start);
146 let end = view.state.doc().byte_to_char(end); // <-- index 744, len 743
148 let text = view.state.doc().slice(start..end);
150 use helix_core::graphemes::{grapheme_width, RopeGraphemes};
152 let style = match spans.first() {
153 Some(span) => view.theme.get(view.theme.scopes()[span.0].as_str()),
154 None => Style::default().fg(Color::Rgb(164, 160, 232)), // lavender
155 };
157 // TODO: we could render the text to a surface, then cache that, that
158 // way if only the selection/cursor changes we can copy from cache
159 // and paint the new cursor.
161 let mut char_index = start;
163 // iterate over range char by char
164 for grapheme in RopeGraphemes::new(&text) {
165 // TODO: track current char_index
167 if grapheme == "\n" {
168 visual_x = 0;
169 line += 1;
171 // TODO: with proper iter this shouldn't be necessary
172 if line >= viewport.height {
173 break 'outer;
174 }
175 } else {
176 // Cow will prevent allocations if span contained in a single slice
177 // which should really be the majority case
178 let grapheme = Cow::from(grapheme);
179 let width = grapheme_width(&grapheme) as u16;
181 let style = if visible_selections
182 .iter()
183 .any(|range| range.contains(char_index))
184 {
185 // cedar
186 style.clone().bg(Color::Rgb(128, 47, 0))
187 } else {
188 style
189 };
191 // TODO: paint cursor heads except primary
193 self.surface.set_string(
194 offset + visual_x,
195 line,
196 grapheme,
197 style,
198 );
200 visual_x += width;
201 }
202 // if grapheme == "\t"
204 char_index += 1;
205 }
206 }
207 }
208 }
210 let style: Style = view.theme.get("ui.linenr");
211 for (i, line) in (view.first_line..(last_line as u16)).enumerate() {
212 self.surface
213 .set_stringn(0, line, format!("{:>5}", i + 1), 5, style);
214 // lavender
215 }
217 // let lines = state
218 // .doc
219 // .lines_at(self.first_line as usize)
220 // .take(self.size.1 as usize)
221 // .map(|x| x.as_str().unwrap());
223 // // iterate over selections and render them
224 // let select = Style::default().bg(tui::style::Color::LightBlue);
225 // let text = state.doc.slice(..);
226 // for range in state.selection.ranges() {
227 // // get terminal coords for x,y for each range pos
228 // // TODO: this won't work with multiline
229 // let (y1, x1) = coords_at_pos(&text, range.from());
230 // let (y2, x2) = coords_at_pos(&text, range.to());
231 // let area = Rect::new(
232 // (x1 + 2) as u16,
233 // y1 as u16,
234 // (x2 - x1 + 1) as u16,
235 // (y2 - y1 + 1) as u16,
236 // );
237 // self.surface.set_style(area, select);
239 // // TODO: don't highlight next char in append mode
240 // }
242 // statusline
243 let mode = match view.state.mode() {
244 Mode::Insert => "INS",
245 Mode::Normal => "NOR",
246 };
247 self.surface.set_style(
248 Rect::new(0, self.size.1 - 1, self.size.0, 1),
249 view.theme.get("ui.statusline"),
250 );
251 // TODO: unfocused one with different color
252 let text_color = Style::default().fg(Color::Rgb(219, 191, 239)); // lilac
253 self.surface
254 .set_string(1, self.size.1 - 1, mode, text_color);
255 if let Some(path) = view.state.path() {
256 self.surface
257 .set_string(6, self.size.1 - 1, path.to_string_lossy(), text_color);
258 }
260 self.terminal
261 .backend_mut()
262 .draw(self.cache.diff(&self.surface).into_iter());
263 // swap the buffer
264 std::mem::swap(&mut self.surface, &mut self.cache);
266 // set cursor shape
267 match view.state.mode() {
268 Mode::Insert => write!(stdout, "\x1B[6 q"),
269 Mode::Normal => write!(stdout, "\x1B[2 q"),
270 };
272 // render the cursor
273 let pos = view.state.selection().cursor();
274 let coords = coords_at_pos(&view.state.doc().slice(..), pos);
275 execute!(
276 stdout,
277 cursor::MoveTo(
278 coords.col as u16 + viewport.x,
279 coords.row as u16 - view.first_line + viewport.y,
280 )
281 );
282 }
283 None => (),
284 }
285 }
287 pub async fn event_loop(&mut self) {
288 let mut reader = EventStream::new();
289 let keymap = keymap::default();
291 self.render();
293 loop {
294 // Handle key events
295 let mut event = reader.next().await;
296 match event {
297 Some(Ok(Event::Resize(width, height))) => {
298 self.size = (width, height);
299 let area = Rect::new(0, 0, width, height);
300 self.surface = Surface::empty(area);
301 self.cache = Surface::empty(area);
303 // TODO: simplistic ensure cursor in view for now
304 if let Some(view) = &mut self.view {
305 view.size = self.size;
306 view.ensure_cursor_in_view()
307 };
309 self.render();
310 }
311 Some(Ok(Event::Key(KeyEvent {
312 code: KeyCode::Char('q'),
313 ..
314 }))) => {
315 break;
316 }
317 Some(Ok(Event::Key(event))) => {
318 if let Some(view) = &mut self.view {
319 match view.state.mode() {
320 Mode::Insert => {
321 // TODO: handle modes and sequences (`gg`)
322 let keys = vec![event];
323 if let Some(command) = keymap[&Mode::Insert].get(&keys) {
324 // TODO: handle count other than 1
325 command(view, 1);
326 } else if let KeyEvent {
327 code: KeyCode::Char(c),
328 ..
329 } = event
330 {
331 commands::insert_char(view, c);
332 }
333 view.ensure_cursor_in_view();
335 self.render();
336 }
337 Mode::Normal => {
338 // TODO: handle modes and sequences (`gg`)
339 let keys = vec![event];
340 if let Some(command) = keymap[&Mode::Normal].get(&keys) {
341 // TODO: handle count other than 1
342 command(view, 1);
344 // TODO: simplistic ensure cursor in view for now
345 view.ensure_cursor_in_view();
347 self.render();
348 }
349 }
350 }
351 }
352 }
353 Some(Ok(_)) => {
354 // unhandled event
355 }
356 Some(Err(x)) => panic!(x),
357 None => break,
358 }
359 }
360 }
362 pub async fn run(&mut self) -> Result<(), Error> {
363 enable_raw_mode()?;
365 let mut stdout = stdout();
367 execute!(stdout, terminal::EnterAlternateScreen)?;
369 // Exit the alternate screen and disable raw mode before panicking
370 let hook = std::panic::take_hook();
371 std::panic::set_hook(Box::new(move |info| {
372 execute!(std::io::stdout(), terminal::LeaveAlternateScreen);
373 disable_raw_mode();
374 hook(info);
375 }));
377 self.event_loop().await;
379 // reset cursor shape
380 write!(stdout, "\x1B[2 q");
382 execute!(stdout, terminal::LeaveAlternateScreen)?;
384 disable_raw_mode()?;
386 Ok(())
387 }
390// TODO: language configs:
391// tabSize, fileExtension etc, mapping to tree sitter parser
392// themes:
393// map tree sitter highlights to color values
394//
395// TODO: expand highlight thing so we're able to render only viewport range
396// TODO: async: maybe pre-cache scopes as empty so we render all graphemes initially as regular
397////text until calc finishes
398// TODO: scope matching: biggest union match? [string] & [html, string], [string, html] & [ string, html]
399// can do this by sorting our theme matches based on array len (longest first) then stopping at the
400// first rule that matches (rule.all(|scope| scopes.contains(scope)))
401//
402// let visual_x = 0;
403// let line = ?;
404// for span in spans {
405// start(scope) => scopes.push(scope)
406// span =>
407// let text = rope.slice(span.start..span.end);
408// let style = calculate_style(scopes);
409// for each grapheme in text.graphemes() {
410// // if newline += lines, continue
411//
412// if state.selection.ranges().any(|range| range.contains(char_index)) {
413// if exactly on cursor {
414// }
415// if on primary cursor? {
416// }
417// modify style temporarily
418// }
419//
420// // if in bounds
421//
422// // if tab, draw tab width
423// // draw(visual_x, line, grapheme, style)
424// // increment visual_x by grapheme_width(grapheme)
425// // increment char_index by grapheme.len_chars()
426// }
427// end => scopes.pop()
428// }