Offline, privacy-first grammar checker. Fast, open-source, Rust-powered
feat(core): add rule to expand btw (#1329)
Elijah Potter1362b0bb4bc0
diff --git a/harper-core/src/linting/initialism_linter.rs b/harper-core/src/linting/initialism_linter.rsnew file mode 100644index 000000000..034cbeeda--- /dev/null+++ b/harper-core/src/linting/initialism_linter.rs@@ -0,0 +1,81 @@+use itertools::Itertools;++use crate::{+ Token,+ patterns::{Pattern, Word},+};++use super::{Lint, LintKind, PatternLinter, Suggestion};++/// A struct that can be composed to expand initialisms, respecting the capitalization of each+/// item.+pub struct InitialismLinter {+ pattern: Box<dyn Pattern>,+ /// The lowercase-normalized expansion of the initialism.+ expansion_lower: Vec<Vec<char>>,+}++impl InitialismLinter {+ /// Construct a linter that can correct an initialism to+ pub fn new(initialism: &str, expansion: &str) -> Self {+ let expansion_lower = expansion+ .split(' ')+ .map(|s| s.chars().map(|v| v.to_ascii_lowercase()).collect())+ .collect();++ Self {+ pattern: Box::new(Word::from_char_string(initialism.chars().collect())),+ expansion_lower,+ }+ }+}++impl PatternLinter for InitialismLinter {+ fn pattern(&self) -> &dyn Pattern {+ self.pattern.as_ref()+ }++ fn match_to_lint(&self, matched_tokens: &[Token], source: &[char]) -> Option<Lint> {+ let tok = matched_tokens.first()?;+ let source = tok.span.get_content(source);++ let caps = source+ .iter()+ .map(char::is_ascii_uppercase)+ .chain([false].into_iter().cycle());++ let mut expansion_lower = self.expansion_lower.to_owned();++ for (word, cap) in expansion_lower.iter_mut().zip(caps) {+ word[0] = if cap {+ word[0].to_ascii_uppercase()+ } else {+ word[0].to_ascii_lowercase()+ }+ }++ let phrase = Itertools::intersperse_with(expansion_lower.into_iter(), || vec![' '])+ .reduce(|mut left, mut right| {+ left.append(&mut right);+ left+ })+ .unwrap();++ Some(Lint {+ span: tok.span,+ lint_kind: LintKind::Miscellaneous,+ suggestions: vec![Suggestion::ReplaceWith(phrase)],+ message: "Try expanding this initialism.".to_owned(),+ priority: 127,+ })+ }++ fn description(&self) -> &'static str {+ "Expands an initialism."+ }+}++#[cfg(test)]+mod tests {+ use super::InitialismLinter;+}diff --git a/harper-core/src/linting/initialisms.rs b/harper-core/src/linting/initialisms.rsnew file mode 100644index 000000000..ac1d9681b--- /dev/null+++ b/harper-core/src/linting/initialisms.rs@@ -0,0 +1,111 @@+use crate::linting::LintGroup;++use super::InitialismLinter;++pub fn lint_group() -> LintGroup {+ let mut group = LintGroup::empty();++ macro_rules! add_initialism_mappings {+ ($group:expr, { $($name:expr => ($initialism:expr, $expanded:expr)),+ $(,)? }) => {+ $(+ $group.add_pattern_linter(+ $name,+ Box::new(InitialismLinter::new($initialism, $expanded)),+ );+ )++ };+ }++ add_initialism_mappings!(group, {+ "ByTheWay" => ("btw", "by the way"),+ "ForYourInformation" => ("fyi", "for your information"),+ "AsSoonAsPossible" => ("asap", "as soon as possible"),+ "InMyOpinion" => ("imo", "in my opinion"),+ "InMyHumbleOpinion" => ("imho", "in my humble opinion"),+ "OhMyGod" => ("omg", "oh my god"),+ "BeRightBack" => ("brb", "be right back"),+ "TalkToYouLater" => ("ttyl", "talk to you later"),+ "NeverMind" => ("nvm", "never mind"),+ "ToBeHonest" => ("tbh", "to be honest"),+ "AsFarAsIKnow" => ("afaik", "as far as I know"),+ });++ group.set_all_rules_to(Some(true));++ group+}++#[cfg(test)]+mod tests {+ use crate::linting::tests::assert_suggestion_result;++ use super::lint_group;++ #[test]+ fn corrects_btw() {+ assert_suggestion_result(+ "Btw, are you ready to go shopping soon?",+ lint_group(),+ "By the way, are you ready to go shopping soon?",+ );+ }++ #[test]+ fn corrects_style() {+ assert_suggestion_result(+ "I love the fit, btw.",+ lint_group(),+ "I love the fit, by the way.",+ );+ }++ #[test]+ fn corrects_fyi() {+ assert_suggestion_result(+ "Fyi, the meeting is at 3.",+ lint_group(),+ "For your information, the meeting is at 3.",+ );+ }++ #[test]+ fn corrects_asap() {+ assert_suggestion_result(+ "Please respond asap.",+ lint_group(),+ "Please respond as soon as possible.",+ );+ }++ #[test]+ fn corrects_imo() {+ assert_suggestion_result(+ "Imo, that is the best option.",+ lint_group(),+ "In my opinion, that is the best option.",+ );+ }++ #[test]+ fn corrects_omg() {+ assert_suggestion_result(+ "Omg! That's incredible!",+ lint_group(),+ "Oh my god! That's incredible!",+ );+ }++ #[test]+ fn corrects_brb() {+ assert_suggestion_result("Hold on, brb.", lint_group(), "Hold on, be right back.");+ }++ #[test]+ fn corrects_tbh() {+ assert_suggestion_result(+ "Tbh, I'm not impressed.",+ lint_group(),+ "To be honest, I'm not impressed.",+ );+ }+}diff --git a/harper-core/src/linting/lint_group.rs b/harper-core/src/linting/lint_group.rsindex 95ec829ea..1dfe9c61d 100644--- a/harper-core/src/linting/lint_group.rs+++ b/harper-core/src/linting/lint_group.rs@@ -91,7 +91,7 @@ use super::{CurrencyPlacement, HtmlDescriptionLinter, Linter, NoOxfordComma, Oxfuse super::{Lint, PatternLinter};use crate::linting::dashes::Dashes;use crate::linting::open_compounds::OpenCompounds;-use crate::linting::{closed_compounds, phrase_corrections};+use crate::linting::{closed_compounds, initialisms, phrase_corrections};use crate::{CharString, Dialect, Document, TokenStringExt};use crate::{Dictionary, MutableDictionary};@@ -337,6 +337,7 @@ impl LintGroup {dictionary.clone(),));out.merge_from(&mut closed_compounds::lint_group());+ out.merge_from(&mut initialisms::lint_group());// Add all the more complex rules to the group.insert_pattern_rule!(APart, true);diff --git a/harper-core/src/linting/mod.rs b/harper-core/src/linting/mod.rsindex 69c9dc628..eafa1bbc2 100644--- a/harper-core/src/linting/mod.rs+++ b/harper-core/src/linting/mod.rs@@ -34,6 +34,8 @@ mod hop_hope;mod how_to;mod hyphenate_number_day;mod inflected_verb_after_to;+mod initialism_linter;+mod initialisms;mod it_is;mod it_would_be;mod its_contraction;@@ -123,6 +125,7 @@ pub use hop_hope::HopHope;pub use how_to::HowTo;pub use hyphenate_number_day::HyphenateNumberDay;pub use inflected_verb_after_to::InflectedVerbAfterTo;+pub use initialism_linter::InitialismLinter;pub use its_contraction::ItsContraction;pub use left_right_hand::LeftRightHand;pub use lets_confusion::LetsConfusion;diff --git a/harper-core/src/patterns/word.rs b/harper-core/src/patterns/word.rsindex 03a18c5d5..930664f33 100644--- a/harper-core/src/patterns/word.rs+++ b/harper-core/src/patterns/word.rs@@ -27,6 +27,11 @@ impl Word {}}+ /// Matches the provided word, ignoring case.+ pub fn from_char_string(word: CharString) -> Self {+ Self { word, exact: false }+ }+/// Matches the provided word, case-sensitive.pub fn new_exact(word: &'static str) -> Self {Self {