1use std::{cell::RefCell, ops::Range, rc::Rc};
6
7use gpui::{Action, App, Context, SharedString, Window, actions};
8use serde::Deserialize;
9
10use super::{InputBaseState, kind::InputModeKind};
11
12pub trait SpellChecker {
18 fn misspelled_words(&self, text: &str, cx: &App) -> Vec<Range<usize>>;
21
22 fn guesses(&self, word: &str, cx: &App) -> Vec<SharedString>;
24
25 fn learn(&self, word: &str, cx: &mut App);
27}
28
29#[derive(Action, Clone, PartialEq, Eq, Deserialize)]
31#[action(namespace = input, no_json)]
32pub struct CorrectSpelling {
33 pub replacement: SharedString,
35}
36
37actions!(
38 input,
39 [
40 LearnSpelling
42 ]
43);
44
45#[derive(Clone, Debug, PartialEq, Eq)]
47pub struct Misspelling {
48 pub range: Range<usize>,
50 pub word: SharedString,
51 pub guesses: Vec<SharedString>,
52}
53
54pub(crate) struct Spelling {
56 checker: Rc<dyn SpellChecker>,
57 found: RefCell<Option<(u64, Rc<[Range<usize>]>)>>,
59}
60
61impl Spelling {
62 fn new(checker: Rc<dyn SpellChecker>) -> Self {
63 Self {
64 checker,
65 found: RefCell::new(None),
66 }
67 }
68}
69
70impl<M: InputModeKind> InputBaseState<M> {
71 pub fn spell_checker(mut self, checker: impl SpellChecker + 'static) -> Self {
73 self.spelling = Some(Spelling::new(Rc::new(checker)));
74 self
75 }
76
77 pub fn set_spell_checker(
79 &mut self,
80 checker: Option<Rc<dyn SpellChecker>>,
81 cx: &mut Context<Self>,
82 ) {
83 self.spelling = checker.map(Spelling::new);
84 cx.notify();
85 }
86
87 pub(crate) fn misspelled_words(&self, cx: &App) -> Rc<[Range<usize>]> {
90 let Some(spelling) = self.spelling.as_ref().filter(|_| !self.masked) else {
91 return Rc::new([]);
92 };
93 let mut found = spelling.found.borrow_mut();
94 if let Some((revision, ranges)) = found.as_ref()
95 && *revision == self.document_revision
96 {
97 return ranges.clone();
98 }
99 let ranges: Rc<[Range<usize>]> = spelling
100 .checker
101 .misspelled_words(&self.text.to_string(), cx)
102 .into();
103 *found = Some((self.document_revision, ranges.clone()));
104 ranges
105 }
106
107 pub(crate) fn misspellings_shown(&self, cx: &App) -> Vec<Range<usize>> {
110 let cursor = self.cursor();
111 let typing = self.active_selection().is_empty();
112 self.misspelled_words(cx)
113 .iter()
114 .filter(|range| !(typing && range.end == cursor))
115 .cloned()
116 .collect()
117 }
118
119 pub(crate) fn misspelling_at(&self, offset: usize, cx: &App) -> Option<Misspelling> {
121 let spelling = self.spelling.as_ref()?;
122 let range = self
123 .misspelled_words(cx)
124 .iter()
125 .find(|range| range.start <= offset && offset <= range.end)?
126 .clone();
127 let word: SharedString = self.text.slice(range.clone()).to_string().into();
128 let guesses = spelling.checker.guesses(&word, cx);
129 Some(Misspelling {
130 range,
131 word,
132 guesses,
133 })
134 }
135
136 pub fn context_menu_misspelling(&self, cx: &App) -> Option<Misspelling> {
139 self.misspelling_at(self.context_menu_offset()?, cx)
140 }
141
142 fn misspelling_acted_on(&self, cx: &App) -> Option<Misspelling> {
145 self.misspelling_at(self.context_menu_offset().unwrap_or(self.cursor()), cx)
146 }
147
148 pub(super) fn correct_spelling(
149 &mut self,
150 action: &CorrectSpelling,
151 window: &mut Window,
152 cx: &mut Context<Self>,
153 ) {
154 if !self.is_editable() {
155 return;
156 }
157 let Some(misspelling) = self.misspelling_acted_on(cx) else {
158 return;
159 };
160 self.set_selection(misspelling.range.start, misspelling.range.end);
161 self.replace(action.replacement.clone(), window, cx);
162 }
163
164 pub(super) fn learn_spelling(
165 &mut self,
166 _: &LearnSpelling,
167 _: &mut Window,
168 cx: &mut Context<Self>,
169 ) {
170 let Some(misspelling) = self.misspelling_acted_on(cx) else {
171 return;
172 };
173 let Some(spelling) = self.spelling.as_ref() else {
174 return;
175 };
176 let checker = spelling.checker.clone();
177 spelling.found.borrow_mut().take();
178 checker.learn(&misspelling.word, cx);
179 cx.notify();
180 }
181}
182
183#[cfg(test)]
184mod tests {
185 use std::{cell::RefCell, ops::Range, rc::Rc};
186
187 use gpui::{App, SharedString};
188
189 use super::{CorrectSpelling, LearnSpelling, SpellChecker};
190 use crate::input::TextareaState;
191
192 struct Words(Rc<RefCell<Vec<String>>>);
195
196 impl SpellChecker for Words {
197 fn misspelled_words(&self, text: &str, _: &App) -> Vec<Range<usize>> {
198 let known = self.0.borrow();
199 let mut found = Vec::new();
200 let mut start = 0;
201 for word in text.split(' ') {
202 if !word.is_empty() && !known.iter().any(|k| k == word) {
203 found.push(start..start + word.len());
204 }
205 start += word.len() + 1;
206 }
207 found
208 }
209
210 fn guesses(&self, _: &str, _: &App) -> Vec<SharedString> {
211 vec!["world".into()]
212 }
213
214 fn learn(&self, word: &str, _: &mut App) {
215 self.0.borrow_mut().push(word.to_owned());
216 }
217 }
218
219 #[gpui::test]
220 fn misspelled_words_are_found_corrected_and_learned(cx: &mut gpui::TestAppContext) {
221 cx.update(crate::init);
222 let known = Rc::new(RefCell::new(vec!["hello".to_owned(), "world".to_owned()]));
223 let checker = Words(known.clone());
224 let (state, cx) = cx.add_window_view(|window, cx| {
225 TextareaState::new(window, cx)
226 .spell_checker(checker)
227 .default_value("hello wurld zorp")
228 });
229 let misspelled = |cx: &mut gpui::VisualTestContext| {
230 state.read_with(cx, |state, cx| state.misspelled_words(cx).to_vec())
231 };
232 assert_eq!(misspelled(cx), vec![6..11, 12..16]);
233
234 cx.update(|_, cx| state.update(cx, |state, cx| state.set_selected_range(16..16, cx)));
236 let shown = state.read_with(cx, |state, cx| state.misspellings_shown(cx));
237 assert_eq!(shown, vec![6..11]);
238
239 let found = state.read_with(cx, |state, cx| state.misspelling_at(8, cx));
240 assert_eq!(
241 found.map(|m| (m.word, m.guesses)),
242 Some(("wurld".into(), vec!["world".into()]))
243 );
244
245 cx.update(|window, cx| {
246 state.update(cx, |state, cx| {
247 state.set_selected_range(8..8, cx);
248 let world = CorrectSpelling {
249 replacement: "world".into(),
250 };
251 state.correct_spelling(&world, window, cx);
252 })
253 });
254 assert_eq!(
255 state.read_with(cx, |state, _| state.value()),
256 "hello world zorp"
257 );
258 assert_eq!(misspelled(cx), vec![12..16]);
259
260 cx.update(|window, cx| {
261 state.update(cx, |state, cx| {
262 state.set_selected_range(13..13, cx);
263 state.learn_spelling(&LearnSpelling, window, cx);
264 })
265 });
266 assert!(known.borrow().iter().any(|k| k == "zorp"));
267 assert!(misspelled(cx).is_empty());
268 }
269}