Skip to main content

dateoxide_core/
search.rs

1use crate::get_date_data;
2use crate::locale::{fold_diacritics, normalize_digits_and_lower, LocaleRegistry};
3use crate::settings::{ParsedDateTime, Period, Settings};
4use crate::time_spans;
5use crate::timezone::finalize_datetime;
6
7#[derive(Debug, Clone)]
8pub struct SearchMatch {
9    pub text: String,
10    pub date_obj: ParsedDateTime,
11    pub period: Period,
12    pub locale: Option<String>,
13}
14
15/// Linear-time date finder across free-form text (compatible with `dateparser.search.search_dates`).
16pub fn search_dates(text: &str, settings: &Settings) -> Vec<(String, ParsedDateTime)> {
17    search_dates_full(text, settings)
18        .into_iter()
19        .map(|m| (m.text, m.date_obj))
20        .collect()
21}
22
23/// Linear-time date finder across free-form text including the detected language code.
24pub fn search_dates_with_locale(
25    text: &str,
26    settings: &Settings,
27) -> Vec<(String, ParsedDateTime, Option<String>)> {
28    search_dates_full(text, settings)
29        .into_iter()
30        .map(|m| (m.text, m.date_obj, m.locale))
31        .collect()
32}
33
34/// Full `search_dates` returning matched text, datetime, period, and detected locale.
35pub fn search_dates_full(text: &str, settings: &Settings) -> Vec<SearchMatch> {
36    if text.trim().is_empty() {
37        return Vec::new();
38    }
39
40    if settings.return_time_span {
41        if let Some(span) = time_spans::detect_time_span(text) {
42            let base = settings.effective_base();
43            let num = span.number.unwrap_or(1);
44            if let Some((start_dt, end_dt)) =
45                time_spans::generate_time_span(span.span_type, span.direction, num, base, settings)
46            {
47                let period = match span.span_type {
48                    "week" | "weeks" => Period::Week,
49                    "month" | "months" => Period::Month,
50                    _ => Period::Day,
51                };
52                return vec![
53                    SearchMatch {
54                        text: format!("{} (start)", span.matched_text),
55                        date_obj: finalize_datetime(start_dt, None, settings),
56                        period,
57                        locale: Some("en".to_string()),
58                    },
59                    SearchMatch {
60                        text: format!("{} (end)", span.matched_text),
61                        date_obj: finalize_datetime(end_dt, None, settings),
62                        period,
63                        locale: Some("en".to_string()),
64                    },
65                ];
66            }
67        }
68    }
69
70    let registry = LocaleRegistry::global();
71
72    let spans = collect_word_spans(text);
73    if spans.is_empty() {
74        return Vec::new();
75    }
76
77    let mut kinds = Vec::with_capacity(spans.len());
78    for &(start, end) in &spans {
79        let raw = &text[start..end];
80        let trimmed = raw.trim_matches(|c: char| {
81            matches!(
82                c,
83                ',' | '.' | ';' | '!' | '?' | '(' | ')' | '[' | ']' | '"' | '\'' | '«' | '»'
84            )
85        });
86        kinds.push(classify_token(trimmed, registry, settings.normalize));
87    }
88
89    let mut results = Vec::new();
90    let mut i = 0;
91    while i < spans.len() {
92        if kinds[i] != TokenKind::Signal {
93            i += 1;
94            continue;
95        }
96
97        let mut best_end = i;
98        let mut j = i + 1;
99        while j < spans.len() && (j - i) < 8 {
100            let prev_raw = &text[spans[j - 1].0..spans[j - 1].1];
101            let prev_ends_sentence = prev_raw.ends_with([';', '!', '?'])
102                || (prev_raw.ends_with('.')
103                    && !prev_raw[..prev_raw.len() - 1]
104                        .bytes()
105                        .all(|b| b.is_ascii_digit())
106                    && prev_raw.len() > 4);
107            if prev_ends_sentence {
108                break;
109            }
110
111            match kinds[j] {
112                TokenKind::Signal => {
113                    best_end = j;
114                    j += 1;
115                }
116                TokenKind::Connector => {
117                    if j + 1 < spans.len() && kinds[j + 1] == TokenKind::Signal {
118                        j += 1;
119                    } else {
120                        break;
121                    }
122                }
123                TokenKind::Other => break,
124            }
125        }
126
127        let mut matched = false;
128        for end_idx in (i..=best_end).rev() {
129            let last_tok_lower = normalize_digits_and_lower(
130                text[spans[end_idx].0..spans[end_idx].1]
131                    .trim_matches(|c: char| matches!(c, ',' | '.' | ';' | '!' | '?' | '(' | ')')),
132            );
133            if matches!(
134                last_tok_lower.as_str(),
135                "in" | "at" | "on" | "of" | "the" | "de" | "del" | "el" | "la" | "le" | "à"
136                    | "am" | "um" | "and" | "ve" | "und" | "et" | "for" | "to" | "a" | "an"
137                    | "vor" | "hace" | "dans" | "en" | "saat"
138            ) {
139                continue;
140            }
141
142            let sub_start = spans[i].0;
143            let sub_end = spans[end_idx].1;
144            let raw_sub = text[sub_start..sub_end].trim_matches(|c: char| {
145                matches!(
146                    c,
147                    ',' | ';' | '!' | '?' | '(' | ')' | '[' | ']' | '"' | '\''
148                )
149            });
150            let raw_sub = raw_sub.trim_end_matches('.');
151
152            if raw_sub.bytes().all(|b| b.is_ascii_digit()) && raw_sub.len() < 4 {
153                continue;
154            }
155            if end_idx == i && !is_valid_single_token_date(raw_sub, registry, settings.normalize) {
156                continue;
157            }
158
159            let dd = get_date_data(raw_sub, settings);
160            if let Some(dt) = dd.date_obj {
161                results.push(SearchMatch {
162                    text: raw_sub.to_string(),
163                    date_obj: dt,
164                    period: dd.period,
165                    locale: dd.locale,
166                });
167                i = end_idx + 1;
168                matched = true;
169                break;
170            }
171        }
172
173        if !matched {
174            i += 1;
175        }
176    }
177
178    results
179}
180
181#[derive(Debug, Clone, Copy, PartialEq, Eq)]
182enum TokenKind {
183    Signal,
184    Connector,
185    Other,
186}
187
188fn collect_word_spans(s: &str) -> Vec<(usize, usize)> {
189    let mut out = Vec::new();
190    let mut start: Option<usize> = None;
191    for (idx, ch) in s.char_indices() {
192        if ch.is_whitespace() {
193            if let Some(st) = start.take() {
194                out.push((st, idx));
195            }
196        } else if start.is_none() {
197            start = Some(idx);
198        }
199    }
200    if let Some(st) = start {
201        out.push((st, s.len()));
202    }
203    out
204}
205
206fn classify_token(tok: &str, registry: &LocaleRegistry, normalize: bool) -> TokenKind {
207    if tok.is_empty() {
208        return TokenKind::Other;
209    }
210
211    if tok.chars().any(|c| {
212        c.is_ascii_digit()
213            || matches!(
214                c,
215                '\u{0660}'..='\u{0669}' | '年' | '月' | '日' | '년' | '월' | '일'
216            )
217    }) {
218        return TokenKind::Signal;
219    }
220
221    let lower = normalize_digits_and_lower(tok);
222
223    if matches!(
224        lower.as_str(),
225        "of" | "the" | "at" | "on" | "de" | "del" | "el" | "la" | "le" | "à" | "am" | "um"
226            | "saat" | "and" | "ve" | "und" | "et" | "il" | "y" | "a" | "an" | "in" | "en"
227            | "dans" | "vor" | "hace"
228    ) {
229        if matches!(
230            lower.as_str(),
231            "in" | "vor" | "hace" | "dans" | "il" | "a" | "an" | "en"
232        ) {
233            return TokenKind::Signal;
234        }
235        return TokenKind::Connector;
236    }
237
238    if registry.known_date_tokens.contains(&lower) {
239        return TokenKind::Signal;
240    }
241    if normalize {
242        let folded = fold_diacritics(&lower);
243        if registry.known_date_tokens.contains(&folded) {
244            return TokenKind::Signal;
245        }
246    }
247
248    if tok.len() >= 3
249        && tok.len() <= 5
250        && tok.bytes().all(|b| b.is_ascii_uppercase())
251        && crate::timezone::parse_tz_spec(tok).is_some()
252    {
253        return TokenKind::Signal;
254    }
255
256    if matches!(
257        lower.as_str(),
258        "last" | "next" | "this" | "geçen" | "gecen" | "gelecek" | "bu" | "bir" | "iki" | "üç"
259            | "one" | "two" | "three" | "four" | "five" | "zwei" | "drei" | "ein" | "une"
260            | "deux" | "tonight" | "anoche" | "noon" | "midnight"
261    ) {
262        return TokenKind::Signal;
263    }
264
265    TokenKind::Other
266}
267
268fn is_valid_single_token_date(tok: &str, registry: &LocaleRegistry, normalize: bool) -> bool {
269    if tok.contains(['-', '/', '.', ':', '年', '月', '日', '년', '월', '일'])
270        && tok.chars().any(|c| c.is_ascii_digit())
271    {
272        return true;
273    }
274    if tok.len() == 4 && tok.bytes().all(|b| b.is_ascii_digit()) {
275        if let Ok(y) = tok.parse::<u32>() {
276            return (1900..=2100).contains(&y);
277        }
278    }
279    let lower = normalize_digits_and_lower(tok);
280    if registry.exact_phrase_index.contains_key(&lower)
281        || matches!(lower.as_str(), "tonight" | "anoche")
282    {
283        return true;
284    }
285    if normalize {
286        let folded = fold_diacritics(&lower);
287        if registry.folded_exact_phrase_index.contains_key(&folded) {
288            return true;
289        }
290    }
291    false
292}