Offline, privacy-first grammar checker. Fast, open-source, Rust-powered
feat(fst-dict): implement suggesting logic in spell/mod.rs
Grant Lemons01f996c35d99
diff --git a/harper-core/src/spell/fst_dictionary.rs b/harper-core/src/spell/fst_dictionary.rsindex 3cee520a5..e590ffc80 100644--- a/harper-core/src/spell/fst_dictionary.rs+++ b/harper-core/src/spell/fst_dictionary.rs@@ -1,7 +1,6 @@-use core::str;-use fst::Map as FstMap;use fst::{automaton::Levenshtein, IntoStreamer};+use itertools::Itertools;use super::hunspell::{parse_default_attribute_list, parse_default_word_list};use crate::{CharString, Lrc, WordMetadata};@@ -29,13 +28,15 @@ fn uncached_inner_new() -> Lrc<FstDictionary> {// all of it into memory.let word_map = FstMap::new(include_bytes!("../../dictionary.fst").to_vec()).unwrap();- let mut words: Vec<CharString> = word_list- .iter()- .map(|mw| mw.letters.as_ref().into())- .collect();- words.sort();- words.dedup();- let metadata: Vec<WordMetadata> = todo!();+ // There will be at _least_ this number of words+ let mut wmap = hashbrown::HashMap::with_capacity(word_list.len());+ attr_list.expand_marked_words(word_list, &mut wmap);++ let (words, metadata) = wmap+ .into_iter()+ .sorted_by(|a, b| Ord::cmp(a.0.as_slice(), b.0.as_slice()))+ .dedup_by(|a, b| a.0 == b.0)+ .unzip();Lrc::new(FstDictionary {metadata,diff --git a/harper-core/src/spell/mod.rs b/harper-core/src/spell/mod.rsindex 072f9aae7..d80ba3bdf 100644--- a/harper-core/src/spell/mod.rs+++ b/harper-core/src/spell/mod.rs@@ -1,5 +1,3 @@-use std::borrow::Cow;-use itertools::{Itertools, MinMaxResult};use crate::CharString;@@ -27,12 +25,52 @@ pub fn suggest_correct_spelling<'a>(.into_iter().map(|r| r.0).collect();- matches++ let mut found = Vec::with_capacity(matches.len());+ // Often the longest and the shortest words are the most helpful, so lets push+ // them first.+ let minmax = matches.iter().position_minmax_by_key(|a| a.len());+ if let MinMaxResult::MinMax(a, b) = minmax {+ if a == b {+ found.push(matches[a]);+ } else {+ found.push(matches[a]);+ found.push(matches[b]);+ }++ // Push the rest+ found.extend(+ matches+ .iter()+ .enumerate()+ .filter(|(i, _)| *i != a && *i != b)+ .map(|v| v.1),+ );+ } else {+ // Push the rest+ found.extend(matches);+ }++ // Swap the lowest edit distance word with the shortest.+ if found.len() >= 3 {+ found.swap(0, 2);+ }++ // Let common words bubble up.+ found.sort_by_key(|v| {+ if dictionary.get_word_metadata(v).common {+ 0+ } else {+ 1+ }+ });++ found}/// Convenience function over [`suggest_correct_spelling`] that does conversions/// for you.-pub(self) fn suggest_correct_spelling_str(+pub fn suggest_correct_spelling_str(misspelled_word: impl Into<String>,result_limit: usize,max_edit_dist: u8,