Skip to content

Offline, privacy-first grammar checker. Fast, open-source, Rust-powered

feat(core): properly capitalize unusual proper nouns in titles

Elijah Potter935f4a863a7f
diff --git a/harper-core/affixes.json b/harper-core/affixes.json
index 6a51b3d9e..ab65899c1 100644
--- a/harper-core/affixes.json
+++ b/harper-core/affixes.json
@@ -289,7 +289,9 @@
"is_possessive": true
}
},
- "gifts_metadata": {}
+ "gifts_metadata": {
+ "noun": {}
+ }
},
"F": {
"#": "'con-' prefix",
diff --git a/harper-core/dictionary.dict b/harper-core/dictionary.dict
index 62b5f9c74..1cf7fedf6 100644
--- a/harper-core/dictionary.dict
+++ b/harper-core/dictionary.dict
@@ -8570,7 +8570,6 @@ Ryan/2M
Rydberg/2M
Ryder/2M
Ryukyu/2M
-S/152MN
SA/5124
SAC/12
SALT/2M
@@ -37361,7 +37360,6 @@ pox/14MS
pp/1
ppm/1
ppr
-pr/5
practicability/1M
practicably/
practical/51SMY
diff --git a/harper-core/src/document.rs b/harper-core/src/document.rs
index 237b249d6..e6809f677 100644
--- a/harper-core/src/document.rs
+++ b/harper-core/src/document.rs
@@ -129,7 +129,10 @@ impl Document {
for token in self.tokens.iter_mut() {
if let TokenKind::Word(meta) = &mut token.kind {
let word_source = token.span.get_content(&self.source);
- let found_meta = dictionary.get_word_metadata(word_source);
+ let found_meta = dictionary
+ .get_correct_capitalization_of(word_source)
+ .map(|canonical_caps| dictionary.get_word_metadata(canonical_caps))
+ .unwrap_or_default();
*meta = meta.or(&found_meta);
}
}
diff --git a/harper-core/src/linting/compound_nouns/general_compound_nouns.rs b/harper-core/src/linting/compound_nouns/general_compound_nouns.rs
index d499ec32d..3c720e56e 100644
--- a/harper-core/src/linting/compound_nouns/general_compound_nouns.rs
+++ b/harper-core/src/linting/compound_nouns/general_compound_nouns.rs
@@ -58,6 +58,7 @@ impl PatternLinter for GeneralCompoundNouns {
fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Lint {
let span = matched_tokens.span().unwrap();
+ let orig = span.get_content(source);
// If the pattern matched, this will not return `None`.
let word = self
.split_pattern
@@ -67,7 +68,7 @@ impl PatternLinter for GeneralCompoundNouns {
Lint {
span,
lint_kind: LintKind::Spelling,
- suggestions: vec![Suggestion::ReplaceWith(word.to_vec())],
+ suggestions: vec![Suggestion::replace_with_match_case(word.to_vec(), orig)],
message: format!(
"Did you mean the closed compound noun “{}”?",
word.to_string()
diff --git a/harper-core/src/linting/compound_nouns/mod.rs b/harper-core/src/linting/compound_nouns/mod.rs
index f5989d428..6846d91da 100644
--- a/harper-core/src/linting/compound_nouns/mod.rs
+++ b/harper-core/src/linting/compound_nouns/mod.rs
@@ -226,7 +226,7 @@ mod tests {
#[test]
fn web_socket() {
let test_sentence = "Real-time updates are sent via a web socket.";
- let expected = "Real-time updates are sent via a WebSocket.";
+ let expected = "Real-time updates are sent via a websocket.";
assert_suggestion_result(test_sentence, CompoundNouns::default(), expected);
}
diff --git a/harper-core/src/linting/spell_check.rs b/harper-core/src/linting/spell_check.rs
index 51bbbe368..eef15c04c 100644
--- a/harper-core/src/linting/spell_check.rs
+++ b/harper-core/src/linting/spell_check.rs
@@ -5,7 +5,7 @@ use super::Suggestion;
use super::{Lint, LintKind, Linter};
use crate::document::Document;
use crate::spell::suggest_correct_spelling;
-use crate::{CharString, Dictionary, TokenStringExt};
+use crate::{CharString, CharStringExt, Dictionary, TokenStringExt};
pub struct SpellCheck<T>
where
@@ -56,7 +56,9 @@ impl<T: Dictionary> Linter for SpellCheck<T> {
for word in document.iter_words() {
let word_chars = document.get_span_content(word.span);
- if self.dictionary.contains_word(word_chars) {
+ if self.dictionary.contains_exact_word(word_chars)
+ || self.dictionary.contains_exact_word(&word_chars.to_lower())
+ {
continue;
}
diff --git a/harper-core/src/patterns/split_compound_word.rs b/harper-core/src/patterns/split_compound_word.rs
index 9cb53d9cb..b972a805e 100644
--- a/harper-core/src/patterns/split_compound_word.rs
+++ b/harper-core/src/patterns/split_compound_word.rs
@@ -34,36 +34,25 @@ impl SplitCompoundWord {
word_b: Token,
source: &[char],
) -> Option<CharString> {
- let mut a_chars: CharString = word_a.span.get_content(source).into();
- let mut b_chars: CharString = word_b.span.get_content(source).into();
+ let a_chars: CharString = word_a.span.get_content(source).into();
+ let b_chars: CharString = word_b.span.get_content(source).into();
let mut buffer = CharString::new();
- macro_rules! attempt {
- () => {
- buffer.clear();
- buffer.extend_from_slice(&a_chars);
- buffer.extend_from_slice(&b_chars);
+ buffer.clear();
+ buffer.extend_from_slice(&a_chars);
+ buffer.extend_from_slice(&b_chars);
- if self.dict.contains_word(&buffer) {
- let metadata = self.dict.get_word_metadata(&buffer);
- if (self.predicate)(metadata) {
- return Some(buffer);
- }
- }
- };
+ if self.dict.contains_word(&buffer) {
+ let metadata = self.dict.get_word_metadata(&buffer);
+ if (self.predicate)(metadata) {
+ let correct = self.dict.get_correct_capitalization_of(&buffer).unwrap();
+ buffer.clear();
+ buffer.extend_from_slice(correct);
+ return Some(buffer);
+ }
}
- attempt!();
- a_chars[0] = a_chars[0].to_ascii_uppercase();
- attempt!();
- b_chars[0] = b_chars[0].to_ascii_uppercase();
- attempt!();
- a_chars[0] = a_chars[0].to_ascii_lowercase();
- attempt!();
- b_chars[0] = b_chars[0].to_ascii_lowercase();
- attempt!();
-
None
}
}
diff --git a/harper-core/src/spell/dictionary.rs b/harper-core/src/spell/dictionary.rs
index 403f29b86..7fd1c4f4e 100644
--- a/harper-core/src/spell/dictionary.rs
+++ b/harper-core/src/spell/dictionary.rs
@@ -8,10 +8,14 @@ use crate::WordMetadata;
/// See also: [`super::FstDictionary`] and [`super::MutableDictionary`].
#[blanket(derive(Arc))]
pub trait Dictionary: Send + Sync {
- /// Check if the dictionary contains a given word.
+ /// Check if the dictionary contains any capitalization of a given word.
fn contains_word(&self, word: &[char]) -> bool;
- /// Check if the dictionary contains a given word.
+ /// Check if the dictionary contains any capitalization of a given word.
fn contains_word_str(&self, word: &str) -> bool;
+ /// Check if the dictionary contains the exact capitalization of a given word.
+ fn contains_exact_word(&self, word: &[char]) -> bool;
+ /// Check if the dictionary contains the exact capitalization of a given word.
+ fn contains_exact_word_str(&self, word: &str) -> bool;
/// Gets best fuzzy match from dictionary
fn fuzzy_match(
&self,
@@ -26,15 +30,15 @@ pub trait Dictionary: Send + Sync {
max_distance: u8,
max_results: usize,
) -> Vec<FuzzyMatchResult>;
- /// Get the associated [`WordMetadata`] for a given word.
+ fn get_correct_capitalization_of(&self, word: &[char]) -> Option<&'_ [char]>;
+ /// Get the associated [`WordMetadata`] for any capitalization of a given word.
/// If the word isn't in the dictionary, the resulting metadata will be
/// empty.
fn get_word_metadata(&self, word: &[char]) -> WordMetadata;
- /// Get the associated [`WordMetadata`] for a given word.
+ /// Get the associated [`WordMetadata`] for any capitalization of a given word.
/// If the word isn't in the dictionary, the resulting metadata will be
/// empty.
fn get_word_metadata_str(&self, word: &str) -> WordMetadata;
-
/// Iterate over the words in the dictionary.
fn words_iter(&self) -> Box<dyn Iterator<Item = &'_ [char]> + Send + '_>;
diff --git a/harper-core/src/spell/fst_dictionary.rs b/harper-core/src/spell/fst_dictionary.rs
index 816048043..bd7f79cac 100644
--- a/harper-core/src/spell/fst_dictionary.rs
+++ b/harper-core/src/spell/fst_dictionary.rs
@@ -212,6 +212,18 @@ impl Dictionary for FstDictionary {
fn words_with_len_iter(&self, len: usize) -> Box<dyn Iterator<Item = &'_ [char]> + Send + '_> {
self.full_dict.words_with_len_iter(len)
}
+
+ fn contains_exact_word(&self, word: &[char]) -> bool {
+ self.full_dict.contains_exact_word(word)
+ }
+
+ fn contains_exact_word_str(&self, word: &str) -> bool {
+ self.full_dict.contains_exact_word_str(word)
+ }
+
+ fn get_correct_capitalization_of(&self, word: &[char]) -> Option<&'_ [char]> {
+ self.full_dict.get_correct_capitalization_of(word)
+ }
}
#[cfg(test)]
diff --git a/harper-core/src/spell/merged_dictionary.rs b/harper-core/src/spell/merged_dictionary.rs
index c455a2298..2724d37cf 100644
--- a/harper-core/src/spell/merged_dictionary.rs
+++ b/harper-core/src/spell/merged_dictionary.rs
@@ -37,6 +37,15 @@ impl Default for MergedDictionary {
}
impl Dictionary for MergedDictionary {
+ fn get_correct_capitalization_of(&self, word: &[char]) -> Option<&'_ [char]> {
+ for child in &self.children {
+ if let Some(word) = child.get_correct_capitalization_of(word) {
+ return Some(word);
+ }
+ }
+ None
+ }
+
fn contains_word(&self, word: &[char]) -> bool {
for child in &self.children {
if child.contains_word(word) {
@@ -46,6 +55,15 @@ impl Dictionary for MergedDictionary {
false
}
+ fn contains_exact_word(&self, word: &[char]) -> bool {
+ for child in &self.children {
+ if child.contains_exact_word(word) {
+ return true;
+ }
+ }
+ false
+ }
+
fn get_word_metadata(&self, word: &[char]) -> WordMetadata {
let mut found_metadata = WordMetadata::default();
for child in &self.children {
@@ -72,6 +90,11 @@ impl Dictionary for MergedDictionary {
self.contains_word(&chars)
}
+ fn contains_exact_word_str(&self, word: &str) -> bool {
+ let chars: CharString = word.chars().collect();
+ self.contains_word(&chars)
+ }
+
fn get_word_metadata_str(&self, word: &str) -> WordMetadata {
let chars: CharString = word.chars().collect();
self.get_word_metadata(&chars)
diff --git a/harper-core/src/spell/mutable_dictionary.rs b/harper-core/src/spell/mutable_dictionary.rs
index a88fed755..17f950701 100644
--- a/harper-core/src/spell/mutable_dictionary.rs
+++ b/harper-core/src/spell/mutable_dictionary.rs
@@ -14,7 +14,7 @@ use crate::{CharString, CharStringExt, WordMetadata};
use super::dictionary::Dictionary;
use super::FuzzyMatchResult;
-/// A basic dictionary that allows words to be added.
+/// A basic dictionary that allows words to be added after instantiating.
/// This is useful for user and file dictionaries that may change at runtime.
///
/// For immutable use-cases, such as the curated dictionary, prefer [`super::FstDictionary`],
@@ -37,6 +37,12 @@ pub struct MutableDictionary {
word_len_starts: Vec<usize>,
/// All English words
word_map: HashMap<CharString, WordMetadata>,
+ /// A map from the lowercase versions of a word to the correct capitalization
+ /// of that same word.
+ ///
+ /// It can be used to check if a word is correctly capitalized, or if it is valid, regardless of
+ /// capitalization.
+ word_map_lowercase: HashMap<CharString, CharString>,
}
/// The uncached function that is used to produce the original copy of the
@@ -56,8 +62,14 @@ fn uncached_inner_new() -> Arc<MutableDictionary> {
words.dedup();
words.sort_unstable_by_key(|w| w.len());
+ let mut word_map_lowercase = HashMap::with_capacity(word_map.len());
+ for key in word_map.keys() {
+ word_map_lowercase.insert(key.to_lower(), key.clone());
+ }
+
Arc::new(MutableDictionary {
word_map,
+ word_map_lowercase,
word_len_starts: MutableDictionary::create_len_starts(&words),
words,
})
@@ -73,6 +85,7 @@ impl MutableDictionary {
words: Vec::new(),
word_len_starts: Vec::new(),
word_map: HashMap::new(),
+ word_map_lowercase: HashMap::new(),
}
}
@@ -98,6 +111,8 @@ impl MutableDictionary {
self.words.extend(pairs.iter().map(|(v, _)| v.clone()));
self.words.sort_by_key(|w| w.len());
self.word_len_starts = Self::create_len_starts(&self.words);
+ self.word_map_lowercase
+ .extend(pairs.iter().map(|(key, _)| (key.to_lower(), key.clone())));
self.word_map.extend(pairs);
}
@@ -145,12 +160,13 @@ impl Default for MutableDictionary {
impl Dictionary for MutableDictionary {
fn get_word_metadata(&self, word: &[char]) -> WordMetadata {
let normalized = seq_to_normalized(word);
- let lowercase: CharString = normalized.to_lower();
+ let Some(correct_caps) = self.get_correct_capitalization_of(&normalized) else {
+ return WordMetadata::default();
+ };
self.word_map
- .get(normalized.as_ref())
+ .get(correct_caps)
.cloned()
- .or(self.word_map.get(lowercase.as_ref()).cloned())
.unwrap_or(WordMetadata::default())
}
@@ -158,7 +174,7 @@ impl Dictionary for MutableDictionary {
let normalized = seq_to_normalized(word);
let lowercase: CharString = normalized.to_lower();
- self.word_map.contains_key(normalized.as_ref()) || self.word_map.contains_key(&lowercase)
+ self.word_map_lowercase.contains_key(&lowercase)
}
fn contains_word_str(&self, word: &str) -> bool {
@@ -171,6 +187,15 @@ impl Dictionary for MutableDictionary {
self.get_word_metadata(&chars)
}
+ fn get_correct_capitalization_of(&self, word: &[char]) -> Option<&'_ [char]> {
+ let normalized = seq_to_normalized(word);
+ let lowercase: CharString = normalized.to_lower();
+
+ self.word_map_lowercase
+ .get(&lowercase)
+ .map(|v| v.as_slice())
+ }
+
/// Suggest a correct spelling for a given misspelled word.
/// `Self::word` is assumed to be quite small (n < 100).
/// `max_distance` relates to an optimization that allows the search
@@ -258,6 +283,15 @@ impl Dictionary for MutableDictionary {
Box::new(self.words[start..end].iter().map(|v| v.as_slice()))
}
+
+ fn contains_exact_word(&self, word: &[char]) -> bool {
+ self.word_map.contains_key(seq_to_normalized(word).as_ref())
+ }
+
+ fn contains_exact_word_str(&self, word: &str) -> bool {
+ let word: CharString = word.chars().collect();
+ self.contains_exact_word(word.as_ref())
+ }
}
#[cfg(test)]
diff --git a/harper-core/src/title_case.rs b/harper-core/src/title_case.rs
index 5cdec274d..6819a314e 100644
--- a/harper-core/src/title_case.rs
+++ b/harper-core/src/title_case.rs
@@ -35,6 +35,24 @@ pub fn make_title_case(toks: &[Token], source: &[char], dict: &impl Dictionary)
let mut output = toks.span().unwrap().get_content(source).to_vec();
while let Some((index, word)) = word_likes.next() {
+ let Some(metadata) = word.kind.as_word() else {
+ continue;
+ };
+
+ if metadata.is_proper_noun() {
+ // Replace it with the dictionary entry verbatim.
+ let orig_text = word.span.get_content(source);
+
+ if let Some(correct_caps) = dict.get_correct_capitalization_of(orig_text) {
+ // It should match the dictionary verbatim
+ output[word.span.start - start_index..word.span.end - start_index]
+ .iter_mut()
+ .enumerate()
+ .for_each(|(idx, c)| *c = correct_caps[idx]);
+ continue;
+ }
+ }
+
let should_capitalize = should_capitalize_token(&word, source, dict)
|| index == 0
|| word_likes.peek().is_none();
@@ -160,6 +178,14 @@ mod tests {
)
}
+ #[test]
+ fn fixes_video_press() {
+ assert_eq!(
+ make_title_case_str("videopress", &PlainEnglish, &FstDictionary::curated()),
+ "VideoPress"
+ )
+ }
+
#[quickcheck]
fn a_stays_lowercase(prefix: String, postfix: String) -> TestResult {
// There must be words other than the `a`.
diff --git a/packages/obsidian-plugin/data.json b/packages/obsidian-plugin/data.json
deleted file mode 100644
index d0f18ef2c..000000000
--- a/packages/obsidian-plugin/data.json
+++ /dev/null
@@ -1,4 +0,0 @@
-{
- "useWebWorker": true,
- "lintSettings": {}
-}