From ac6e02ab638ee324b3e3894e2a05488aad0b467c Mon Sep 17 00:00:00 2001 From: Kristijan Husak Date: Tue, 24 Sep 2024 10:33:44 +0200 Subject: [PATCH] fix(calendar): Do not modify time when switching months --- lua/orgmode/objects/calendar.lua | 4 ++-- lua/orgmode/objects/date.lua | 4 ++++ tests/plenary/object/date_spec.lua | 10 ++++++++++ 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/lua/orgmode/objects/calendar.lua b/lua/orgmode/objects/calendar.lua index 0dd46f983..c0d0cba94 100644 --- a/lua/orgmode/objects/calendar.lua +++ b/lua/orgmode/objects/calendar.lua @@ -335,7 +335,7 @@ end function Calendar:forward() self:_ensure_day() - self.date = self.date:start_of('month'):add({ month = vim.v.count1 }) + self.date = self.date:set({ day = 1 }):add({ month = vim.v.count1 }) self:render() vim.fn.cursor(2, 1) vim.fn.search('01') @@ -344,7 +344,7 @@ end function Calendar:backward() self:_ensure_day() - self.date = self.date:start_of('month'):subtract({ month = vim.v.count1 }):end_of('month') + self.date = self.date:set({ day = 1 }):subtract({ month = vim.v.count1 }):last_day_of_month() self:render() vim.fn.cursor(8, 0) vim.fn.search([[\d\d]], 'b') diff --git a/lua/orgmode/objects/date.lua b/lua/orgmode/objects/date.lua index 7c50dd765..feca8d0fa 100644 --- a/lua/orgmode/objects/date.lua +++ b/lua/orgmode/objects/date.lua @@ -498,6 +498,10 @@ function Date:end_of(span) return self end +function Date:last_day_of_month() + return self:set({ day = Date._days_of_month(os_date(self.timestamp)) }) +end + ---@return number function Date:get_isoweekday() ---@type table diff --git a/tests/plenary/object/date_spec.lua b/tests/plenary/object/date_spec.lua index d15ee5031..5923216ef 100644 --- a/tests/plenary/object/date_spec.lua +++ b/tests/plenary/object/date_spec.lua @@ -303,6 +303,16 @@ describe('Date object', function() assert.are.same('2021-05-31 Mon 23:59', date:to_string()) end) + it('should get last day of the month', function() + local date = Date.from_string('2024-02-02 09:00') + date = date:last_day_of_month() + assert.are.same('2024-02-29 Thu 09:00', date:to_string()) + date = date:add({ month = 1 }):last_day_of_month() + assert.are.same('2024-03-31 Sun 09:00', date:to_string()) + date = date:set({ month = 6, day = 2 }):last_day_of_month() + assert.are.same('2024-06-30 Sun 09:00', date:to_string()) + end) + it('should properly handle end of month', function() local date = Date.from_string('2021-05-12') date = date:end_of('month')