on master help sign in
Add support for time and more date formats
commit37e484ee38eb5a9b4da280960fb1e29939ee9d39 authorJason Rodney Hansen <jasonrodneyhansen@gmail.com> dateThu 25 Nov 2021, 19:58 (5 years ago) parentc9641fc
4 files changed+518−477
helix-core/src/increment/date.rs−474 helix-core/src/increment/date_time.rs+515 helix-core/src/increment/mod.rs+1−1 helix-term/src/commands.rs+2−2
helix-core/src/increment/date.rsdeleted−474
@@ -1,474 +0,0 @@
1−use regex::Regex;
2−
3−use std::borrow::Cow;
4−use std::cmp;
5−
6−use ropey::RopeSlice;
7−
8−use crate::{Range, Tendril};
9−
10−use chrono::{Datelike, Duration, NaiveDate};
11−
12−use super::Increment;
13−
14−fn ndays_in_month(year: i32, month: u32) -> u32 {
15− // The first day of the next month...
16− let (y, m) = if month == 12 {
17− (year + 1, 1)
18− } else {
19− (year, month + 1)
20− };
21− let d = NaiveDate::from_ymd(y, m, 1);
22−
23− // ...is preceded by the last day of the original month.
24− d.pred().day()
25−}
26−
27−fn add_days(date: NaiveDate, amount: i64) -> Option<NaiveDate> {
28− date.checked_add_signed(Duration::days(amount))
29−}
30−
31−fn add_months(date: NaiveDate, amount: i64) -> Option<NaiveDate> {
32− let month = date.month0() as i64 + amount;
33− let year = date.year() + i32::try_from(month / 12).ok()?;
34− let year = if month.is_negative() { year - 1 } else { year };
35−
36− // Normalize month
37− let month = month % 12;
38− let month = if month.is_negative() {
39− month + 13
40− } else {
41− month + 1
42− } as u32;
43−
44− let day = cmp::min(date.day(), ndays_in_month(year, month));
45−
46− Some(NaiveDate::from_ymd(year, month, day))
47−}
48−
49−fn add_years(date: NaiveDate, amount: i64) -> Option<NaiveDate> {
50− let year = i32::try_from(date.year() as i64 + amount).ok()?;
51− let ndays = ndays_in_month(year, date.month());
52−
53− if date.day() > ndays {
54− let d = NaiveDate::from_ymd(year, date.month(), ndays);
55− Some(d.succ())
56− } else {
57− date.with_year(year)
58− }
59−}
60−
61−#[derive(Copy, Clone, Debug, PartialEq, Eq)]
62−struct Format {
63− regex: &'static str,
64− separator: char,
65−}
66−
67−// Only support formats that aren't region specific.
68−static FORMATS: &[Format] = &[
69− Format {
70− regex: r"(\d{4})-(\d{2})-(\d{2})",
71− separator: '-',
72− },
73− Format {
74− regex: r"(\d{4})/(\d{2})/(\d{2})",
75− separator: '/',
76− },
77−];
78−
79−const DATE_LENGTH: usize = 10;
80−
81−#[derive(Copy, Clone, Debug, PartialEq, Eq)]
82−enum DateField {
83− Year,
84− Month,
85− Day,
86−}
87−
88−#[derive(Debug, PartialEq, Eq)]
89−pub struct DateIncrementor {
90− date: NaiveDate,
91− range: Range,
92− field: DateField,
93− format: Format,
94−}
95−
96−impl DateIncrementor {
97− pub fn from_range(text: RopeSlice, range: Range) -> Option<DateIncrementor> {
98− let range = if range.is_empty() {
99− if range.anchor < text.len_bytes() {
100− // Treat empty range as a cursor range.
101− range.put_cursor(text, range.anchor + 1, true)
102− } else {
103− // The range is empty and at the end of the text.
104− return None;
105− }
106− } else {
107− range
108− };
109−
110− let from = range.from().saturating_sub(DATE_LENGTH);
111− let to = (range.from() + DATE_LENGTH).min(text.len_chars());
112−
113− let (from_in_text, to_in_text) = (range.from() - from, range.to() - from);
114− let text: Cow<str> = text.slice(from..to).into();
115−
116− FORMATS.iter().find_map(|&format| {
117− let re = Regex::new(format.regex).ok()?;
118− let captures = re.captures(&text)?;
119−
120− let date = captures.get(0)?;
121− let offset = range.from() - from_in_text;
122− let range = Range::new(date.start() + offset, date.end() + offset);
123−
124− let (year, month, day) = (captures.get(1)?, captures.get(2)?, captures.get(3)?);
125− let (year_range, month_range, day_range) = (year.range(), month.range(), day.range());
126−
127− let field = if year_range.contains(&from_in_text)
128− && year_range.contains(&(to_in_text - 1))
129− {
130− DateField::Year
131− } else if month_range.contains(&from_in_text) && month_range.contains(&(to_in_text - 1))
132− {
133− DateField::Month
134− } else if day_range.contains(&from_in_text) && day_range.contains(&(to_in_text - 1)) {
135− DateField::Day
136− } else {
137− return None;
138− };
139−
140− let date = NaiveDate::from_ymd_opt(
141− year.as_str().parse::<i32>().ok()?,
142− month.as_str().parse::<u32>().ok()?,
143− day.as_str().parse::<u32>().ok()?,
144− )?;
145−
146− Some(DateIncrementor {
147− date,
148− field,
149− range,
150− format,
151− })
152− })
153− }
154−}
155−
156−impl Increment for DateIncrementor {
157− fn increment(&self, amount: i64) -> (Range, Tendril) {
158− let date = match self.field {
159− DateField::Year => add_years(self.date, amount),
160− DateField::Month => add_months(self.date, amount),
161− DateField::Day => add_days(self.date, amount),
162− }
163− .unwrap_or(self.date);
164−
165− (
166− self.range,
167− format!(
168− "{:04}{}{:02}{}{:02}",
169− date.year(),
170− self.format.separator,
171− date.month(),
172− self.format.separator,
173− date.day()
174− )
175− .into(),
176− )
177− }
178−}
179−
180−#[cfg(test)]
181−mod test {
182− use super::*;
183− use crate::Rope;
184−
185− #[test]
186− fn test_create_incrementor_for_year_with_dashes() {
187− let rope = Rope::from_str("2021-11-15");
188−
189− for cursor in 0..=3 {
190− let range = Range::new(cursor, cursor + 1);
191− assert_eq!(
192− DateIncrementor::from_range(rope.slice(..), range),
193− Some(DateIncrementor {
194− date: NaiveDate::from_ymd(2021, 11, 15),
195− range: Range::new(0, 10),
196− field: DateField::Year,
197− format: FORMATS[0],
198− })
199− );
200− }
201− }
202−
203− #[test]
204− fn test_create_incrementor_for_month_with_dashes() {
205− let rope = Rope::from_str("2021-11-15");
206−
207− for cursor in 5..=6 {
208− let range = Range::new(cursor, cursor + 1);
209− assert_eq!(
210− DateIncrementor::from_range(rope.slice(..), range),
211− Some(DateIncrementor {
212− date: NaiveDate::from_ymd(2021, 11, 15),
213− range: Range::new(0, 10),
214− field: DateField::Month,
215− format: FORMATS[0],
216− })
217− );
218− }
219− }
220−
221− #[test]
222− fn test_create_incrementor_for_day_with_dashes() {
223− let rope = Rope::from_str("2021-11-15");
224−
225− for cursor in 8..=9 {
226− let range = Range::new(cursor, cursor + 1);
227− assert_eq!(
228− DateIncrementor::from_range(rope.slice(..), range),
229− Some(DateIncrementor {
230− date: NaiveDate::from_ymd(2021, 11, 15),
231− range: Range::new(0, 10),
232− field: DateField::Day,
233− format: FORMATS[0],
234− })
235− );
236− }
237− }
238−
239− #[test]
240− fn test_try_create_incrementor_on_dashes() {
241− let rope = Rope::from_str("2021-11-15");
242−
243− for &cursor in &[4, 7] {
244− let range = Range::new(cursor, cursor + 1);
245− assert_eq!(DateIncrementor::from_range(rope.slice(..), range), None,);
246− }
247− }
248−
249− #[test]
250− fn test_create_incrementor_for_year_with_slashes() {
251− let rope = Rope::from_str("2021/11/15");
252−
253− for cursor in 0..=3 {
254− let range = Range::new(cursor, cursor + 1);
255− assert_eq!(
256− DateIncrementor::from_range(rope.slice(..), range),
257− Some(DateIncrementor {
258− date: NaiveDate::from_ymd(2021, 11, 15),
259− range: Range::new(0, 10),
260− field: DateField::Year,
261− format: FORMATS[1],
262− })
263− );
264− }
265− }
266−
267− #[test]
268− fn test_create_incrementor_for_month_with_slashes() {
269− let rope = Rope::from_str("2021/11/15");
270−
271− for cursor in 5..=6 {
272− let range = Range::new(cursor, cursor + 1);
273− assert_eq!(
274− DateIncrementor::from_range(rope.slice(..), range),
275− Some(DateIncrementor {
276− date: NaiveDate::from_ymd(2021, 11, 15),
277− range: Range::new(0, 10),
278− field: DateField::Month,
279− format: FORMATS[1],
280− })
281− );
282− }
283− }
284−
285− #[test]
286− fn test_create_incrementor_for_day_with_slashes() {
287− let rope = Rope::from_str("2021/11/15");
288−
289− for cursor in 8..=9 {
290− let range = Range::new(cursor, cursor + 1);
291− assert_eq!(
292− DateIncrementor::from_range(rope.slice(..), range),
293− Some(DateIncrementor {
294− date: NaiveDate::from_ymd(2021, 11, 15),
295− range: Range::new(0, 10),
296− field: DateField::Day,
297− format: FORMATS[1],
298− })
299− );
300− }
301− }
302−
303− #[test]
304− fn test_try_create_incrementor_on_slashes() {
305− let rope = Rope::from_str("2021/11/15");
306−
307− for &cursor in &[4, 7] {
308− let range = Range::new(cursor, cursor + 1);
309− assert_eq!(DateIncrementor::from_range(rope.slice(..), range), None,);
310− }
311− }
312−
313− #[test]
314− fn test_date_surrounded_by_spaces() {
315− let rope = Rope::from_str(" 2021-11-15 ");
316− let range = Range::new(3, 4);
317− assert_eq!(
318− DateIncrementor::from_range(rope.slice(..), range),
319− Some(DateIncrementor {
320− date: NaiveDate::from_ymd(2021, 11, 15),
321− range: Range::new(3, 13),
322− field: DateField::Year,
323− format: FORMATS[0],
324− })
325− );
326− }
327−
328− #[test]
329− fn test_date_in_single_quotes() {
330− let rope = Rope::from_str("date = '2021-11-15'");
331− let range = Range::new(10, 11);
332− assert_eq!(
333− DateIncrementor::from_range(rope.slice(..), range),
334− Some(DateIncrementor {
335− date: NaiveDate::from_ymd(2021, 11, 15),
336− range: Range::new(8, 18),
337− field: DateField::Year,
338− format: FORMATS[0],
339− })
340− );
341− }
342−
343− #[test]
344− fn test_date_in_double_quotes() {
345− let rope = Rope::from_str("let date = \"2021-11-15\";");
346− let range = Range::new(12, 13);
347− assert_eq!(
348− DateIncrementor::from_range(rope.slice(..), range),
349− Some(DateIncrementor {
350− date: NaiveDate::from_ymd(2021, 11, 15),
351− range: Range::new(12, 22),
352− field: DateField::Year,
353− format: FORMATS[0],
354− })
355− );
356− }
357−
358− #[test]
359− fn test_date_cursor_one_right_of_date() {
360− let rope = Rope::from_str("2021-11-15 ");
361− let range = Range::new(10, 11);
362− assert_eq!(DateIncrementor::from_range(rope.slice(..), range), None);
363− }
364−
365− #[test]
366− fn test_date_cursor_one_left_of_number() {
367− let rope = Rope::from_str(" 2021-11-15");
368− let range = Range::new(0, 1);
369− assert_eq!(DateIncrementor::from_range(rope.slice(..), range), None);
370− }
371−
372− #[test]
373− fn test_date_empty_range_at_beginning() {
374− let rope = Rope::from_str("2021-11-15");
375− let range = Range::point(0);
376− assert_eq!(
377− DateIncrementor::from_range(rope.slice(..), range),
378− Some(DateIncrementor {
379− date: NaiveDate::from_ymd(2021, 11, 15),
380− range: Range::new(0, 10),
381− field: DateField::Year,
382− format: FORMATS[0],
383− })
384− );
385− }
386−
387− #[test]
388− fn test_date_empty_range_at_in_middle() {
389− let rope = Rope::from_str("2021-11-15");
390− let range = Range::point(5);
391− assert_eq!(
392− DateIncrementor::from_range(rope.slice(..), range),
393− Some(DateIncrementor {
394− date: NaiveDate::from_ymd(2021, 11, 15),
395− range: Range::new(0, 10),
396− field: DateField::Month,
397− format: FORMATS[0],
398− })
399− );
400− }
401−
402− #[test]
403− fn test_date_empty_range_at_end() {
404− let rope = Rope::from_str("2021-11-15");
405− let range = Range::point(10);
406− assert_eq!(DateIncrementor::from_range(rope.slice(..), range), None);
407− }
408−
409− #[test]
410− fn test_invalid_dates() {
411− let tests = [
412− "0000-00-00",
413− "1980-2-21",
414− "1980-12-1",
415− "12345",
416− "2020-02-30",
417− "1999-12-32",
418− "19-12-32",
419− "1-2-3",
420− "0000/00/00",
421− "1980/2/21",
422− "1980/12/1",
423− "12345",
424− "2020/02/30",
425− "1999/12/32",
426− "19/12/32",
427− "1/2/3",
428− ];
429−
430− for invalid in tests {
431− let rope = Rope::from_str(invalid);
432− let range = Range::new(0, 1);
433−
434− assert_eq!(DateIncrementor::from_range(rope.slice(..), range), None);
435− }
436− }
437−
438− #[test]
439− fn test_increment_dates() {
440− let tests = [
441− // (original, cursor, amount, expected)
442− ("2020-02-28", 0, 1, "2021-02-28"),
443− ("2020-02-29", 0, 1, "2021-03-01"),
444− ("2020-01-31", 5, 1, "2020-02-29"),
445− ("2020-01-20", 5, 1, "2020-02-20"),
446− ("2021-01-01", 5, -1, "2020-12-01"),
447− ("2021-01-31", 5, -2, "2020-11-30"),
448− ("2020-02-28", 8, 1, "2020-02-29"),
449− ("2021-02-28", 8, 1, "2021-03-01"),
450− ("2021-02-28", 0, -1, "2020-02-28"),
451− ("2021-03-01", 0, -1, "2020-03-01"),
452− ("2020-02-29", 5, -1, "2020-01-29"),
453− ("2020-02-20", 5, -1, "2020-01-20"),
454− ("2020-02-29", 8, -1, "2020-02-28"),
455− ("2021-03-01", 8, -1, "2021-02-28"),
456− ("1980/12/21", 8, 100, "1981/03/31"),
457− ("1980/12/21", 8, -100, "1980/09/12"),
458− ("1980/12/21", 8, 1000, "1983/09/17"),
459− ("1980/12/21", 8, -1000, "1978/03/27"),
460− ];
461−
462− for (original, cursor, amount, expected) in tests {
463− let rope = Rope::from_str(original);
464− let range = Range::new(cursor, cursor + 1);
465− assert_eq!(
466− DateIncrementor::from_range(rope.slice(..), range)
467− .unwrap()
468− .increment(amount)
469− .1,
470− expected.into()
471− );
472− }
473− }
474−}
helix-core/src/increment/date_time.rsnew file+515
@@ -0,0 +1,515 @@
1+use chrono::{Datelike, Duration, NaiveDate, NaiveDateTime, NaiveTime, Timelike};
2+use once_cell::sync::Lazy;
3+use regex::Regex;
4+use ropey::RopeSlice;
5+
6+use std::borrow::Cow;
7+use std::cmp;
8+
9+use super::Increment;
10+use crate::{Range, Tendril};
11+
12+#[derive(Debug, PartialEq, Eq)]
13+pub struct DateTimeIncrementor {
14+ date_time: NaiveDateTime,
15+ range: Range,
16+ format: Format,
17+ field: DateField,
18+}
19+
20+impl DateTimeIncrementor {
21+ pub fn from_range(text: RopeSlice, range: Range) -> Option<DateTimeIncrementor> {
22+ let range = if range.is_empty() {
23+ if range.anchor < text.len_chars() {
24+ // Treat empty range as a cursor range.
25+ range.put_cursor(text, range.anchor + 1, true)
26+ } else {
27+ // The range is empty and at the end of the text.
28+ return None;
29+ }
30+ } else {
31+ range
32+ };
33+
34+ FORMATS.iter().find_map(|format| {
35+ let from = range.from().saturating_sub(format.max_len);
36+ let to = (range.from() + format.max_len).min(text.len_chars());
37+
38+ let (from_in_text, to_in_text) = (range.from() - from, range.to() - from);
39+ let text: Cow<str> = text.slice(from..to).into();
40+
41+ let captures = format.regex.captures(&text)?;
42+ if captures.len() - 1 != format.fields.len() {
43+ return None;
44+ }
45+
46+ let date_time = captures.get(0)?;
47+ let offset = range.from() - from_in_text;
48+ let range = Range::new(date_time.start() + offset, date_time.end() + offset);
49+
50+ let field = captures
51+ .iter()
52+ .skip(1)
53+ .enumerate()
54+ .find_map(|(i, capture)| {
55+ let capture = capture?;
56+ let capture_range = capture.range();
57+
58+ if capture_range.contains(&from_in_text)
59+ && capture_range.contains(&(to_in_text - 1))
60+ {
61+ Some(format.fields[i])
62+ } else {
63+ None
64+ }
65+ })?;
66+
67+ let has_date = format.fields.iter().any(|f| f.unit.is_date());
68+ let has_time = format.fields.iter().any(|f| f.unit.is_time());
69+
70+ let date_time = match (has_date, has_time) {
71+ (true, true) => NaiveDateTime::parse_from_str(
72+ &text[date_time.start()..date_time.end()],
73+ format.fmt,
74+ )
75+ .ok()?,
76+ (true, false) => {
77+ let date = NaiveDate::parse_from_str(
78+ &text[date_time.start()..date_time.end()],
79+ format.fmt,
80+ )
81+ .ok()?;
82+
83+ date.and_hms(0, 0, 0)
84+ }
85+ (false, true) => {
86+ let time = NaiveTime::parse_from_str(
87+ &text[date_time.start()..date_time.end()],
88+ format.fmt,
89+ )
90+ .ok()?;
91+
92+ NaiveDate::from_ymd(0, 1, 1).and_time(time)
93+ }
94+ (false, false) => return None,
95+ };
96+
97+ Some(DateTimeIncrementor {
98+ date_time,
99+ range,
100+ format: format.clone(),
101+ field,
102+ })
103+ })
104+ }
105+}
106+
107+impl Increment for DateTimeIncrementor {
108+ fn increment(&self, amount: i64) -> (Range, Tendril) {
109+ let date_time = match self.field.unit {
110+ DateUnit::Years => add_years(self.date_time, amount),
111+ DateUnit::Months => add_months(self.date_time, amount),
112+ DateUnit::Days => add_duration(self.date_time, Duration::days(amount)),
113+ DateUnit::Hours => add_duration(self.date_time, Duration::hours(amount)),
114+ DateUnit::Minutes => add_duration(self.date_time, Duration::minutes(amount)),
115+ DateUnit::Seconds => add_duration(self.date_time, Duration::seconds(amount)),
116+ DateUnit::AmPm => toggle_am_pm(self.date_time),
117+ }
118+ .unwrap_or(self.date_time);
119+
120+ (
121+ self.range,
122+ date_time.format(self.format.fmt).to_string().into(),
123+ )
124+ }
125+}
126+
127+static FORMATS: Lazy<Vec<Format>> = Lazy::new(|| {
128+ vec![
129+ Format::new("%Y-%m-%d %H:%M:%S"), // 2021-11-24 07:12:23
130+ Format::new("%Y/%m/%d %H:%M:%S"), // 2021/11/24 07:12:23
131+ Format::new("%Y-%m-%d %H:%M"), // 2021-11-24 07:12
132+ Format::new("%Y/%m/%d %H:%M"), // 2021/11/24 07:12
133+ Format::new("%Y-%m-%d"), // 2021-11-24
134+ Format::new("%Y/%m/%d"), // 2021/11/24
135+ Format::new("%a %b %d %Y"), // Wed Nov 24 2021
136+ Format::new("%d-%b-%Y"), // 24-Nov-2021
137+ Format::new("%Y %b %d"), // 2021 Nov 24
138+ Format::new("%b %d, %Y"), // Nov 24, 2021
139+ Format::new("%-I:%M:%S %P"), // 7:21:53 am
140+ Format::new("%-I:%M %P"), // 7:21 am
141+ Format::new("%-I:%M:%S %p"), // 7:21:53 AM
142+ Format::new("%-I:%M %p"), // 7:21 AM
143+ Format::new("%H:%M:%S"), // 23:24:23
144+ Format::new("%H:%M"), // 23:24
145+ ]
146+});
147+
148+#[derive(Clone, Debug)]
149+struct Format {
150+ fmt: &'static str,
151+ fields: Vec<DateField>,
152+ regex: Regex,
153+ max_len: usize,
154+}
155+
156+impl Format {
157+ fn new(fmt: &'static str) -> Self {
158+ let mut remaining = fmt;
159+ let mut fields = Vec::new();
160+ let mut regex = String::new();
161+ let mut max_len = 0;
162+
163+ while let Some(i) = remaining.find('%') {
164+ let mut chars = remaining[i + 1..].chars();
165+ let spec_len = if let Some(c) = chars.next() {
166+ if c == '-' {
167+ if chars.next().is_some() {
168+ 2
169+ } else {
170+ 0
171+ }
172+ } else {
173+ 1
174+ }
175+ } else {
176+ 0
177+ };
178+
179+ if i < remaining.len() - spec_len {
180+ let specifier = &remaining[i + 1..i + 1 + spec_len];
181+ if let Some(field) = DateField::from_specifier(specifier) {
182+ fields.push(field);
183+ max_len += field.max_len + remaining[..i].len();
184+ regex += &remaining[..i];
185+ regex += &format!("({})", field.regex);
186+ remaining = &remaining[i + spec_len + 1..];
187+ } else {
188+ regex += &remaining[..=i];
189+ }
190+ } else {
191+ regex += remaining;
192+ }
193+ }
194+
195+ let regex = Regex::new(&regex).unwrap();
196+
197+ Self {
198+ fmt,
199+ fields,
200+ regex,
201+ max_len,
202+ }
203+ }
204+}
205+
206+impl PartialEq for Format {
207+ fn eq(&self, other: &Self) -> bool {
208+ self.fmt == other.fmt && self.fields == other.fields && self.max_len == other.max_len
209+ }
210+}
211+
212+impl Eq for Format {}
213+
214+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
215+struct DateField {
216+ regex: &'static str,
217+ unit: DateUnit,
218+ max_len: usize,
219+}
220+
221+impl DateField {
222+ fn from_specifier(specifier: &str) -> Option<Self> {
223+ match specifier {
224+ "Y" => Some(DateField {
225+ regex: r"\d{4}",
226+ unit: DateUnit::Years,
227+ max_len: 5,
228+ }),
229+ "y" => Some(DateField {
230+ regex: r"\d\d",
231+ unit: DateUnit::Years,
232+ max_len: 2,
233+ }),
234+ "m" => Some(DateField {
235+ regex: r"[0-1]\d",
236+ unit: DateUnit::Months,
237+ max_len: 2,
238+ }),
239+ "d" => Some(DateField {
240+ regex: r"[0-3]\d",
241+ unit: DateUnit::Days,
242+ max_len: 2,
243+ }),
244+ "-d" => Some(DateField {
245+ regex: r"[1-3]?\d",
246+ unit: DateUnit::Days,
247+ max_len: 2,
248+ }),
249+ "a" => Some(DateField {
250+ regex: r"Sun|Mon|Tue|Wed|Thu|Fri|Sat",
251+ unit: DateUnit::Days,
252+ max_len: 3,
253+ }),
254+ "A" => Some(DateField {
255+ regex: r"Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday",
256+ unit: DateUnit::Days,
257+ max_len: 9,
258+ }),
259+ "b" | "h" => Some(DateField {
260+ regex: r"Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec",
261+ unit: DateUnit::Months,
262+ max_len: 3,
263+ }),
264+ "B" => Some(DateField {
265+ regex: r"January|February|March|April|May|June|July|August|September|October|November|December",
266+ unit: DateUnit::Months,
267+ max_len: 9,
268+ }),
269+ "H" => Some(DateField {
270+ regex: r"[0-2]\d",
271+ unit: DateUnit::Hours,
272+ max_len: 2,
273+ }),
274+ "M" => Some(DateField {
275+ regex: r"[0-5]\d",
276+ unit: DateUnit::Minutes,
277+ max_len: 2,
278+ }),
279+ "S" => Some(DateField {
280+ regex: r"[0-5]\d",
281+ unit: DateUnit::Seconds,
282+ max_len: 2,
283+ }),
284+ "I" => Some(DateField {
285+ regex: r"[0-1]\d",
286+ unit: DateUnit::Hours,
287+ max_len: 2,
288+ }),
289+ "-I" => Some(DateField {
290+ regex: r"1?\d",
291+ unit: DateUnit::Hours,
292+ max_len: 2,
293+ }),
294+ "P" => Some(DateField {
295+ regex: r"am|pm",
296+ unit: DateUnit::AmPm,
297+ max_len: 2,
298+ }),
299+ "p" => Some(DateField {
300+ regex: r"AM|PM",
301+ unit: DateUnit::AmPm,
302+ max_len: 2,
303+ }),
304+ _ => None,
305+ }
306+ }
307+}
308+
309+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
310+enum DateUnit {
311+ Years,
312+ Months,
313+ Days,
314+ Hours,
315+ Minutes,
316+ Seconds,
317+ AmPm,
318+}
319+
320+impl DateUnit {
321+ fn is_date(self) -> bool {
322+ matches!(self, DateUnit::Years | DateUnit::Months | DateUnit::Days)
323+ }
324+
325+ fn is_time(self) -> bool {
326+ matches!(
327+ self,
328+ DateUnit::Hours | DateUnit::Minutes | DateUnit::Seconds
329+ )
330+ }
331+}
332+
333+fn ndays_in_month(year: i32, month: u32) -> u32 {
334+ // The first day of the next month...
335+ let (y, m) = if month == 12 {
336+ (year + 1, 1)
337+ } else {
338+ (year, month + 1)
339+ };
340+ let d = NaiveDate::from_ymd(y, m, 1);
341+
342+ // ...is preceded by the last day of the original month.
343+ d.pred().day()
344+}
345+
346+fn add_months(date_time: NaiveDateTime, amount: i64) -> Option<NaiveDateTime> {
347+ let month = date_time.month0() as i64 + amount;
348+ let year = date_time.year() + i32::try_from(month / 12).ok()?;
349+ let year = if month.is_negative() { year - 1 } else { year };
350+
351+ // Normalize month
352+ let month = month % 12;
353+ let month = if month.is_negative() {
354+ month + 13
355+ } else {
356+ month + 1
357+ } as u32;
358+
359+ let day = cmp::min(date_time.day(), ndays_in_month(year, month));
360+
361+ Some(NaiveDate::from_ymd(year, month, day).and_time(date_time.time()))
362+}
363+
364+fn add_years(date_time: NaiveDateTime, amount: i64) -> Option<NaiveDateTime> {
365+ let year = i32::try_from(date_time.year() as i64 + amount).ok()?;
366+ let ndays = ndays_in_month(year, date_time.month());
367+
368+ if date_time.day() > ndays {
369+ let d = NaiveDate::from_ymd(year, date_time.month(), ndays);
370+ Some(d.succ().and_time(date_time.time()))
371+ } else {
372+ date_time.with_year(year)
373+ }
374+}
375+
376+fn add_duration(date_time: NaiveDateTime, duration: Duration) -> Option<NaiveDateTime> {
377+ date_time.checked_add_signed(duration)
378+}
379+
380+fn toggle_am_pm(date_time: NaiveDateTime) -> Option<NaiveDateTime> {
381+ if date_time.hour() < 12 {
382+ add_duration(date_time, Duration::hours(12))
383+ } else {
384+ add_duration(date_time, Duration::hours(-12))
385+ }
386+}
387+
388+#[cfg(test)]
389+mod test {
390+ use super::*;
391+ use crate::Rope;
392+
393+ #[test]
394+ fn test_increment_date_times() {
395+ let tests = [
396+ // (original, cursor, amount, expected)
397+ ("2020-02-28", 0, 1, "2021-02-28"),
398+ ("2020-02-29", 0, 1, "2021-03-01"),
399+ ("2020-01-31", 5, 1, "2020-02-29"),
400+ ("2020-01-20", 5, 1, "2020-02-20"),
401+ ("2021-01-01", 5, -1, "2020-12-01"),
402+ ("2021-01-31", 5, -2, "2020-11-30"),
403+ ("2020-02-28", 8, 1, "2020-02-29"),
404+ ("2021-02-28", 8, 1, "2021-03-01"),
405+ ("2021-02-28", 0, -1, "2020-02-28"),
406+ ("2021-03-01", 0, -1, "2020-03-01"),
407+ ("2020-02-29", 5, -1, "2020-01-29"),
408+ ("2020-02-20", 5, -1, "2020-01-20"),
409+ ("2020-02-29", 8, -1, "2020-02-28"),
410+ ("2021-03-01", 8, -1, "2021-02-28"),
411+ ("1980/12/21", 8, 100, "1981/03/31"),
412+ ("1980/12/21", 8, -100, "1980/09/12"),
413+ ("1980/12/21", 8, 1000, "1983/09/17"),
414+ ("1980/12/21", 8, -1000, "1978/03/27"),
415+ ("2021-11-24 07:12:23", 0, 1, "2022-11-24 07:12:23"),
416+ ("2021-11-24 07:12:23", 5, 1, "2021-12-24 07:12:23"),
417+ ("2021-11-24 07:12:23", 8, 1, "2021-11-25 07:12:23"),
418+ ("2021-11-24 07:12:23", 11, 1, "2021-11-24 08:12:23"),
419+ ("2021-11-24 07:12:23", 14, 1, "2021-11-24 07:13:23"),
420+ ("2021-11-24 07:12:23", 17, 1, "2021-11-24 07:12:24"),
421+ ("2021/11/24 07:12:23", 0, 1, "2022/11/24 07:12:23"),
422+ ("2021/11/24 07:12:23", 5, 1, "2021/12/24 07:12:23"),
423+ ("2021/11/24 07:12:23", 8, 1, "2021/11/25 07:12:23"),
424+ ("2021/11/24 07:12:23", 11, 1, "2021/11/24 08:12:23"),
425+ ("2021/11/24 07:12:23", 14, 1, "2021/11/24 07:13:23"),
426+ ("2021/11/24 07:12:23", 17, 1, "2021/11/24 07:12:24"),
427+ ("2021-11-24 07:12", 0, 1, "2022-11-24 07:12"),
428+ ("2021-11-24 07:12", 5, 1, "2021-12-24 07:12"),
429+ ("2021-11-24 07:12", 8, 1, "2021-11-25 07:12"),
430+ ("2021-11-24 07:12", 11, 1, "2021-11-24 08:12"),
431+ ("2021-11-24 07:12", 14, 1, "2021-11-24 07:13"),
432+ ("2021/11/24 07:12", 0, 1, "2022/11/24 07:12"),
433+ ("2021/11/24 07:12", 5, 1, "2021/12/24 07:12"),
434+ ("2021/11/24 07:12", 8, 1, "2021/11/25 07:12"),
435+ ("2021/11/24 07:12", 11, 1, "2021/11/24 08:12"),
436+ ("2021/11/24 07:12", 14, 1, "2021/11/24 07:13"),
437+ ("Wed Nov 24 2021", 0, 1, "Thu Nov 25 2021"),
438+ ("Wed Nov 24 2021", 4, 1, "Fri Dec 24 2021"),
439+ ("Wed Nov 24 2021", 8, 1, "Thu Nov 25 2021"),
440+ ("Wed Nov 24 2021", 11, 1, "Thu Nov 24 2022"),
441+ ("24-Nov-2021", 0, 1, "25-Nov-2021"),
442+ ("24-Nov-2021", 3, 1, "24-Dec-2021"),
443+ ("24-Nov-2021", 7, 1, "24-Nov-2022"),
444+ ("2021 Nov 24", 0, 1, "2022 Nov 24"),
445+ ("2021 Nov 24", 5, 1, "2021 Dec 24"),
446+ ("2021 Nov 24", 9, 1, "2021 Nov 25"),
447+ ("Nov 24, 2021", 0, 1, "Dec 24, 2021"),
448+ ("Nov 24, 2021", 4, 1, "Nov 25, 2021"),
449+ ("Nov 24, 2021", 8, 1, "Nov 24, 2022"),
450+ ("7:21:53 am", 0, 1, "8:21:53 am"),
451+ ("7:21:53 am", 3, 1, "7:22:53 am"),
452+ ("7:21:53 am", 5, 1, "7:21:54 am"),
453+ ("7:21:53 am", 8, 1, "7:21:53 pm"),
454+ ("7:21:53 AM", 0, 1, "8:21:53 AM"),
455+ ("7:21:53 AM", 3, 1, "7:22:53 AM"),
456+ ("7:21:53 AM", 5, 1, "7:21:54 AM"),
457+ ("7:21:53 AM", 8, 1, "7:21:53 PM"),
458+ ("7:21 am", 0, 1, "8:21 am"),
459+ ("7:21 am", 3, 1, "7:22 am"),
460+ ("7:21 am", 5, 1, "7:21 pm"),
461+ ("7:21 AM", 0, 1, "8:21 AM"),
462+ ("7:21 AM", 3, 1, "7:22 AM"),
463+ ("7:21 AM", 5, 1, "7:21 PM"),
464+ ("23:24:23", 1, 1, "00:24:23"),
465+ ("23:24:23", 3, 1, "23:25:23"),
466+ ("23:24:23", 6, 1, "23:24:24"),
467+ ("23:24", 1, 1, "00:24"),
468+ ("23:24", 3, 1, "23:25"),
469+ ];
470+
471+ for (original, cursor, amount, expected) in tests {
472+ let rope = Rope::from_str(original);
473+ let range = Range::new(cursor, cursor + 1);
474+ assert_eq!(
475+ DateTimeIncrementor::from_range(rope.slice(..), range)
476+ .unwrap()
477+ .increment(amount)
478+ .1,
479+ expected.into()
480+ );
481+ }
482+ }
483+
484+ #[test]
485+ fn test_invalid_date_times() {
486+ let tests = [
487+ "0000-00-00",
488+ "1980-2-21",
489+ "1980-12-1",
490+ "12345",
491+ "2020-02-30",
492+ "1999-12-32",
493+ "19-12-32",
494+ "1-2-3",
495+ "0000/00/00",
496+ "1980/2/21",
497+ "1980/12/1",
498+ "12345",
499+ "2020/02/30",
500+ "1999/12/32",
501+ "19/12/32",
502+ "1/2/3",
503+ "123:456:789",
504+ "11:61",
505+ "2021-55-12 08:12:54",
506+ ];
507+
508+ for invalid in tests {
509+ let rope = Rope::from_str(invalid);
510+ let range = Range::new(0, 1);
511+
512+ assert_eq!(DateTimeIncrementor::from_range(rope.slice(..), range), None)
513+ }
514+ }
515+}
helix-core/src/increment/mod.rs+1−1
@@ -1,4 +1,4 @@
1−pub mod date;
1+pub mod date_time;
22pub mod number;
33
44use crate::{Range, Tendril};
helix-term/src/commands.rs+2−2
@@ -1,7 +1,7 @@
11use helix_core::{
22 comment, coords_at_pos, find_first_non_whitespace_char, find_root, graphemes,
33 history::UndoKind,
4− increment::date::DateIncrementor,
4+ increment::date_time::DateTimeIncrementor,
55 increment::{number::NumberIncrementor, Increment},
66 indent,
77 indent::IndentStyle,
@@ -5804,7 +5804,7 @@ fn increment_impl(cx: &mut Context, amount: i64) {
58045804
58055805 let changes = selection.ranges().iter().filter_map(|range| {
58065806 let incrementor: Option<Box<dyn Increment>> = if let Some(incrementor) =
5807− DateIncrementor::from_range(text.slice(..), *range)
5807+ DateTimeIncrementor::from_range(text.slice(..), *range)
58085808 {
58095809 Some(Box::new(incrementor))
58105810 } else if let Some(incrementor) = NumberIncrementor::from_range(text.slice(..), *range) {