11local ts_utils = require (' nvim-treesitter.ts_utils' )
22local tree_utils = require (' orgmode.utils.treesitter' )
3+ local Date = require (' orgmode.objects.date' )
34local config = require (' orgmode.config' )
45local query = vim .treesitter .query
56
67local Headline = {}
78
8- --- @param headline userdata tree sitter headline node
9+ --- @param headline_node userdata tree sitter headline node
910function Headline :new (headline_node )
1011 local data = { headline = headline_node }
1112 setmetatable (data , self )
@@ -17,6 +18,12 @@ function Headline:stars()
1718 return self .headline :field (' stars' )[1 ]
1819end
1920
21+ --- @return number
22+ function Headline :level ()
23+ local stars = self :stars ()
24+ return query .get_node_text (stars , 0 ):len ()
25+ end
26+
2027function Headline :priority ()
2128 return self :parse (' %[#(%w+)%]' )
2229end
8390function Headline :dates ()
8491 local plan = self :plan ()
8592 local dates = {}
93+
94+ if not plan then
95+ return dates
96+ end
97+
8698 for _ , node in ipairs (ts_utils .get_named_children (plan )) do
8799 local name = vim .treesitter .query .get_node_text (node :named_child (0 ), 0 )
88100 dates [name ] = node
@@ -103,12 +115,21 @@ end
103115
104116function Headline :add_closed_date ()
105117 local dates = self :dates ()
106- if vim . tbl_count ( dates ) == 0 or dates [' CLOSED' ] then
118+ if dates [' CLOSED' ] then
107119 return
108120 end
121+ local closed_text = ' CLOSED: ' .. Date .now ():to_wrapped_string (false )
122+ if vim .tbl_isempty (dates ) then
123+ local indent = config :get_indent (self :level () + 1 )
124+ local start_line = self .headline :start ()
125+ return vim .api .nvim_call_function (' append' , {
126+ start_line + 1 ,
127+ string.format (' %s%s' , indent , closed_text ),
128+ })
129+ end
109130 local last_child = dates [' DEADLINE' ] or dates [' SCHEDULED' ]
110131 local ptext = query .get_node_text (last_child , 0 )
111- local text = ptext .. ' CLOSED: [ ' .. vim . fn . strftime ( ' %Y-%m-%d %a %H:%M ' ) .. ' ] '
132+ local text = ptext .. ' ' .. closed_text
112133 tree_utils .set_node_text (last_child , text )
113134end
114135
@@ -117,7 +138,11 @@ function Headline:remove_closed_date()
117138 if vim .tbl_count (dates ) == 0 or not dates [' CLOSED' ] then
118139 return
119140 end
141+ local line_nr = dates [' CLOSED' ]:start () + 1
120142 tree_utils .set_node_text (dates [' CLOSED' ], ' ' , true )
143+ if vim .trim (vim .fn .getline (line_nr )) == ' ' then
144+ return vim .api .nvim_call_function (' deletebufline' , { vim .api .nvim_get_current_buf (), line_nr })
145+ end
121146end
122147
123148-- @return tsnode, string
0 commit comments