1use clap::ArgMatches as Args;
2use helix_core::{state::coords_at_pos, state::Mode, syntax::HighlightEvent, Range, State};
3use helix_view::{commands, keymap, View};
7 io::{self, stdout, Write},
19 event::{self, read, Event, EventStream, KeyCode, KeyEvent},
21 style::{Color, Print, SetForegroundColor},
22 terminal::{self, disable_raw_mode, enable_raw_mode},
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();
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 {
51 surface: Surface::empty(area),
52 cache: Surface::empty(area),
53 // TODO; move to state
56 if let Some(file) = args.values_of_t::<PathBuf>("files").unwrap().pop() {
63 pub fn open(&mut self, path: PathBuf) -> Result<(), Error> {
64 self.view = Some(View::open(path, self.size)?);
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 {
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
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,
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();
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() {
109 .highlight_iter(source_code.as_bytes(), Some(range), None, |_| None)
111 .collect() // TODO: we collect here to avoid double borrow, fix later
113 None => vec![Ok(HighlightEvent::Source {
119 let mut spans = Vec::new();
121 let mut visual_x = 0;
124 let visible_selections: Vec<Range> = view
129 // TODO: limit selection to one in viewport
130 .filter(|range| !range.is_empty()) // && range.overlaps(&Range::new(start, end + 1))
134 'outer: for event in highlights {
135 match event.unwrap() {
136 HighlightEvent::HighlightStart(span) => {
139 HighlightEvent::HighlightEnd => {
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
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" {
171 // TODO: with proper iter this shouldn't be necessary
172 if line >= viewport.height {
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
183 .any(|range| range.contains(char_index))
186 style.clone().bg(Color::Rgb(128, 47, 0))
191 // TODO: paint cursor heads except primary
193 self.surface.set_string(
202 // if grapheme == "\t"
210 let style: Style = view.theme.get("ui.linenr");
211 for (i, line) in (view.first_line..(last_line as u16)).enumerate() {
213 .set_stringn(0, line, format!("{:>5}", i + 1), 5, style);
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(
234 // (x2 - x1 + 1) as u16,
235 // (y2 - y1 + 1) as u16,
237 // self.surface.set_style(area, select);
239 // // TODO: don't highlight next char in append mode
243 let mode = match view.state.mode() {
244 Mode::Insert => "INS",
245 Mode::Normal => "NOR",
247 self.surface.set_style(
248 Rect::new(0, self.size.1 - 1, self.size.0, 1),
249 view.theme.get("ui.statusline"),
251 // TODO: unfocused one with different color
252 let text_color = Style::default().fg(Color::Rgb(219, 191, 239)); // lilac
254 .set_string(1, self.size.1 - 1, mode, text_color);
255 if let Some(path) = view.state.path() {
257 .set_string(6, self.size.1 - 1, path.to_string_lossy(), text_color);
262 .draw(self.cache.diff(&self.surface).into_iter());
264 std::mem::swap(&mut self.surface, &mut self.cache);
267 match view.state.mode() {
268 Mode::Insert => write!(stdout, "\x1B[6 q"),
269 Mode::Normal => write!(stdout, "\x1B[2 q"),
273 let pos = view.state.selection().cursor();
274 let coords = coords_at_pos(&view.state.doc().slice(..), pos);
278 coords.col as u16 + viewport.x,
279 coords.row as u16 - view.first_line + viewport.y,
287 pub async fn event_loop(&mut self) {
288 let mut reader = EventStream::new();
289 let keymap = keymap::default();
295 let mut event = reader.next().await;
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()
311 Some(Ok(Event::Key(KeyEvent {
312 code: KeyCode::Char('q'),
317 Some(Ok(Event::Key(event))) => {
318 if let Some(view) = &mut self.view {
319 match view.state.mode() {
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
326 } else if let KeyEvent {
327 code: KeyCode::Char(c),
331 commands::insert_char(view, c);
333 view.ensure_cursor_in_view();
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
344 // TODO: simplistic ensure cursor in view for now
345 view.ensure_cursor_in_view();
356 Some(Err(x)) => panic!(x),
362 pub async fn run(&mut self) -> Result<(), Error> {
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);
377 self.event_loop().await;
379 // reset cursor shape
380 write!(stdout, "\x1B[2 q");
382 execute!(stdout, terminal::LeaveAlternateScreen)?;
390// TODO: language configs:
391// tabSize, fileExtension etc, mapping to tree sitter parser
393// map tree sitter highlights to color values
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)))
404// for span in spans {
405// start(scope) => scopes.push(scope)
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
412// if state.selection.ranges().any(|range| range.contains(char_index)) {
413// if exactly on cursor {
415// if on primary cursor? {
417// modify style temporarily
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()
427// end => scopes.pop()
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list