1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
mod config;
mod data;
pub mod hunspell;
use std::io;
use std::path::PathBuf;
pub use config::load_config;
pub use data::LangProvider;
use directories::ProjectDirs;
use unicode_segmentation::UnicodeSegmentation;
pub(crate) fn dirs() -> ProjectDirs {
ProjectDirs::from("", "", "rspell").expect("get project directories")
}
#[derive(Debug)]
#[non_exhaustive]
pub enum SpellError {
DicNotFound(PathBuf),
NoDicSource,
FileCachingError(io::Error),
RemoveDicError(io::Error),
ConversionError(io::Error),
InitConfigError(io::Error),
ReadConfigError(io::Error),
LoadConfigError(toml::de::Error),
}
#[derive(Debug)]
pub enum SpellResult {
Correct,
Incorrect { suggestions: Vec<String> },
}
impl SpellResult {
pub fn correct(&self) -> bool {
match self {
Self::Correct => true,
_ => false,
}
}
}
#[derive(Debug)]
pub struct BadWord<'a> {
pub offset: usize,
pub word: &'a str,
pub suggestions: Vec<String>,
}
pub struct Spell {
hs: hunspell::Hunspell,
}
impl Spell {
pub fn new(lang: &str) -> Result<Spell, SpellError> {
if cfg!(feature = "local_files") {
let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("files");
Ok(Spell {
hs: hunspell::Hunspell::new(
dir.join(&format!("{}.aff", lang)),
dir.join(&format!("{}.dic", lang)),
),
})
} else {
let config = config::load_config()?;
let provider = LangProvider::new(lang, &config);
provider.ensure_data()?;
Ok(Spell {
hs: provider.into(),
})
}
}
pub fn check_word(&self, word: &str) -> SpellResult {
if self.hs.spell(word) {
SpellResult::Correct
} else {
SpellResult::Incorrect {
suggestions: self.hs.suggest(word),
}
}
}
pub fn check<'a>(&self, text: &'a str) -> Vec<BadWord<'a>> {
text.split_word_bound_indices()
.filter(|(_, word)| word.chars().any(char::is_alphanumeric))
.filter_map(|(i, word)| match self.check_word(word) {
SpellResult::Correct => None,
SpellResult::Incorrect { suggestions } => Some(BadWord {
offset: i,
word,
suggestions,
}),
})
.collect()
}
}