Offline, privacy-first grammar checker. Fast, open-source, Rust-powered
feat: censor swear words (#1783)
Andrew Dunbar45543a3485f2
diff --git a/harper-core/dictionary.dict b/harper-core/dictionary.dictindex cb1edf26a..a2589e7ea 100644--- a/harper-core/dictionary.dict+++ b/harper-core/dictionary.dict@@ -12727,6 +12727,7 @@ ape/~NVJdSgGapelike/Japeritif/NgSaperture/~NSg+apeshit/Jxapex/~NgSaphasia/Ngaphasic/JNgS@@ -21322,6 +21323,7 @@ dipped/~VJdipper/NSgdipping/~VNdippy/J>^+dipshit/NSgxdipso/NSdipsomania/Nmgdipsomaniac/NgS@@ -25752,11 +25754,12 @@ ftp/~JNOVZGSfuchsia/NJgSfuck/~VNSgGd>Zxfucker/NgxS-fuckhead/NSx+fuckhead/NSgx+fuckwit/NSgxfuddle/VNdSgG-fudge/~NVdSgG+fudge/~NwVdSgGfuehrer/NgS-fuel/~NVrdGS+fuel/~NwVrdGSfuel'sfuelled/Vr!@_fuelling/VNr!@_@@ -48628,7 +48631,7 @@ tirelessness/Ngtiresome/JpYtiresomeness/Ngtissue/~NwVSg-tit/~NVSg+tit/~NVSgxtitan/~NSgtitanic/~Jtitanium/~Nmg@@ -48652,7 +48655,7 @@ titmouse/Ngtitration/NgStitter/VNSGgdtittle/NVSg-titty/NS+titty/NSxtitular/~JNtizz/Ntizzy/NSgdiff --git a/harper-core/src/expr/sequence_expr.rs b/harper-core/src/expr/sequence_expr.rsindex cc1adb365..2bc57acd4 100644--- a/harper-core/src/expr/sequence_expr.rs+++ b/harper-core/src/expr/sequence_expr.rs@@ -300,8 +300,11 @@ impl SequenceExpr {})}+ // Word property matching methods+// Out-of-vocabulary word. (Words not in the dictionary)gen_then_from_is!(oov);+ gen_then_from_is!(swear);// Part-of-speech matching methodsdiff --git a/harper-core/src/linting/avoid_curses.rs b/harper-core/src/linting/avoid_curses.rsindex 717327c8c..85c5cad3e 100644--- a/harper-core/src/linting/avoid_curses.rs+++ b/harper-core/src/linting/avoid_curses.rs@@ -1,36 +1,295 @@-use super::{Lint, LintKind, Linter};-use crate::{Document, TokenStringExt};--#[derive(Debug, Default)]-pub struct AvoidCurses;--impl Linter for AvoidCurses {- fn lint(&mut self, document: &Document) -> Vec<Lint> {- document- .iter_words()- .filter(|t| t.kind.is_swear())- .map(|t| Lint {- span: t.span,- lint_kind: LintKind::Miscellaneous,- suggestions: vec![],- message: "Try to avoid offensive language.".to_string(),- priority: 63,+use crate::Token;+use crate::expr::{Expr, SequenceExpr};+use crate::linting::{LintKind, Suggestion};++use super::{ExprLinter, Lint};++pub struct AvoidCurses {+ expr: Box<dyn Expr>,+}++impl Default for AvoidCurses {+ fn default() -> Self {+ Self {+ expr: Box::new(SequenceExpr::default().then_swear()),+ }+ }+}++impl ExprLinter for AvoidCurses {+ fn expr(&self) -> &dyn Expr {+ self.expr.as_ref()+ }++ fn match_to_lint(&self, toks: &[Token], src: &[char]) -> Option<Lint> {+ if toks.len() != 1 {+ return None;+ }++ let tok = &toks[0];+ let span = tok.span;+ let bad_word_chars = span.get_content(src);+ let bad_word_str = span.get_content_string(src);+ let bad_word_norm = bad_word_str.to_lowercase();++ // Define offensive morphemes which are common parts of multiple words+ // Each entry maps a morpheme to an optional censored version.+ const MORPHEMES: &[(&str, Option<&str>)] = &[+ ("arse", None),+ ("ass", Some("a**")),+ ("cock", Some("c**k")),+ ("cunt", Some("c**t")),+ ("dick", Some("d**k")),+ ("fuck", Some("f**k")),+ ("piss", Some("p**s")),+ ("shit", Some("sh*t")),+ ("wank", Some("w**k")),+ ];++ // Define offensive words and their possible replacements+ const WORDS: &[(&str, &[&str])] = &[+ ("apeshit", &["crazy", "mad", "insane", "wild"]),+ (+ "arse",+ &["bum", "buttocks", "backside", "bottom", "rump", "posterior"],+ ),+ (+ "arses",+ &[+ "bums",+ "buttocks",+ "backsides",+ "bottoms",+ "rumps",+ "posteriors",+ ],+ ),+ ("arsed", &["bothered"]),+ ("arsehole", &["bumhole"]),+ (+ "ass",+ &[+ "butt",+ "buttocks",+ "backside",+ "bottom",+ "rump",+ "posterior",+ "tuchus",+ "tush",+ ],+ ),+ (+ "asses",+ &[+ "butts",+ "buttocks",+ "backsides",+ "bottoms",+ "rumps",+ "posteriors",+ "tuchuses",+ "tushes",+ ],+ ),+ ("asshole", &["butthole"]),+ // batshit+ // birdshit+ ("bullshit", &["bullcrap", "bulldust", "lie", "lies"]),+ ("bullshitted", &["bullcrapped", "lied"]),+ ("bullshitting", &["bullcrapping", "lying"]),+ ("bullshitter", &["liar"]),+ // bullshittery+ ("chickenshit", &["gutless", "cowardly"]),+ ("cock", &["pee-pee", "willy", "penis", "phallus", "member"]),+ (+ "cocks",+ &["pee-pees", "willies", "penises", "phalluses", "members"],+ ),+ // cocksucker+ ("cunt", &["vagina"]),+ ("cunts", &["vaginas"]),+ ("dick", &["pee-pee", "penis"]),+ ("dicks", &["pee-pees", "penises"]),+ ("dickhead", &["jerk", "idiot"]),+ ("dichheads", &["jerks", "idiots"]),+ // dipshit+ ("dumbass", &["idiot", "fool"]),+ ("dumbasses", &["idiots", "fools"]),+ ("fart", &["gas", "wind", "break wind"]),+ ("farts", &["gas", "wind", "breaks wind"]),+ ("farted", &["broke wind", "broken wind"]),+ ("farting", &["breaking wind"]),+ ("fuck", &["fudge", "screw", "damn", "hoot"]),+ ("fucks", &["screws"]),+ ("fucked", &["screwed"]),+ ("fucking", &["screwing"]),+ ("fucker", &["jerk"]),+ ("fuckers", &["jerks"]),+ // fuckhead+ ("horseshit", &["nonsense"]),+ // mindfuck+ // motherfucker+ // nigga+ // nigger+ ("piss", &["pee", "urine", "urinate"]),+ ("pisses", &["pees", "urinates"]),+ ("pissed", &["peed", "urinated"]),+ ("pissing", &["peeing", "urinating"]),+ ("pisser", &["toilet", "bathroom", "restroom", "washroom"]),+ // pissy+ (+ "shit",+ &["crap", "poo", "poop", "feces", "dung", "damn", "hoot"],+ ),+ ("shits", &["craps", "poos", "poops"]),+ ("shitted", &["crapped", "pooed", "pooped"]),+ ("shitting", &["crapping", "pooing", "pooping"]),+ // shitcoin+ // shitfaced+ // shitfest+ // shithead+ ("shitless", &["witless"]),+ (+ "shitload",+ &["crapload", "shedload", "shirtload", "load", "tons", "pile"],+ ),+ (+ "shitloads",+ &[+ "craploads",+ "shedloads",+ "shirtloads",+ "loads",+ "tons",+ "piles",+ ],+ ),+ // shitpost+ ("shitty", &["shirty", "crappy", "inferior"]),+ ("shittier", &["crappier", "shirtier"]),+ ("shittiest", &["crappiest", "shirtiest"]),+ ("tit", &["boob", "breast"]),+ ("tits", &["boobs", "breasts"]),+ ("titty", &["boob", "breast"]),+ ("titties", &["boobs", "breasts"]),+ ("turd", &["poo", "poop", "feces", "dung"]),+ ("turds", &["poos", "poops", "feces", "dung"]),+ ("twat", &["vagina"]),+ // wank+ ("wanker", &["jerk"]),+ // wanky+ ("whore", &["prostitute"]),+ ];++ // Replace common morphemes with both specific censored versions and all-asterisk versions+ let morpheme_replacements: Vec<String> = MORPHEMES+ .iter()+ .filter(|(m, _)| bad_word_norm.contains(m))+ .flat_map(|(m, censored)| {+ let mut replacements = Vec::new();++ // Add all-asterisk version for the censored morpheme only+ let asterisked = "*".repeat(m.len());+ let asterisked_word = bad_word_norm.replace(m, &asterisked);+ replacements.push(asterisked_word);++ // Add specific censored version if it exists+ if let Some(c) = censored {+ let censored_word = bad_word_norm.replace(m, c);+ replacements.push(censored_word);+ }++ replacements+ })+ .collect();++ // Find all replacement suggestions for the bad word+ let word_replacements: Vec<&str> = WORDS+ .iter()+ .filter(|(bad, _)| *bad == bad_word_norm)+ .flat_map(|(_, suggestions)| suggestions.iter().copied())+ .collect();++ if morpheme_replacements.is_empty() && word_replacements.is_empty() {+ return None;+ }++ let m_suggestions: Vec<Suggestion> = morpheme_replacements+ .into_iter()+ .map(|replacement| {+ Suggestion::replace_with_match_case(replacement.chars().collect(), bad_word_chars)+ })+ .collect();++ let w_suggestions: Vec<Suggestion> = word_replacements+ .into_iter()+ .map(|replacement| {+ Suggestion::replace_with_match_case(replacement.chars().collect(), bad_word_chars)})- .collect()+ .collect();++ let suggestions = m_suggestions.into_iter().chain(w_suggestions).collect();++ Some(Lint {+ span,+ lint_kind: LintKind::WordChoice,+ suggestions,+ message: "Try to avoid offensive language.".to_string(),+ ..Default::default()+ })}fn description(&self) -> &'static str {- "A rule that looks for common offensive language."+ "Flags offensive language and offers various ways to censor or replace with euphemisms."}}#[cfg(test)]mod tests {use super::AvoidCurses;- use crate::linting::tests::assert_lint_count;+ use crate::linting::tests::{assert_lint_count, assert_top3_suggestion_result};#[test]fn detects_shit() {- assert_lint_count("He ate shit when he fell off the bike.", AvoidCurses, 1);+ assert_lint_count(+ "He ate shit when he fell off the bike.",+ AvoidCurses::default(),+ 1,+ );+ }++ #[test]+ fn fix_shit() {+ assert_top3_suggestion_result("shit", AvoidCurses::default(), "crap")+ }++ #[test]+ fn fix_shit_titlecase() {+ assert_top3_suggestion_result("Shit", AvoidCurses::default(), "Crap")+ }++ #[test]+ fn fix_shit_allcaps() {+ assert_top3_suggestion_result("SHIT", AvoidCurses::default(), "CRAP")+ }++ #[test]+ fn fix_f_word_to_all_asterisks() {+ assert_top3_suggestion_result(+ "fuck those fucking fuckers",+ AvoidCurses::default(),+ "**** those ****ing ****ers",+ )+ }++ #[test]+ fn fix_shit_with_single_asterisk() {+ assert_top3_suggestion_result("shit", AvoidCurses::default(), "sh*t")+ }++ #[test]+ fn fix_shite_all_caps_with_single_asterisk() {+ assert_top3_suggestion_result("SHIT", AvoidCurses::default(), "SH*T")}}diff --git a/harper-core/src/linting/lint_group.rs b/harper-core/src/linting/lint_group.rsindex fb9f2d5e1..e109ff5e5 100644--- a/harper-core/src/linting/lint_group.rs+++ b/harper-core/src/linting/lint_group.rs@@ -409,7 +409,7 @@ impl LintGroup {insert_expr_rule!(AnotherThingComing, true);insert_expr_rule!(AnotherThinkComing, false);insert_expr_rule!(AskNoPreposition, true);- insert_struct_rule!(AvoidCurses, true);+ insert_expr_rule!(AvoidCurses, true);insert_expr_rule!(BackInTheDay, true);insert_expr_rule!(BestOfAllTime, true);insert_expr_rule!(BoringWords, false);diff --git a/harper-core/tests/text/linters/Swear.snap.yml b/harper-core/tests/text/linters/Swear.snap.ymlindex e8ee7bb31..482a9e8ff 100644--- a/harper-core/tests/text/linters/Swear.snap.yml+++ b/harper-core/tests/text/linters/Swear.snap.yml@@ -1,42 +1,65 @@-Lint: Miscellaneous (63 priority)+Lint: WordChoice (127 priority)Message: |7 | One turd, two turds.| ^~~~ Try to avoid offensive language.+Suggest:+ - Replace with: “poo”+ - Replace with: “poop”+ - Replace with: “feces”+ - Replace with: “dung”-Lint: Miscellaneous (63 priority)+Lint: WordChoice (127 priority)Message: |7 | One turd, two turds.| ^~~~~ Try to avoid offensive language.+Suggest:+ - Replace with: “poos”+ - Replace with: “poops”+ - Replace with: “feces”+ - Replace with: “dung”-Lint: Miscellaneous (63 priority)+Lint: WordChoice (127 priority)Message: |9 | I fart, you're farting, he farts, she farted.| ^~~~ Try to avoid offensive language.+Suggest:+ - Replace with: “gas”+ - Replace with: “wind”+ - Replace with: “break wind”-Lint: Miscellaneous (63 priority)+Lint: WordChoice (127 priority)Message: |9 | I fart, you're farting, he farts, she farted.| ^~~~~~~ Try to avoid offensive language.+Suggest:+ - Replace with: “breaking wind”-Lint: Miscellaneous (63 priority)+Lint: WordChoice (127 priority)Message: |9 | I fart, you're farting, he farts, she farted.| ^~~~~ Try to avoid offensive language.+Suggest:+ - Replace with: “gas”+ - Replace with: “wind”+ - Replace with: “breaks wind”-Lint: Miscellaneous (63 priority)+Lint: WordChoice (127 priority)Message: |9 | I fart, you're farting, he farts, she farted.| ^~~~~~ Try to avoid offensive language.+Suggest:+ - Replace with: “broke wind”+ - Replace with: “broken wind”