Debian Codegraph @

helix-core/src/graphemes.rs

raw symbols SCIP
1 //! Utility functions to traverse the unicode graphemes of a `Rope`'s text contents.
2 //!
3 //! Based on <https://github.com/cessen/led/blob/c4fa72405f510b7fd16052f90a598c429b3104a6/src/graphemes.rs>
4 use ropey::{str_utils::byte_to_char_idx, RopeSlice};
5 use unicode_segmentation::{GraphemeCursor, GraphemeIncomplete};
6 use unicode_width::UnicodeWidthStr;
7
8 use std::borrow::Cow;
9 use std::fmt::{self, Debug, Display};
10 use std::marker::PhantomData;
11 use std::ops::Deref;
12 use std::ptr::NonNull;
13 use std::{slice, str};
14
15 use crate::chars::{char_is_whitespace, char_is_word};
16 use crate::LineEnding;
17
18 #[inline]
19 pub fn tab_width_at(visual_x: usize, tab_width: u16) -> usize {
20 tab_width as usize - (visual_x % tab_width as usize)
21 }
22
23 #[derive(Debug, Clone, PartialEq, Eq)]
24 pub enum Grapheme<'a> {
25 Newline,
26 Tab { width: usize },
27 Other { g: GraphemeStr<'a> },
28 }
29
30 impl<'a> Grapheme<'a> {
31 pub fn new_decoration(g: &'static str) -> Grapheme<'a> {
32 assert_ne!(g, "\t");
33 Grapheme::new(g.into(), 0, 0)
34 }
35
36 pub fn new(g: GraphemeStr<'a>, visual_x: usize, tab_width: u16) -> Grapheme<'a> {
37 match g {
38 g if g == "\t" => Grapheme::Tab {
39 width: tab_width_at(visual_x, tab_width),
40 },
41 _ if LineEnding::from_str(&g).is_some() => Grapheme::Newline,
42 _ => Grapheme::Other { g },
43 }
44 }
45
46 pub fn change_position(&mut self, visual_x: usize, tab_width: u16) {
47 if let Grapheme::Tab { width } = self {
48 *width = tab_width_at(visual_x, tab_width)
49 }
50 }
51
52 /// Returns the a visual width of this grapheme,
53 #[inline]
54 pub fn width(&self) -> usize {
55 match *self {
56 // width is not cached because we are dealing with
57 // ASCII almost all the time which already has a fastpath
58 // it's okay to convert to u16 here because no codepoint has a width larger
59 // than 2 and graphemes are usually atmost two visible codepoints wide
60 Grapheme::Other { ref g } => grapheme_width(g),
61 Grapheme::Tab { width } => width,
62 Grapheme::Newline => 1,
63 }
64 }
65
66 pub fn is_whitespace(&self) -> bool {
67 !matches!(&self, Grapheme::Other { g } if !g.chars().next().is_some_and(char_is_whitespace))
68 }
69
70 // TODO currently word boundaries are used for softwrapping.
71 // This works best for programming languages and well for prose.
72 // This could however be improved in the future by considering unicode
73 // character classes but
74 pub fn is_word_boundary(&self) -> bool {
75 !matches!(&self, Grapheme::Other { g,.. } if g.chars().next().is_some_and(char_is_word))
76 }
77 }
78
79 impl Display for Grapheme<'_> {
80 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81 match *self {
82 Grapheme::Newline => write!(f, " "),
83 Grapheme::Tab { width } => {
84 for _ in 0..width {
85 write!(f, " ")?;
86 }
87 Ok(())
88 }
89 Grapheme::Other { ref g } => {
90 write!(f, "{g}")
91 }
92 }
93 }
94 }
95
96 #[must_use]
97 pub fn grapheme_width(g: &str) -> usize {
98 if g.as_bytes()[0] <= 127 {
99 // Fast-path ascii.
100 // Point 1: theoretically, ascii control characters should have zero
101 // width, but in our case we actually want them to have width: if they
102 // show up in text, we want to treat them as textual elements that can
103 // be edited. So we can get away with making all ascii single width
104 // here.
105 // Point 2: we're only examining the first codepoint here, which means
106 // we're ignoring graphemes formed with combining characters. However,
107 // if it starts with ascii, it's going to be a single-width grapeheme
108 // regardless, so, again, we can get away with that here.
109 // Point 3: we're only examining the first _byte_. But for utf8, when
110 // checking for ascii range values only, that works.
111 1
112 } else {
113 // We use max(1) here because all grapeheme clusters--even illformed
114 // ones--should have at least some width so they can be edited
115 // properly.
116 // TODO properly handle unicode width for all codepoints
117 // example of where unicode width is currently wrong: 🤦🏼‍♂️ (taken from https://hsivonen.fi/string-length/)
118 UnicodeWidthStr::width(g).max(1)
119 }
120 }
121
122 // NOTE: for byte indexing versions of these functions see `RopeSliceExt`'s
123 // `floor_grapheme_boundary` and `ceil_grapheme_boundary` and the rope grapheme iterators.
124
125 #[must_use]
126 pub fn nth_prev_grapheme_boundary(slice: RopeSlice, char_idx: usize, n: usize) -> usize {
127 // Bounds check
128 debug_assert!(char_idx <= slice.len_chars());
129
130 // We work with bytes for this, so convert.
131 let mut byte_idx = slice.char_to_byte(char_idx);
132
133 // Get the chunk with our byte index in it.
134 let (mut chunk, mut chunk_byte_idx, mut chunk_char_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 // Find the previous grapheme cluster boundary.
140 for _ in 0..n {
141 loop {
142 match gc.prev_boundary(chunk, chunk_byte_idx) {
143 Ok(None) => return 0,
144 Ok(Some(n)) => {
145 byte_idx = n;
146 break;
147 }
148 Err(GraphemeIncomplete::PrevChunk) => {
149 let (a, b, c, _) = slice.chunk_at_byte(chunk_byte_idx - 1);
150 chunk = a;
151 chunk_byte_idx = b;
152 chunk_char_idx = c;
153 }
154 Err(GraphemeIncomplete::PreContext(n)) => {
155 let ctx_chunk = slice.chunk_at_byte(n - 1).0;
156 gc.provide_context(ctx_chunk, n - ctx_chunk.len());
157 }
158 _ => unreachable!(),
159 }
160 }
161 }
162 let tmp = byte_to_char_idx(chunk, byte_idx - chunk_byte_idx);
163 chunk_char_idx + tmp
164 }
165
166 /// Finds the previous grapheme boundary before the given char position.
167 #[must_use]
168 #[inline(always)]
169 pub fn prev_grapheme_boundary(slice: RopeSlice, char_idx: usize) -> usize {
170 nth_prev_grapheme_boundary(slice, char_idx, 1)
171 }
172
173 #[must_use]
174 pub fn nth_next_grapheme_boundary(slice: RopeSlice, char_idx: usize, n: usize) -> usize {
175 // Bounds check
176 debug_assert!(char_idx <= slice.len_chars());
177
178 // We work with bytes for this, so convert.
179 let mut byte_idx = slice.char_to_byte(char_idx);
180
181 // Get the chunk with our byte index in it.
182 let (mut chunk, mut chunk_byte_idx, mut chunk_char_idx, _) = slice.chunk_at_byte(byte_idx);
183
184 // Set up the grapheme cursor.
185 let mut gc = GraphemeCursor::new(byte_idx, slice.len_bytes(), true);
186
187 // Find the nth next grapheme cluster boundary.
188 for _ in 0..n {
189 loop {
190 match gc.next_boundary(chunk, chunk_byte_idx) {
191 Ok(None) => return slice.len_chars(),
192 Ok(Some(n)) => {
193 byte_idx = n;
194 break;
195 }
196 Err(GraphemeIncomplete::NextChunk) => {
197 chunk_byte_idx += chunk.len();
198 let (a, _, c, _) = slice.chunk_at_byte(chunk_byte_idx);
199 chunk = a;
200 chunk_char_idx = c;
201 }
202 Err(GraphemeIncomplete::PreContext(n)) => {
203 let ctx_chunk = slice.chunk_at_byte(n - 1).0;
204 gc.provide_context(ctx_chunk, n - ctx_chunk.len());
205 }
206 _ => unreachable!(),
207 }
208 }
209 }
210 let tmp = byte_to_char_idx(chunk, byte_idx - chunk_byte_idx);
211 chunk_char_idx + tmp
212 }
213
214 /// Finds the next grapheme boundary after the given char position.
215 #[must_use]
216 #[inline(always)]
217 pub fn next_grapheme_boundary(slice: RopeSlice, char_idx: usize) -> usize {
218 nth_next_grapheme_boundary(slice, char_idx, 1)
219 }
220
221 /// Returns the passed char index if it's already a grapheme boundary,
222 /// or the next grapheme boundary char index if not.
223 #[must_use]
224 #[inline]
225 pub fn ensure_grapheme_boundary_next(slice: RopeSlice, char_idx: usize) -> usize {
226 if char_idx == 0 {
227 char_idx
228 } else {
229 next_grapheme_boundary(slice, char_idx - 1)
230 }
231 }
232
233 /// Returns the passed char index if it's already a grapheme boundary,
234 /// or the prev grapheme boundary char index if not.
235 #[must_use]
236 #[inline]
237 pub fn ensure_grapheme_boundary_prev(slice: RopeSlice, char_idx: usize) -> usize {
238 if char_idx == slice.len_chars() {
239 char_idx
240 } else {
241 prev_grapheme_boundary(slice, char_idx + 1)
242 }
243 }
244
245 /// A highly compressed Cow<'a, str> that holds
246 /// atmost u31::MAX bytes and is readonly
247 pub struct GraphemeStr<'a> {
248 ptr: NonNull<u8>,
249 len: u32,
250 phantom: PhantomData<&'a str>,
251 }
252
253 impl GraphemeStr<'_> {
254 const MASK_OWNED: u32 = 1 << 31;
255
256 fn compute_len(&self) -> usize {
257 (self.len & !Self::MASK_OWNED) as usize
258 }
259 }
260
261 impl Deref for GraphemeStr<'_> {
262 type Target = str;
263 fn deref(&self) -> &Self::Target {
264 unsafe {
265 let bytes = slice::from_raw_parts(self.ptr.as_ptr(), self.compute_len());
266 str::from_utf8_unchecked(bytes)
267 }
268 }
269 }
270
271 impl Drop for GraphemeStr<'_> {
272 fn drop(&mut self) {
273 if self.len & Self::MASK_OWNED != 0 {
274 // free allocation
275 unsafe {
276 drop(Box::from_raw(std::ptr::slice_from_raw_parts_mut(
277 self.ptr.as_ptr(),
278 self.compute_len(),
279 )));
280 }
281 }
282 }
283 }
284
285 impl<'a> From<&'a str> for GraphemeStr<'a> {
286 fn from(g: &'a str) -> Self {
287 GraphemeStr {
288 ptr: unsafe { NonNull::new_unchecked(g.as_bytes().as_ptr() as *mut u8) },
289 len: i32::try_from(g.len()).unwrap() as u32,
290 phantom: PhantomData,
291 }
292 }
293 }
294
295 impl From<String> for GraphemeStr<'_> {
296 fn from(g: String) -> Self {
297 let len = g.len();
298 let ptr = Box::into_raw(g.into_bytes().into_boxed_slice()) as *mut u8;
299 GraphemeStr {
300 ptr: unsafe { NonNull::new_unchecked(ptr) },
301 len: (i32::try_from(len).unwrap() as u32) | Self::MASK_OWNED,
302 phantom: PhantomData,
303 }
304 }
305 }
306
307 impl<'a> From<Cow<'a, str>> for GraphemeStr<'a> {
308 fn from(g: Cow<'a, str>) -> Self {
309 match g {
310 Cow::Borrowed(g) => g.into(),
311 Cow::Owned(g) => g.into(),
312 }
313 }
314 }
315
316 impl<T: Deref<Target = str>> PartialEq<T> for GraphemeStr<'_> {
317 fn eq(&self, other: &T) -> bool {
318 self.deref() == other.deref()
319 }
320 }
321 impl PartialEq<str> for GraphemeStr<'_> {
322 fn eq(&self, other: &str) -> bool {
323 self.deref() == other
324 }
325 }
326 impl Eq for GraphemeStr<'_> {}
327 impl Debug for GraphemeStr<'_> {
328 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
329 Debug::fmt(self.deref(), f)
330 }
331 }
332 impl Display for GraphemeStr<'_> {
333 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
334 Display::fmt(self.deref(), f)
335 }
336 }
337 impl Clone for GraphemeStr<'_> {
338 fn clone(&self) -> Self {
339 self.deref().to_owned().into()
340 }
341 }