on master help sign in
wip: importing to github
commit613d06dfb0e5fe2fc05b94e5c651dfd10af23310 authorBlaž Hrastnik <blaz@mxxn.io> dateMon 1 Jun 2020, 17:42 (6 years ago) parent6905ff0
11 files changed+375−7
Cargo.lock+44 helix-core/Cargo.toml+2 helix-core/src/graphemes.rs+213 helix-core/src/lib.rs+1 helix-core/src/selection.rs+2−2 helix-core/src/state.rs+81−5 helix-term/Cargo.toml+1 helix-term/src/component.rs+18 helix-term/src/editor.rs+7 helix-term/src/line.rs+5 helix-term/src/main.rs+1
Cargo.lock+44
@@ -59,6 +59,12 @@ version = "1.2.1"
5959source = "registry+https://github.com/rust-lang/crates.io-index"
6060checksum = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693"
6161
62+[[package]]
63+name = "cassowary"
64+version = "0.3.0"
65+source = "registry+https://github.com/rust-lang/crates.io-index"
66+checksum = "df8670b8c7b9dae1793364eafadf7239c40d669904660c5960d74cfd80b46a53"
67+
6268[[package]]
6369name = "cc"
6470version = "1.0.54"
@@ -176,6 +182,12 @@ dependencies = [
176182 "winapi",
177183]
178184
185+[[package]]
186+name = "either"
187+version = "1.5.3"
188+source = "registry+https://github.com/rust-lang/crates.io-index"
189+checksum = "bb1f6b1ce1c140482ea30ddd3335fc0024ac7ee112895426e0a629a6c20adfe3"
190+
179191[[package]]
180192name = "futf"
181193version = "0.1.4"
@@ -298,6 +310,8 @@ dependencies = [
298310 "ropey",
299311 "smallvec",
300312 "tendril",
313+ "unicode-segmentation",
314+ "unicode-width",
301315]
302316
303317[[package]]
@@ -312,6 +326,7 @@ dependencies = [
312326 "num_cpus",
313327 "piper",
314328 "smol",
329+ "tui",
315330]
316331
317332[[package]]
@@ -323,6 +338,15 @@ dependencies = [
323338 "libc",
324339]
325340
341+[[package]]
342+name = "itertools"
343+version = "0.9.0"
344+source = "registry+https://github.com/rust-lang/crates.io-index"
345+checksum = "284f18f85651fe11e8a991b2adb42cb078325c996ed026d994719efcfca1d54b"
346+dependencies = [
347+ "either",
348+]
349+
326350[[package]]
327351name = "lazy_static"
328352version = "1.4.0"
@@ -651,12 +675,32 @@ dependencies = [
651675 "utf-8",
652676]
653677
678+[[package]]
679+name = "tui"
680+version = "0.9.5"
681+source = "registry+https://github.com/rust-lang/crates.io-index"
682+checksum = "9533d39bef0ae8f510e8a99d78702e68d1bbf0b98a78ec9740509d287010ae1e"
683+dependencies = [
684+ "bitflags",
685+ "cassowary",
686+ "either",
687+ "itertools",
688+ "unicode-segmentation",
689+ "unicode-width",
690+]
691+
654692[[package]]
655693name = "unicode-segmentation"
656694version = "1.6.0"
657695source = "registry+https://github.com/rust-lang/crates.io-index"
658696checksum = "e83e153d1053cbb5a118eeff7fd5be06ed99153f00dbcd8ae310c5fb2b22edc0"
659697
698+[[package]]
699+name = "unicode-width"
700+version = "0.1.7"
701+source = "registry+https://github.com/rust-lang/crates.io-index"
702+checksum = "caaa9d531767d1ff2150b9332433f32a24622147e5ebb1f26409d5da67afd479"
703+
660704[[package]]
661705name = "unicode-xid"
662706version = "0.2.0"
helix-core/Cargo.toml+2
@@ -12,4 +12,6 @@ ropey = { git = "https://github.com/cessen/ropey" }
1212anyhow = "1.0.31"
1313smallvec = "1.4.0"
1414tendril = { git = "https://github.com/servo/tendril" }
15+unicode-segmentation = "1.6.0"
16+unicode-width = "0.1.7"
1517# slab = "0.4.2"
helix-core/src/graphemes.rsnew file+213
@@ -0,0 +1,213 @@
1+// Based on https://github.com/cessen/led/blob/c4fa72405f510b7fd16052f90a598c429b3104a6/src/graphemes.rs
2+use ropey::{iter::Chunks, str_utils::byte_to_char_idx, RopeSlice};
3+use unicode_segmentation::{GraphemeCursor, GraphemeIncomplete};
4+use unicode_width::UnicodeWidthStr;
5+
6+pub fn grapheme_width(g: &str) -> usize {
7+ if g.as_bytes()[0] <= 127 {
8+ // Fast-path ascii.
9+ // Point 1: theoretically, ascii control characters should have zero
10+ // width, but in our case we actually want them to have width: if they
11+ // show up in text, we want to treat them as textual elements that can
12+ // be editied. So we can get away with making all ascii single width
13+ // here.
14+ // Point 2: we're only examining the first codepoint here, which means
15+ // we're ignoring graphemes formed with combining characters. However,
16+ // if it starts with ascii, it's going to be a single-width grapeheme
17+ // regardless, so, again, we can get away with that here.
18+ // Point 3: we're only examining the first _byte_. But for utf8, when
19+ // checking for ascii range values only, that works.
20+ 1
21+ } else {
22+ // We use max(1) here because all grapeheme clusters--even illformed
23+ // ones--should have at least some width so they can be edited
24+ // properly.
25+ UnicodeWidthStr::width(g).max(1)
26+ }
27+}
28+
29+pub fn nth_prev_grapheme_boundary(slice: &RopeSlice, char_idx: usize, n: usize) -> usize {
30+ // TODO: implement this more efficiently. This has to do a lot of
31+ // re-scanning of rope chunks. Probably move the main implementation here,
32+ // and have prev_grapheme_boundary call this instead.
33+ let mut char_idx = char_idx;
34+ for _ in 0..n {
35+ char_idx = prev_grapheme_boundary(slice, char_idx);
36+ }
37+ char_idx
38+}
39+
40+/// Finds the previous grapheme boundary before the given char position.
41+pub fn prev_grapheme_boundary(slice: &RopeSlice, char_idx: usize) -> usize {
42+ // Bounds check
43+ debug_assert!(char_idx <= slice.len_chars());
44+
45+ // We work with bytes for this, so convert.
46+ let byte_idx = slice.char_to_byte(char_idx);
47+
48+ // Get the chunk with our byte index in it.
49+ let (mut chunk, mut chunk_byte_idx, mut chunk_char_idx, _) = slice.chunk_at_byte(byte_idx);
50+
51+ // Set up the grapheme cursor.
52+ let mut gc = GraphemeCursor::new(byte_idx, slice.len_bytes(), true);
53+
54+ // Find the previous grapheme cluster boundary.
55+ loop {
56+ match gc.prev_boundary(chunk, chunk_byte_idx) {
57+ Ok(None) => return 0,
58+ Ok(Some(n)) => {
59+ let tmp = byte_to_char_idx(chunk, n - chunk_byte_idx);
60+ return chunk_char_idx + tmp;
61+ }
62+ Err(GraphemeIncomplete::PrevChunk) => {
63+ let (a, b, c, _) = slice.chunk_at_byte(chunk_byte_idx - 1);
64+ chunk = a;
65+ chunk_byte_idx = b;
66+ chunk_char_idx = c;
67+ }
68+ Err(GraphemeIncomplete::PreContext(n)) => {
69+ let ctx_chunk = slice.chunk_at_byte(n - 1).0;
70+ gc.provide_context(ctx_chunk, n - ctx_chunk.len());
71+ }
72+ _ => unreachable!(),
73+ }
74+ }
75+}
76+
77+pub fn nth_next_grapheme_boundary(slice: &RopeSlice, char_idx: usize, n: usize) -> usize {
78+ // TODO: implement this more efficiently. This has to do a lot of
79+ // re-scanning of rope chunks. Probably move the main implementation here,
80+ // and have next_grapheme_boundary call this instead.
81+ let mut char_idx = char_idx;
82+ for _ in 0..n {
83+ char_idx = next_grapheme_boundary(slice, char_idx);
84+ }
85+ char_idx
86+}
87+
88+/// Finds the next grapheme boundary after the given char position.
89+pub fn next_grapheme_boundary(slice: &RopeSlice, char_idx: usize) -> usize {
90+ // Bounds check
91+ debug_assert!(char_idx <= slice.len_chars());
92+
93+ // We work with bytes for this, so convert.
94+ let byte_idx = slice.char_to_byte(char_idx);
95+
96+ // Get the chunk with our byte index in it.
97+ let (mut chunk, mut chunk_byte_idx, mut chunk_char_idx, _) = slice.chunk_at_byte(byte_idx);
98+
99+ // Set up the grapheme cursor.
100+ let mut gc = GraphemeCursor::new(byte_idx, slice.len_bytes(), true);
101+
102+ // Find the next grapheme cluster boundary.
103+ loop {
104+ match gc.next_boundary(chunk, chunk_byte_idx) {
105+ Ok(None) => return slice.len_chars(),
106+ Ok(Some(n)) => {
107+ let tmp = byte_to_char_idx(chunk, n - chunk_byte_idx);
108+ return chunk_char_idx + tmp;
109+ }
110+ Err(GraphemeIncomplete::NextChunk) => {
111+ chunk_byte_idx += chunk.len();
112+ let (a, _, c, _) = slice.chunk_at_byte(chunk_byte_idx);
113+ chunk = a;
114+ chunk_char_idx = c;
115+ }
116+ Err(GraphemeIncomplete::PreContext(n)) => {
117+ let ctx_chunk = slice.chunk_at_byte(n - 1).0;
118+ gc.provide_context(ctx_chunk, n - ctx_chunk.len());
119+ }
120+ _ => unreachable!(),
121+ }
122+ }
123+}
124+
125+/// Returns whether the given char position is a grapheme boundary.
126+pub fn is_grapheme_boundary(slice: &RopeSlice, char_idx: usize) -> bool {
127+ // Bounds check
128+ debug_assert!(char_idx <= slice.len_chars());
129+
130+ // We work with bytes for this, so convert.
131+ let byte_idx = slice.char_to_byte(char_idx);
132+
133+ // Get the chunk with our byte index in it.
134+ let (chunk, chunk_byte_idx, _, _) = slice.chunk_at_byte(byte_idx);
135+
136+ // Set up the grapheme cursor.
137+ let mut gc = GraphemeCursor::new(byte_idx, slice.len_bytes(), true);
138+
139+ // Determine if the given position is a grapheme cluster boundary.
140+ loop {
141+ match gc.is_boundary(chunk, chunk_byte_idx) {
142+ Ok(n) => return n,
143+ Err(GraphemeIncomplete::PreContext(n)) => {
144+ let (ctx_chunk, ctx_byte_start, _, _) = slice.chunk_at_byte(n - 1);
145+ gc.provide_context(ctx_chunk, ctx_byte_start);
146+ }
147+ _ => unreachable!(),
148+ }
149+ }
150+}
151+
152+/// An iterator over the graphemes of a RopeSlice.
153+#[derive(Clone)]
154+pub struct RopeGraphemes<'a> {
155+ text: RopeSlice<'a>,
156+ chunks: Chunks<'a>,
157+ cur_chunk: &'a str,
158+ cur_chunk_start: usize,
159+ cursor: GraphemeCursor,
160+}
161+
162+impl<'a> RopeGraphemes<'a> {
163+ pub fn new<'b>(slice: &RopeSlice<'b>) -> RopeGraphemes<'b> {
164+ let mut chunks = slice.chunks();
165+ let first_chunk = chunks.next().unwrap_or("");
166+ RopeGraphemes {
167+ text: *slice,
168+ chunks: chunks,
169+ cur_chunk: first_chunk,
170+ cur_chunk_start: 0,
171+ cursor: GraphemeCursor::new(0, slice.len_bytes(), true),
172+ }
173+ }
174+}
175+
176+impl<'a> Iterator for RopeGraphemes<'a> {
177+ type Item = RopeSlice<'a>;
178+
179+ fn next(&mut self) -> Option<RopeSlice<'a>> {
180+ let a = self.cursor.cur_cursor();
181+ let b;
182+ loop {
183+ match self
184+ .cursor
185+ .next_boundary(self.cur_chunk, self.cur_chunk_start)
186+ {
187+ Ok(None) => {
188+ return None;
189+ }
190+ Ok(Some(n)) => {
191+ b = n;
192+ break;
193+ }
194+ Err(GraphemeIncomplete::NextChunk) => {
195+ self.cur_chunk_start += self.cur_chunk.len();
196+ self.cur_chunk = self.chunks.next().unwrap_or("");
197+ }
198+ _ => unreachable!(),
199+ }
200+ }
201+
202+ if a < self.cur_chunk_start {
203+ let a_char = self.text.byte_to_char(a);
204+ let b_char = self.text.byte_to_char(b);
205+
206+ Some(self.text.slice(a_char..b_char))
207+ } else {
208+ let a2 = a - self.cur_chunk_start;
209+ let b2 = b - self.cur_chunk_start;
210+ Some((&self.cur_chunk[a2..b2]).into())
211+ }
212+ }
213+}
helix-core/src/lib.rs+1
@@ -1,4 +1,5 @@
11mod buffer;
2+mod graphemes;
23mod selection;
34mod state;
45mod transaction;
helix-core/src/selection.rs+2−2
@@ -99,8 +99,8 @@ impl Range {
9999/// A selection consists of one or more selection ranges.
100100pub struct Selection {
101101 // TODO: decide how many ranges to inline SmallVec<[Range; 1]>
102− ranges: SmallVec<[Range; 1]>,
103− primary_index: usize,
102+ pub(crate) ranges: SmallVec<[Range; 1]>,
103+ pub(crate) primary_index: usize,
104104}
105105
106106impl Selection {
helix-core/src/state.rs+81−5
@@ -1,17 +1,30 @@
1−use crate::{Buffer, Selection};
1+use crate::graphemes::{nth_next_grapheme_boundary, nth_prev_grapheme_boundary};
2+use crate::{Buffer, Selection, SelectionRange};
23
34/// A state represents the current editor state of a single buffer.
45pub struct State {
5− // TODO: maybe doc: ?
6− buffer: Buffer,
6+ doc: Buffer,
77 selection: Selection,
88}
99
10+#[derive(Copy, Clone, PartialEq, Eq)]
11+pub enum Direction {
12+ Forward,
13+ Backward,
14+}
15+#[derive(Copy, Clone, PartialEq, Eq)]
16+pub enum Granularity {
17+ Character,
18+ Word,
19+ Line,
20+ // LineBoundary
21+}
22+
1023impl State {
1124 #[must_use]
12− pub fn new(buffer: Buffer) -> Self {
25+ pub fn new(doc: Buffer) -> Self {
1326 Self {
14− buffer,
27+ doc,
1528 selection: Selection::single(0, 0),
1629 }
1730 }
@@ -40,4 +53,67 @@ impl State {
4053 // syntax
4154 // foldable
4255 // changeFilter/transactionFilter
56+
57+ pub fn move_pos(
58+ &self,
59+ pos: usize,
60+ dir: Direction,
61+ granularity: Granularity,
62+ n: usize,
63+ ) -> usize {
64+ let text = &self.doc.contents;
65+ match (dir, granularity) {
66+ (Direction::Backward, Granularity::Character) => {
67+ nth_prev_grapheme_boundary(&text.slice(..), pos, n)
68+ }
69+ (Direction::Forward, Granularity::Character) => {
70+ nth_next_grapheme_boundary(&text.slice(..), pos, n)
71+ }
72+ _ => pos,
73+ }
74+ }
75+
76+ pub fn move_selection(
77+ &self,
78+ sel: Selection,
79+ dir: Direction,
80+ granularity: Granularity,
81+ // TODO: n
82+ ) -> Selection {
83+ // TODO: move all selections according to normal cursor move semantics by collapsing it
84+ // into cursors and moving them vertically
85+
86+ let ranges = sel.ranges.into_iter().map(|range| {
87+ // let pos = if !range.is_empty() {
88+ // // if selection already exists, bump it to the start or end of current select first
89+ // if dir == Direction::Backward {
90+ // range.from()
91+ // } else {
92+ // range.to()
93+ // }
94+ // } else {
95+ let pos = self.move_pos(range.head, dir, granularity, 1)
96+ // };
97+ SelectionRange::new(pos, pos)
98+ });
99+
100+ Selection::new(ranges.collect(), sel.primary_index)
101+ // TODO: update selection in state via transaction
102+ }
103+
104+ pub fn extend_selection(
105+ &self,
106+ sel: Selection,
107+ dir: Direction,
108+ granularity: Granularity,
109+ n: usize,
110+ ) -> Selection {
111+ let ranges = sel.ranges.into_iter().map(|range| {
112+ let pos = self.move_pos(range.head, dir, granularity, n);
113+ SelectionRange::new(range.anchor, pos)
114+ });
115+
116+ Selection::new(ranges.collect(), sel.primary_index)
117+ // TODO: update selection in state via transaction
118+ }
43119}
helix-term/Cargo.toml+1
@@ -29,3 +29,4 @@ futures = { version = "0.3.5", default-features = false, features = ["std"] }
2929smol = "0.1.10"
3030num_cpus = "1.13.0"
3131piper = "0.1.2"
32+tui = { version = "0.9.5", default-features = false }
helix-term/src/component.rsnew file+18
@@ -0,0 +1,18 @@
1+
2+// IDEA: render to a cache buffer, then if not changed, copy the buf into the parent
3+pub trait Component {
4+ /// Process input events, return true if handled.
5+ fn process_event(&mut self, event: crossterm::event::Event, args) -> bool;
6+ /// Should redraw? Useful for saving redraw cycles if we know component didn't change.
7+ fn should_update(&self) -> bool { true }
8+
9+ fn render(&mut self, surface: &mut Surface, args: ());
10+}
11+
12+// HStack / VStack
13+// focus by component id: each View/Editor gets it's own incremental id at create
14+// Component: View(Arc<State>) -> multiple views can point to same state
15+// id 0 = prompt?
16+// when entering to prompt, it needs to direct Commands to last focus window
17+// -> prompt.trigger(focus_id), on_leave -> focus(focus_id)
18+// popups on another layer
helix-term/src/editor.rs+7
@@ -278,4 +278,11 @@ impl Editor {
278278 println!("The text you entered: {}", typed_text);
279279 Ok(())
280280 }
281+
282+ pub fn render(&self) {
283+ // create a new window sized surface
284+ // paint all components
285+ // diff vs last frame, swap
286+ // paint diff
287+ }
281288}
helix-term/src/line.rs+5
@@ -11,6 +11,8 @@ use futures::{future::FutureExt, select, StreamExt};
1111use smol::Timer;
1212// use futures_timer::Delay;
1313
14+use tui::{backend::CrosstermBackend, Terminal};
15+
1416use crossterm::{
1517 cursor::position,
1618 event::{DisableMouseCapture, EnableMouseCapture, Event, EventStream, KeyCode},
@@ -64,6 +66,9 @@ fn main() -> Result<()> {
6466 let mut stdout = stdout();
6567 execute!(stdout, EnableMouseCapture)?;
6668
69+ let backend = CrosstermBackend::new(stdout);
70+ let mut terminal = Terminal::new(backend)?;
71+
6772 use std::thread;
6873
6974 // Same number of threads as there are CPU cores.
helix-term/src/main.rs+1
@@ -1,4 +1,5 @@
11// mod editor;
2+mod component;
23
34// use editor::Editor;
45