дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-23 18:10:45 +02:00
Порівняти коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
6fbad89af1 |
No files matched your search
@@ -197,28 +197,62 @@ fn software_term(lower: &str) -> bool {
|
||||
.is_some_and(|w| ["s", "x", "z", "ch", "sh"].iter().any(|e| w.ends_with(e)) && plural_of(w))
|
||||
}
|
||||
|
||||
/// Words of a custom dictionary file: a plain word list or a Hunspell `.dic`
|
||||
/// (leading count line and `/FLAGS` ignored). Cached by modification time.
|
||||
fn dictionary_file(path: &Path) -> Arc<HashSet<String>> {
|
||||
type Cache = HashMap<PathBuf, (Option<SystemTime>, Arc<HashSet<String>>)>;
|
||||
static CACHE: OnceLock<Mutex<Cache>> = OnceLock::new();
|
||||
let modified = std::fs::metadata(path).and_then(|m| m.modified()).ok();
|
||||
let mut cache = CACHE.get_or_init(Default::default).lock();
|
||||
if let Some((at, words)) = cache.get(path)
|
||||
&& *at == modified
|
||||
{
|
||||
return words.clone();
|
||||
}
|
||||
let words: HashSet<String> = match std::fs::read_to_string(path) {
|
||||
Ok(text) => parse_word_list(&text),
|
||||
Err(e) => {
|
||||
tracing::debug!("custom dictionary {}: {e}", path.display());
|
||||
HashSet::new()
|
||||
/// A custom dictionary: a word list, or a Hunspell dictionary with its affix rules.
|
||||
enum CustomDictionary {
|
||||
Words(HashSet<String>),
|
||||
Hunspell(Box<spellbook::Dictionary>),
|
||||
}
|
||||
|
||||
impl CustomDictionary {
|
||||
/// Whether the lowercased `lower` is a word of it, in any case style.
|
||||
fn contains(&self, lower: &str) -> bool {
|
||||
match self {
|
||||
Self::Words(words) => words.contains(lower),
|
||||
Self::Hunspell(dict) => {
|
||||
dict.check(lower) || dict.check(&capitalize(lower)) || dict.check(&lower.to_uppercase())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The `.aff` next to a Hunspell `.dic` (`de_DE.dic` → `de_DE.aff`), if there is one.
|
||||
fn affix_file(path: &Path) -> Option<PathBuf> {
|
||||
if !path.extension().is_some_and(|e| e.eq_ignore_ascii_case("dic")) {
|
||||
return None;
|
||||
}
|
||||
["aff", "AFF"].into_iter().map(|ext| path.with_extension(ext)).find(|aff| aff.is_file())
|
||||
}
|
||||
|
||||
/// A custom dictionary file: a Hunspell `.dic` with the `.aff` beside it, with
|
||||
/// its affix, compounding and case rules; otherwise a plain word list (a `.dic`
|
||||
/// alone: leading count line and `/FLAGS` ignored). Cached by modification time.
|
||||
fn dictionary_file(path: &Path) -> Arc<CustomDictionary> {
|
||||
type Stamp = (Option<SystemTime>, Option<SystemTime>);
|
||||
type Cache = HashMap<PathBuf, (Stamp, Arc<CustomDictionary>)>;
|
||||
static CACHE: OnceLock<Mutex<Cache>> = OnceLock::new();
|
||||
let modified = |p: &Path| std::fs::metadata(p).and_then(|m| m.modified()).ok();
|
||||
let aff = affix_file(path);
|
||||
let stamp = (modified(path), aff.as_deref().and_then(modified));
|
||||
if let Some((at, dict)) = CACHE.get_or_init(Default::default).lock().get(path)
|
||||
&& *at == stamp
|
||||
{
|
||||
return dict.clone();
|
||||
}
|
||||
let read = |p: &Path| {
|
||||
std::fs::read_to_string(p).map_err(|e| tracing::debug!("custom dictionary {}: {e}", p.display())).ok()
|
||||
};
|
||||
let words = Arc::new(words);
|
||||
cache.insert(path.to_path_buf(), (modified, words.clone()));
|
||||
words
|
||||
let text = read(path).unwrap_or_default();
|
||||
let hunspell = aff.as_deref().and_then(read).and_then(|aff| {
|
||||
spellbook::Dictionary::new(&aff, &text)
|
||||
.map_err(|e| tracing::warn!("Hunspell dictionary {}: {e}", path.display()))
|
||||
.ok()
|
||||
});
|
||||
let dict = Arc::new(match hunspell {
|
||||
Some(dict) => CustomDictionary::Hunspell(Box::new(dict)),
|
||||
None => CustomDictionary::Words(parse_word_list(&text)),
|
||||
});
|
||||
CACHE.get_or_init(Default::default).lock().insert(path.to_path_buf(), (stamp, dict.clone()));
|
||||
dict
|
||||
}
|
||||
|
||||
/// Lowercased words of a word list / Hunspell `.dic` text.
|
||||
@@ -238,7 +272,7 @@ pub fn parse_word_list(text: &str) -> HashSet<String> {
|
||||
#[derive(Default)]
|
||||
pub struct Speller {
|
||||
accepted: HashSet<String>,
|
||||
custom: Vec<Arc<HashSet<String>>>,
|
||||
custom: Vec<Arc<CustomDictionary>>,
|
||||
}
|
||||
|
||||
impl Speller {
|
||||
@@ -351,16 +385,31 @@ impl Speller {
|
||||
&& !near_word(lower, |w| english().check(w))
|
||||
}
|
||||
|
||||
/// Replacements for `word`, best first, in the word's case style.
|
||||
/// Replacements for `word`, best first, in the word's case style: from the
|
||||
/// English dictionary and the custom Hunspell dictionaries, the closest first.
|
||||
pub fn suggest(&self, word: &str, limit: usize) -> Vec<String> {
|
||||
let hunspell = self.custom.iter().filter_map(|d| match d.as_ref() {
|
||||
CustomDictionary::Hunspell(dict) => Some(dict.as_ref()),
|
||||
CustomDictionary::Words(_) => None,
|
||||
});
|
||||
let dicts: Vec<&spellbook::Dictionary> = std::iter::once(english()).chain(hunspell).collect();
|
||||
let mut out = Vec::new();
|
||||
english().suggest(word, &mut out);
|
||||
if out.is_empty() && word.chars().next().is_some_and(char::is_uppercase) {
|
||||
english().suggest(&word.to_lowercase(), &mut out);
|
||||
out = out.into_iter().map(|s| capitalize(&s)).collect();
|
||||
for dict in &dicts {
|
||||
let mut found = Vec::new();
|
||||
dict.suggest(word, &mut found);
|
||||
if found.is_empty() && word.chars().next().is_some_and(char::is_uppercase) {
|
||||
dict.suggest(&word.to_lowercase(), &mut found);
|
||||
found = found.into_iter().map(|s| capitalize(&s)).collect();
|
||||
}
|
||||
out.extend(found);
|
||||
}
|
||||
let mut seen = HashSet::new();
|
||||
out.retain(|s| s != word && seen.insert(s.clone()));
|
||||
if dicts.len() > 1 {
|
||||
// Stable: within a distance each dictionary keeps its own order, English first.
|
||||
let lower = word.to_lowercase();
|
||||
out.sort_by_key(|s| edit_distance(&lower, &s.to_lowercase()));
|
||||
}
|
||||
out.truncate(limit);
|
||||
out
|
||||
}
|
||||
@@ -416,6 +465,22 @@ impl Speller {
|
||||
}
|
||||
}
|
||||
|
||||
/// Levenshtein distance in characters.
|
||||
fn edit_distance(a: &str, b: &str) -> usize {
|
||||
let b: Vec<char> = b.chars().collect();
|
||||
let mut row: Vec<usize> = (0..=b.len()).collect();
|
||||
for (i, ca) in a.chars().enumerate() {
|
||||
let mut diagonal = row[0];
|
||||
row[0] = i + 1;
|
||||
for (j, cb) in b.iter().enumerate() {
|
||||
let next = (row[j + 1] + 1).min(row[j] + 1).min(diagonal + usize::from(ca != *cb));
|
||||
diagonal = row[j + 1];
|
||||
row[j + 1] = next;
|
||||
}
|
||||
}
|
||||
row[b.len()]
|
||||
}
|
||||
|
||||
fn capitalize(s: &str) -> String {
|
||||
let mut chars = s.chars();
|
||||
chars.next().into_iter().flat_map(char::to_uppercase).chain(chars).collect()
|
||||
@@ -736,6 +801,36 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hunspell_custom_dictionaries_use_their_affix_rules() {
|
||||
let dir = std::env::temp_dir().join(format!("ide-spell-hunspell-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let dic = dir.join("de_TEST.dic");
|
||||
std::fs::write(&dic, "3\nhaus/NZ\ntür/NZ\nschlüssel/Z\n").unwrap();
|
||||
std::fs::write(
|
||||
dir.join("de_TEST.aff"),
|
||||
"SET UTF-8\nTRY esianrtolcdugmphbyfvkwzäöüß\nCOMPOUNDFLAG Z\nSFX N Y 1\nSFX N 0 en .\n",
|
||||
)
|
||||
.unwrap();
|
||||
let s = Speller::new::<&str>([], std::slice::from_ref(&dic));
|
||||
// Affix rules, compounds and case styles of the .aff, not just the listed stems.
|
||||
for word in ["haus", "Haus", "hausen", "türen", "Haustür", "schlüsselhaus"] {
|
||||
assert!(s.is_correct(word), "{word}");
|
||||
}
|
||||
assert!(!s.is_correct("hauz"));
|
||||
assert!(!s.is_correct("schlüsselen"));
|
||||
assert!(s.suggest("Hauss", 5).iter().any(|w| w == "Haus"), "{:?}", s.suggest("Hauss", 5));
|
||||
// English still checks and suggests.
|
||||
assert!(s.is_correct("message"));
|
||||
assert!(s.suggest("mesage", 5).iter().any(|w| w == "message"));
|
||||
// Without its .aff, a .dic is a word list.
|
||||
std::fs::remove_file(dir.join("de_TEST.aff")).unwrap();
|
||||
let words = Speller::new::<&str>([], std::slice::from_ref(&dic));
|
||||
assert!(words.is_correct("haus"));
|
||||
assert!(!words.is_correct("hausen"));
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn utf16_ranges() {
|
||||
let s = Speller::default();
|
||||
|
||||
@@ -65,7 +65,7 @@ function SpellingPage() {
|
||||
<Row
|
||||
label="Dictionary files"
|
||||
stacked
|
||||
hint="Plain-text word lists (one word per line) or Hunspell .dic files. Relative paths resolve against the project root, ~/ against the home folder."
|
||||
hint="Plain-text word lists (one word per line) or Hunspell .dic files; a .dic with its .aff beside it also accepts the inflected forms and compounds its rules allow. Relative paths resolve against the project root, ~/ against the home folder."
|
||||
>
|
||||
<GlobListEditor
|
||||
aria-label="Custom dictionaries"
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
{
|
||||
"Plain-text word lists (one word per line) or Hunspell .dic files; a .dic with its .aff beside it also accepts the inflected forms and compounds its rules allow. Relative paths resolve against the project root, ~/ against the home folder.": "Plain-text word lists (one word per line) or Hunspell .dic files; a .dic with its .aff beside it also accepts the inflected forms and compounds its rules allow. Relative paths resolve against the project root, ~/ against the home folder.",
|
||||
"Trust Folder": "Trust Folder",
|
||||
"No files selected": "No files selected",
|
||||
"{added} added": "{added} added",
|
||||
|
||||
@@ -3244,7 +3244,6 @@
|
||||
"Accepted in every project.": "Aceptadas en todos los proyectos.",
|
||||
"Custom dictionaries": "Diccionarios personalizados",
|
||||
"Dictionary files": "Archivos de diccionario",
|
||||
"Plain-text word lists (one word per line) or Hunspell .dic files. Relative paths resolve against the project root, ~/ against the home folder.": "Listas de palabras en texto plano (una palabra por línea) o archivos .dic de Hunspell. Las rutas relativas se resuelven respecto a la raíz del proyecto y ~/ respecto a la carpeta personal.",
|
||||
"No custom dictionaries": "No hay diccionarios personalizados",
|
||||
"Dictionary path": "Ruta del diccionario",
|
||||
"Natural Languages": "Idiomas naturales",
|
||||
|
||||
@@ -3117,7 +3117,6 @@
|
||||
"Accepted in every project.": "Acceptés dans tous les projets.",
|
||||
"Custom dictionaries": "Dictionnaires personnalisés",
|
||||
"Dictionary files": "Fichiers de dictionnaire",
|
||||
"Plain-text word lists (one word per line) or Hunspell .dic files. Relative paths resolve against the project root, ~/ against the home folder.": "Listes de mots en texte brut (un mot par ligne) ou fichiers Hunspell .dic. Les chemins relatifs sont résolus depuis la racine du projet, ~/ depuis le dossier personnel.",
|
||||
"No custom dictionaries": "Aucun dictionnaire personnalisé",
|
||||
"Dictionary path": "Chemin du dictionnaire",
|
||||
"Natural Languages": "Langues naturelles",
|
||||
|
||||
@@ -3293,7 +3293,6 @@
|
||||
"Accepted in every project.": "모든 프로젝트에서 허용됩니다.",
|
||||
"Custom dictionaries": "사용자 지정 사전",
|
||||
"Dictionary files": "사전 파일",
|
||||
"Plain-text word lists (one word per line) or Hunspell .dic files. Relative paths resolve against the project root, ~/ against the home folder.": "일반 텍스트 단어 목록(한 줄에 한 단어) 또는 Hunspell .dic 파일. 상대 경로는 프로젝트 루트를, ~/는 홈 폴더를 기준으로 해결됩니다.",
|
||||
"No custom dictionaries": "사용자 지정 사전 없음",
|
||||
"Dictionary path": "사전 경로",
|
||||
"Natural Languages": "자연어",
|
||||
|
||||
@@ -3216,7 +3216,6 @@
|
||||
"Accepted in every project.": "Akceptowane we wszystkich projektach.",
|
||||
"Custom dictionaries": "Własne słowniki",
|
||||
"Dictionary files": "Pliki słowników",
|
||||
"Plain-text word lists (one word per line) or Hunspell .dic files. Relative paths resolve against the project root, ~/ against the home folder.": "Listy słów w zwykłym tekście (jednosłowne w wierszu) lub pliki .dic Hunspell. Ścieżki względne są rozwiązywane względem katalogu głównego projektu, a ~/ względem folderu domowego.",
|
||||
"No custom dictionaries": "Brak własnych słowników",
|
||||
"Dictionary path": "Ścieżka słownika",
|
||||
"Natural Languages": "Języki naturalne",
|
||||
|
||||
@@ -3217,7 +3217,6 @@
|
||||
"Accepted in every project.": "Aceitas em todos os projetos.",
|
||||
"Custom dictionaries": "Dicionários personalizados",
|
||||
"Dictionary files": "Arquivos de dicionário",
|
||||
"Plain-text word lists (one word per line) or Hunspell .dic files. Relative paths resolve against the project root, ~/ against the home folder.": "Listas de palavras em texto simples (uma palavra por linha) ou arquivos .dic do Hunspell. Caminhos relativos são resolvidos em relação à raiz do projeto, ~/ em relação à pasta pessoal.",
|
||||
"No custom dictionaries": "Nenhum dicionário personalizado",
|
||||
"Dictionary path": "Caminho do dicionário",
|
||||
"Natural Languages": "Idiomas naturais",
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
{
|
||||
"Plain-text word lists (one word per line) or Hunspell .dic files; a .dic with its .aff beside it also accepts the inflected forms and compounds its rules allow. Relative paths resolve against the project root, ~/ against the home folder.": "纯文本单词列表(每行一个词)或 Hunspell .dic 文件;旁边有同名 .aff 的 .dic 还会接受其规则允许的变形和复合词。相对路径基于项目根目录解析,~/ 表示主目录。",
|
||||
"MCP server instructions": "MCP 服务器说明",
|
||||
"MCP tools (deferred)": "MCP 工具(延迟加载)",
|
||||
"System tools (deferred)": "系统工具(延迟加载)",
|
||||
@@ -4104,7 +4105,6 @@
|
||||
"Accepted in every project.": "在所有项目中接受。",
|
||||
"Custom dictionaries": "自定义词典",
|
||||
"Dictionary files": "词典文件",
|
||||
"Plain-text word lists (one word per line) or Hunspell .dic files. Relative paths resolve against the project root, ~/ against the home folder.": "纯文本单词列表(每行一个单词)或 Hunspell .dic 文件。相对路径相对于项目根目录解析,~/ 相对于主文件夹解析。",
|
||||
"No custom dictionaries": "没有自定义词典",
|
||||
"Dictionary path": "词典路径",
|
||||
"Natural Languages": "自然语言",
|
||||
|
||||
Reference in new issue
Заблокувати користувача