-
Notifications
You must be signed in to change notification settings - Fork 15
/
orgagenda.py
2210 lines (1989 loc) · 82.8 KB
/
orgagenda.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import re
import os
import time
import sublime, sublime_plugin
import datetime
import fnmatch
import OrgExtended.orgparse.node as node
import OrgExtended.orgparse.date as orgdate
import OrgExtended.orgutil.util as util
import OrgExtended.orgutil.navigation as nav
import OrgExtended.orgutil.template as templateEngine
import OrgExtended.orgduration as dur
import logging
import sys
import traceback
import OrgExtended.orgfolding as folding
import OrgExtended.orgdb as db
import OrgExtended.orgdatepicker as dpick
import OrgExtended.asettings as sets
import OrgExtended.pymitter as evt
import OrgExtended.orginsertselected as insSel
import calendar
import dateutil.rrule as dr
import dateutil.parser as dp
import dateutil.relativedelta as drel
log = logging.getLogger(__name__)
AGENDA_VIEW = "Org Mode Agenda"
TODO_VIEW = "Org Todos"
ViewMappings = {}
def ReloadAllUnsavedBuffers():
sheets = sublime.active_window().sheets()
for sheet in sheets:
view = sheet.view()
if(view and util.isPotentialOrgFileOrBuffer(view)):
db.Get().FindInfo(view)
def IsRawDate(ts):
return isinstance(ts,datetime.date) or isinstance(ts,datetime.datetime)
def EnsureDateTime(ts):
if(ts and not isinstance(ts,datetime.datetime)):
return datetime.datetime.combine(ts, datetime.datetime.min.time())
return ts
def EnsureDate(ts):
if(isinstance(ts,datetime.datetime)):
return ts.date()
return ts
def FindMappedView(view):
if(view.name() in ViewMappings):
return ViewMappings[view.name()]
log.debug("Could not find view named: " + view.name())
return None
def move_file_other_group(myview, view):
window = sublime.active_window()
if (window.num_groups() < 2):
#self.window.run_command('clone_file')
window.set_layout({
"cols": [0.0, 0.5, 1.0],
"rows": [0.0, 1.0],
"cells": [[0, 0, 1, 1], [1, 0, 2, 1]]
})
mygroup = 0
othergroup = 1
else:
window.focus_view(view)
mygroup = 1
othergroup = 0
if (window.get_view_index(myview)[0] == 0):
othergroup = 1
mygroup = 0
window.focus_view(view)
window.run_command('move_to_group', {'group': othergroup})
window.run_command('focus_group', {'group': mygroup})
window.focus_view(myview)
#view0 = self.window.active_view_in_group(0)
#view1 = self.window.active_view_in_group(1)
# Same file open in each of the two windows, cull to 1 if possible
#if (view0.file_name() == view1.file_name()):
# self.window.focus_view(view1)
#class CloneFileToNewViewCommand(sublime_plugin.WindowCommand):
# def run(self):
def get_view_for_silent_edit_file(file):
# First check all sheets for this file.
window = sublime.active_window()
view = window.find_open_file(file.filename)
if(view):
return view
# Okay the file is not opened, we have to open it
# but we don't want it having focus
# So keep the old view so we can refocus just to
# be sure.
currentView = window.active_view()
view = window.open_file(file.filename, sublime.ENCODED_POSITION)
window.focus_view(currentView)
return view
def CreateUniqueViewNamed(name, mapped=None):
# Close the view if it exists
win = sublime.active_window()
for view in win.views():
if view.name() == name:
win.focus_view(view)
win.run_command('close')
win.run_command('new_file')
view = win.active_view()
view.set_name(name)
# TODO: Change this.
view.set_syntax_file("Packages/OrgExtended/orgagenda.sublime-syntax")
ViewMappings[view.name()] = mapped
return view
def IsPhone(n):
return n and n.todo and "PHONE" in n.todo
def IsMeeting(n):
return n and n.todo and "MEETING" in n.todo
def IsNote(n):
return n and n.todo and "NOTE" in n.todo
def IsTodo(n):
return n.todo and n.todo in n.env.todo_keys
def IsDone(n):
return n.todo and n.todo in n.env.done_keys
def IsArchived(n):
return "ARCHIVE" in n.tags
def HasChildTasks(n):
for c in n.children:
if(IsTodo(c)):
return True
return False
# Task that belongs to a project. This means we have to have a parent and that parent has to be
# identified as a project.
def IsProjectTask(n):
if(not n or n.is_root()):
return False
return (IsTodo(n) and n.parent and not n.parent.is_root() and IsProject(n.parent))
def IsBlockedProject(n):
if(IsProject(n) and n.num_children > 0):
isBlocked = True
for c in n.children:
if(c.todo and c.todo == 'NEXT'):
isBlocked = False
return isBlocked
else:
return False
def IsProjectTodoWithTodos(n):
if(IsTodo(n) and n.num_children > 0):
for c in n.children:
if(IsTodo(c)):
return True
return False
def IsProjectTaskWithProjectTag(n):
if(n):
tags = n.shallow_tags
if("PROJECT" in tags or "Project" in tags or "project" in tags):
#print("PROJ: " + n.heading)
return True
return False
def IsProjectTaskWithProjectProperty(n):
if(n and (n.get_property("PROJECT") or n.get_property("Project") or n.get_property("project"))):
return True
return False
def IsProject(n):
projType = sets.Get("agendaProjectIs", "nested_todo").lower()
if(projType == "nested_todo"):
return IsProjectTodoWithTodos(n)
if(projType == "tag"):
return IsProjectTaskWithProjectTag(n)
if(projType == "property"):
return IsProjectTaskWithProjectProperty(n)
return IsProjectTodoWithTodos(n)
def IsTodaysDate(check, today):
if(not type(check) == datetime.date):
check = check.date()
if(not type(today) == datetime.date):
today = today.date()
return today == check
def IsInMonthCheck(t, now):
if(IsRawDate(t)):
dateT = t
else:
dateT = datetime.date(t.start.year, t.start.month, t.start.day)
if (dateT.year == now.year):
if (dateT.month >= (now.month-1) and dateT.month <= (now.month+1)):
return True
else:
return False
if (dateT.year == now.year + 1) and (dateT.month == 0 and now.month == 11):
return True
if (dateT.year == now.year - 1) and (dateT.month == 11 and now.month == 0):
return True
return False
def IsInMonth(n, now):
if(not n):
return (None,None)
if(n):
timestamps = n.get_timestamps(active=True,point=True,range=True)
for t in timestamps:
if(t.repeating):
next = t.next_repeat_from(now)
if(IsInMonthCheck(next, now)):
if(IsRawDate(t)):
return (now,True)
else:
return (now, True)
else:
if(IsInMonthCheck(t, now)):
return (t,False)
if(n.scheduled):
if(IsInMonthCheck(n.scheduled, now)):
return (n.scheduled.start,n.scheduled.repeating)
return (None,None)
def IsToday(n, today):
# 4 months of per day scheduling is the maximum
# we are willing to loop to avoid crazy slow loops.
kMaxLoops = sets.GetInt("agendaMaxScheduledIterations", 120)
timestamps = n.get_timestamps(active=True,point=True,range=True)
for t in timestamps:
if(t.repeating):
if(IsTodaysDate(t.start, today)):
return t
next = EnsureDateTime(t.start)
loopcount = 0
while(next <= EnsureDateTime(today) and loopcount <= kMaxLoops):
if IsTodaysDate(next, today):
return next
next = t.next_repeat_from(next)
loopcount += 1
else:
if(t.has_overlap(today)):
return t
if(n.scheduled):
if(n.scheduled.repeating):
next = n.scheduled.start
loopcount = 0
while(EnsureDateTime(next) <= EnsureDateTime(today) and loopcount <= kMaxLoops):
if IsTodaysDate(next, today):
return next
next = n.scheduled.next_repeat_from(EnsureDateTime(next))
loopcount += 1
else:
return n.scheduled.after(today)
if(n.deadline):
start = EnsureDateTime(n.deadline.deadline_start)
if start <= today:
return n.deadline
if(n.deadline.repeating):
next = n.deadline.start
loopcount = 0
while(EnsureDateTime(next) <= EnsureDateTime(today) and loopcount <= kMaxLoops):
if IsTodaysDate(next, today):
return next
next = n.deadline.next_repeat_from(EnsureDateTime(next))
loopcount += 1
return None
def IsAllDay(n,today):
if(not n):
return None
timestamps = n.get_timestamps(active=True,point=True,range=True)
for t in timestamps:
if(t.repeating):
dt = t.next_repeat_from(today)
if(dt.hour == 0 and dt.minute == 0 and dt.second == 0 and dt.microsecond == 0):
return dt
else:
if(t.has_end() or t.has_time()):
continue
return t
if(n.scheduled):
if(n.scheduled.repeating):
dt = n.scheduled.next_repeat_from(today)
if(dt.hour == 0 and dt.minute == 0 and dt.second == 0 and dt.microsecond == 0):
return n.scheduled
else:
if(not n.scheduled.has_end() and not n.scheduled.has_time()):
return n.scheduled
if(n.deadline):
dt = n.deadline.deadline_start
if(isinstance(dt,datetime.date)):
return True
if(dt.hour == 0 and dt.minute == 0 and dt.second == 0 and dt.microsecond == 0):
return today
return None
def HasTimestamp(n):
if(not n):
return False
timestamps = n.get_timestamps(active=True,point=True,range=True)
return n.scheduled or (timestamps and len(timestamps) > 0) or n.deadline
def IsInHourBracket(s, e, hour):
if(not e):
# TODO Make this configurable
e = s + datetime.timedelta(minutes=30)
# Either this task is a ranged task OR it is a single point task
# Ranged tasks have to fit within the hour, point tasks have to
if( Overlaps(s.hour*60 + s.minute, e.hour*60 + e.minute, hour*60, hour*60 + 59)):
return True
def IsInHour(n, hour, today):
if(not n):
return None
timestamps = n.get_timestamps(active=True, point=True,range=True)
if(timestamps):
for t in timestamps:
if(t.has_time()):
if(t.repeating):
next = t.next_repeat_from(today)
if(next.hour == hour):
return next
else:
s = t.start
e = t.end
if(IsInHourBracket(s,e,hour)):
return t
if(n.scheduled and n.scheduled.has_time()):
if(n.scheduled.repeating):
next = n.scheduled.next_repeat_from(today)
if next.hour == hour:
return next
else:
return None
s = EnsureDateTime(n.scheduled.start)
e = EnsureDateTime(n.scheduled.end)
if(IsInHourBracket(s,e,hour)):
return n.scheduled
if(n.deadline):
s = EnsureDateTime(n.deadline.start)
e = EnsureDateTime(n.deadline.end)
if(IsInHourBracket(s,e,hour)):
return n.deadline
return None
def Overlaps(s,e,rs,re):
# s | e |
# +---+
if(s <= rs and e >= rs and e <= re):
return True
# | s | e
# +---+
if(s >= rs and s < re and e >= re):
return True
# | s e |
# +-+
if(s >= rs and e <= re):
return True
# s | | e
# +-------+
if(s <= rs and e >= re):
return True
return False
def IsInHourAndMinuteBracket(s,e,hour,mstart,mend):
if(not e):
# TODO Make this configurable
e = s + datetime.timedelta(minutes=30)
# Either this task is a ranged task OR it is a single point task
# Ranged tasks have to fit within the hour, point tasks have to
if( Overlaps(s.hour*60 + s.minute, e.hour*60 + e.minute, hour*60 + mstart, hour*60 + mend)):
return True
return False
def IsInHourAndMinute(n, hour, mstart, mend, today):
if(not n):
return None
timestamps = n.get_timestamps(active=True, point=True,range=True)
if(timestamps):
for t in timestamps:
if(t.has_time()):
if(t.repeating):
next = t.next_repeat_from(today)
if(next.hour == hour):
return next
else:
s = t.start
e = t.end
if(IsInHourAndMinuteBracket(s,e,hour,mstart,mend)):
return t
if(n.scheduled and n.scheduled.has_time()):
if(n.scheduled.repeating):
next = n.scheduled.next_repeat_from(today)
if(next.hour == hour):
return next
s = n.scheduled.start
e = n.scheduled.end
if(IsInHourAndMinuteBracket(s,e,hour,mstart,mend)):
return n.scheduled
if(n.deadline):
s = EnsureDateTime(n.deadline.start)
e = EnsureDateTime(n.deadline.end)
if(IsInHourAndMinuteBracket(s,e,hour,mstart,mend)):
return n.deadline
return None
def distanceFromStart(e, hour, minSlot):
ts = e['ts']
if(IsRawDate(ts)):
rv = 5*(hour - ts.hour) + (minSlot - int(ts.minute/12))
else:
rv = 5*(hour - ts.start.hour) + (minSlot - int(ts.start.minute/12))
return rv
# ================================================================================
# IDEA Make a base class that has all the functionality needed to
# render an agenda view. Then create an agenda folder with
# all my views, like dynamic blocks.
#
# The goal being to allow people to extend and create custom
# agenda views from their user folder, without having to
# write all the "stuff"
#
# Also create a BUNCH of filters that filter by tag, properties
# and other things so there are example versions of each.
#
# statefilter
# tagfilter
# priorityfilter
class AgendaBaseView:
def __init__(self, name, setup=True, **kwargs):
self.name = name
self.SetTagFilter(kwargs)
self.SetPriorityFilter(kwargs)
self.SetStateFilter(kwargs)
self.SetDurationFilter(kwargs)
self.SetClockedDurationFilter(kwargs)
self.SetDateFilter(kwargs)
self.hasclock = "hasclock" in kwargs
self.clockedtoday = "clockedtoday" in kwargs
self.clockfilter = "clockfilter" in kwargs
self.hasclose = "hasclose" in kwargs
self.hasdeadline = "hasdeadline" in kwargs
self.hasschedule = "hasschedule" in kwargs
self.noclock = "noclock" in kwargs
self.noclose = "noclose" in kwargs
self.nodeadline = "nodeadline" in kwargs
self.noschedule = "noschedule" in kwargs
self.onlyTasks = "onlytasks" in kwargs
self.haschildtasks = "haschildtasks" in kwargs
self.nochildtasks = "nochildtasks" in kwargs
if(setup):
self.SetupView()
else:
self.BasicSetup()
# Default view does not have a filter view
# Only todo view
def OpenFilterView(self):
pass
def BasicSetup(self):
self.UpdateNow()
self.entries = []
def SetDurationFilter(self,kwargs):
self._beforeDuration = []
self._afterDuration = []
if("durationfilter" in kwargs):
self._durationFilter = kwargs["durationfilter"]
else:
self._durationFilter = None
return
tags = self._durationFilter.split(' ')
for tag in tags:
tag = tag.strip()
if not tag or len(tag) <= 0:
continue
m = RE_IN_OUT_TAG.search(tag)
if(m):
inout = m.group('inout')
tagdata = m.group('tag')
if(not inout or inout == '+'):
self._beforeDuration.append(dur.OrgDuration.Parse(tagdata.strip()))
else:
self._afterDuration.append(dur.OrgDuration.Parse(tagdata.strip()))
def SetClockedDurationFilter(self,kwargs):
self._beforeClockedDuration = []
self._afterClockedDuration = []
if("clockfilter" in kwargs):
self._clockedDurationFilter = kwargs["clockfilter"]
else:
self._clockedDurationFilter = None
return
tags = self._clockedDurationFilter.split(' ')
for tag in tags:
tag = tag.strip()
if not tag or len(tag) <= 0:
continue
m = RE_IN_OUT_TAG.search(tag)
if(m):
inout = m.group('inout')
tagdata = m.group('tag')
if(not inout or inout == '+'):
self._beforeClockedDuration.append(dur.OrgDuration.Parse(tagdata.strip()))
else:
self._afterClockedDuration.append(dur.OrgDuration.Parse(tagdata.strip()))
def SetStateFilter(self,kwargs):
if("statefilter" in kwargs):
self._stateFilter = kwargs["statefilter"]
else:
self._stateFilter = None
return
self._inStateTags = []
self._oneofStateTags = []
self._outStateTags = []
tags = self._stateFilter.split(' ')
for tag in tags:
tag = tag.strip()
if not tag or len(tag) <= 0:
continue
m = RE_IN_OUT_TAG.search(tag)
if(m):
inout = m.group('inout')
tagdata = m.group('tag')
if(not inout or inout == '+'):
self._inStateTags.append(tagdata.strip())
elif(inout == '|'):
self._oneofStateTags.append(tagdata.strip())
else:
self._outStateTags.append(tagdata.strip())
def SetPriorityFilter(self,kwargs):
if("priorityfilter" in kwargs):
self._priorityFilter = kwargs["priorityfilter"]
else:
self._priorityFilter = None
return
self._inPriorityTags = []
self._oneofPriorityTags = []
self._outPriorityTagsags = []
tags = self._priorityFilter.split(' ')
for tag in tags:
tag = tag.strip()
if not tag or len(tag) <= 0:
continue
m = RE_IN_OUT_TAG.search(tag)
if(m):
inout = m.group('inout')
tagdata = m.group('tag')
if(not inout or inout == '+'):
self._inPriorityTags.append(tagdata.strip())
elif(inout == '|'):
self._oneofPriorityTags.append(tagdata.strip())
else:
self._outPriorityTags.append(tagdata.strip())
def SetTagFilter(self,kwargs):
if("tagfilter" in kwargs):
self._tagfilter = kwargs["tagfilter"]
else:
self._tagfilter = None
return
self._intags = []
self._oneoftags = []
self._outtags = []
tags = self._tagfilter.split(' ')
for tag in tags:
tag = tag.strip()
if not tag or len(tag) <= 0:
continue
m = RE_IN_OUT_TAG.search(tag)
if(m):
inout = m.group('inout')
tagdata = m.group('tag')
if(not inout or inout == '+'):
self._intags.append(tagdata.strip())
elif(inout == '|'):
self._oneoftags.append(tagdata.strip())
else:
self._outtags.append(tagdata.strip())
def SetDateFilter(self, kwargs):
self._startDoneDateComparator = None
self._endDoneDateComparator = None
if "datefilter" not in kwargs:
return
DATE_PATTERN = "([><=]+)(\d+)"
datefilter = kwargs["datefilter"].split(" ")
for cond in datefilter:
match = re.search(DATE_PATTERN, cond)
if match is None:
continue
operator = match.group(1)
date_str = match.group(2)
try:
date = dp.parse(date_str)
except:
log.error("Failed to parse datefilter")
continue
if operator == ">":
self._startDoneDateComparator = lambda d, date=date: d is not None and date < d
if operator == ">=":
self._startDoneDateComparator = lambda d, date=date: d is not None and date <= d
if operator == "<":
self._endDoneDateComparator = lambda d, date=date: d is not None and d < date
if operator == "<=":
date = date + datetime.timedelta(days=1)
self._endDoneDateComparator = lambda d, date=date: d is not None and d < date
def MatchHas(self, node):
if(self.hasclock and not node.clock):
return False
if(self.hasdeadline and not node.deadline):
return False
if(self.hasclose and not node.closed):
return False
if(self.hasschedule and not node.scheduled):
return False
if(self.haschildtasks and not HasChildTasks(node)):
return False
if(self.noclock and node.clock):
return False
if(self.nodeadline and node.deadline):
return False
if(self.noclose and node.closed):
return False
if(self.noschedule and node.scheduled):
return False
if(self.nochildtasks and HasChildTasks(node)):
return False
return True
def MatchTags(self, node):
if(not self._tagfilter):
return True
if(self._intags and len(self._intags) > 0 and not all(elem in node.tags for elem in self._intags)):
return False
if(self._outtags and any(elem in node.tags for elem in self._outtags)):
return False
if(self._oneoftags and len(self._oneoftags) > 0 and not any(elem in node.tags for elem in self._oneoftags)):
return False
return True
def MatchPriorities(self, node):
if(not self._priorityFilter):
return True
if(self._inPriorityTags and len(self._inPriorityTags) > 0 and not all(elem in node.priority for elem in self._inPriorityTags)):
return False
if(self._outPriorityTags and any(elem in node.priority for elem in self._outPriorityTags)):
return False
if(self._oneofPriorityTags and len(self._oneofPriorityTags) > 0 and not any(elem in node.priority for elem in self._oneofPriorityTags)):
return False
return True
def MatchState(self, node):
t = node.todo
if(not node.todo):
t = ""
if(not self._stateFilter):
return True
if(self._inStateTags and len(self._inStateTags) > 0 and not all(re.search(elem,t) for elem in self._inStateTags)):
return False
if(self._outStateTags and any(re.search(elem,t) for elem in self._outStateTags)):
return False
if(self._oneofStateTags and len(self._oneofStateTags) > 0 and not any(re.search(elem,t) for elem in self._oneofStateTags)):
return False
return True
def MatchDuration(self, node):
t = node.closed
if(t and self._afterDuration and any(not t.after_duration(elem) for elem in self._afterDuration)):
return False
if self._beforeDuration:
s = node.scheduled
d = node.deadline
ts = node.get_timestamps()
if(s and any(s and s.before_duration(elem) for elem in self._beforeDuration)):
return True
if(d and any(d and d.before_duration(elem) for elem in self._beforeDuration)):
return True
if(ts and len(ts) > 0 and any(ts[0] and ts[0].before_duration(elem) for elem in self._beforeDuration)):
return True
return False
return True
def MatchDate(self, node):
start = node.closed.start
end = node.closed.end if node.closed.end is not None else start
if self._startDoneDateComparator is not None \
and not self._startDoneDateComparator(start):
return False
if self._endDoneDateComparator is not None \
and not self._endDoneDateComparator(end):
return False
return True
def MatchClock(self, node):
if self.clockedtoday:
if not node.clock:
return False
now = datetime.datetime.now()
for c in node.clock:
if c.start.date() == now.date():
return True
if c.end.date() == now.date():
return True
return False
if self.clockfilter:
if not node.clock:
return False
for t in node.clock:
if t:
if(self._afterClockedDuration and any(not t.after_duration(elem) for elem in self._afterClockedDuration)):
return False
if(self._beforeClockedDuration and any(not t.before_duration(elem) for elem in self._beforeClockedDuration)):
return False
return True
def SetupView(self):
self.view = CreateUniqueViewNamed(self.name, self)
self.view.set_read_only(True)
self.view.set_scratch(True)
self.view.set_name(self.name)
self.BasicSetup()
self.FilterEntries()
# Keep ourselves attached to this agenda
# This doesn't work BOO
self.view.agenda = self
def DoRenderView(self,edit, clear = False):
self.StartEditing()
self.RenderView(edit, clear)
self.DoneEditing()
def OpenFilterView(self):
first = True
for v in self.agendaViews:
v.view = self.view
v.OpenFilterView()
def InsertAgendaHeading(self, edit):
if(hasattr(self,'_tagfilter') and self._tagfilter):
self.view.insert(edit, self.view.size(), self.name + "\t\t TAGS( " + self._tagfilter + " )\n")
else:
self.view.insert(edit, self.view.size(), self.name + "\n")
def UpdateNow(self, now=None):
if(now == None):
self.now = datetime.datetime.now()
else:
self.now = now
self.entries = []
self.FilterEntries()
# You have to bookend your editing session with these
def StartEditing(self):
self.view.set_read_only(False)
def DoneEditing(self):
self.view.set_read_only(True)
def RestoreCursor(self, pos):
# Restore the cursor
self.view.sel().clear()
self.view.sel().add(pos)
def AddEntry(self, node, file):
self.entries.append({"node": node, "file": file})
def ClearEntriesAt(self):
for e in self.entries:
if 'at' in e:
del e['at']
def MarkEntryAt(self, entry, ts= None):
if(not 'at' in entry):
entry['at'] = []
entry['at'].append(self.view.rowcol(self.view.size())[0])
entry['ts'] = ts
def MarkEntryAtRegion(self, entry, reg, ts=None):
if(not 'at' in entry):
entry['at'] = []
entry['at'].append(reg)
entry['ts'] = ts
def At(self, row, col):
for e in self.entries:
if 'at' in e:
for ea in e['at']:
if(type(ea) == int):
if(ea == row):
return (e['node'], e['file'])
elif(type(ea) == sublime.Region):
if(ea.contains(self.view.text_point(row,col))):
return (e['node'], e['file'])
return (None, None)
def Clear(self, edit):
self.StartEditing()
self.view.erase(edit, sublime.Region(0,self.view.size()))
self.DoneEditing()
# ----------------------------------------------
# These are user extended views!
def RenderView(self, edit, clear=False):
pass
def FilterEntries(self):
allowOutsideOrgDir = sets.Get("agendaIncludeFilesOutsideOrgDir", False)
for file in db.Get().Files:
# Skip over files not in orgDir
if(not file.isOrgDir and not allowOutsideOrgDir):
continue
#if(not "habits" in file.filename):
# continue
#print("AGENDA: " + file.filename + " " + file.key)
for n in file.org[1:]:
if(self.MatchHas(n)
and self.MatchPriorities(n)
and self.MatchTags(n)
and self.MatchState(n)
and self.MatchDuration(n)
and self.MatchDate(n)
and self.MatchClock(n)
and self.FilterEntry(n, file)):
self.AddEntry(n, file)
def FilterEntry(self, node, file):
pass
def IsBeforeNow(ts, now):
if(isinstance(ts,orgdate.OrgDate)):
return ts and (not ts.has_time() or ts.start.time() < now.time())
elif(ts and isinstance(ts,datetime.datetime)):
return ts.time() < now.time()
else:
return False
def IsAfterNow(ts, now):
if(isinstance(ts,orgdate.OrgDate)):
return ts and ts.has_time() and ts.start.time() >= now.time()
elif(ts and isinstance(ts,datetime.datetime)):
return ts.time() >= now.time()
else:
return False
# ============================================================
class CalendarView(AgendaBaseView):
def __init__(self, name, setup=True,**kwargs):
super(CalendarView, self).__init__(name, setup, **kwargs)
firstDayIndex = sets.GetWeekdayIndexByName(sets.Get("firstDayOfWeek","Sunday"))
self.dv = dpick.DateView("orgagenda.now",firstDayIndex = firstDayIndex)
def UpdateNow(self, now=None):
if(now == None):
self.now = datetime.datetime.now()
else:
self.now = now
self.dv.MoveCDateToDate(self.now)
def AddRepeating(self, date):
self.dv.AddToDayHighlights(date, "repeat", "orgagenda.blocked")
def AddTodo(self, date):
if(isinstance(date,orgdate.OrgDate)):
date = date.start
self.dv.AddToDayHighlights(date, "todo", "orgagenda.todo", sublime.DRAW_NO_FILL)
#def AddToDayHighlights(self, date, key, hightlight, drawtype = sublime.DRAW_NO_OUTLINE):
def RenderView(self, edit, clear=False):
self.InsertAgendaHeading(edit)
self.dv.SetView(self.view)
self.dv.Render(self.now)
toHighlight = []
for entry in self.entries:
n = entry['node']
ts, repeating = IsInMonth(n, self.now)
if(ts):
self.AddTodo(ts)
if(ts and repeating):
self.AddRepeating(ts)
def FilterEntry(self, n, filename):
return (not self.onlyTasks or (IsTodo(n) and not IsDone(n) and not IsArchived(n))) and not IsProject(n) and HasTimestamp(n)
def bystartdate(a, b):
if a.scheduled.start > b.scheduled.start:
return 1
if a.scheduled.start < b.scheduled.start:
return -1
return 0
def bystartdatekey(a):
return a.scheduled.start
def bystartnodedatekey(a):
n = a['node']
dt = a['ts']
#dt = n.scheduled.start
if(isinstance(dt,orgdate.OrgDate)):
dt=dt.start
elif(isinstance(dt, datetime.date)):
return datetime.datetime.combine(dt.today(), datetime.datetime.min.time()).timestamp()
return dt.timestamp()
def getdatefromnode(n):
dt = datetime.datetime.min
timestamps = n.get_timestamps(active=True,point=True,range=True)
if timestamps and len(timestamps) > 0:
dt = timestamps[0]
if n.deadline:
dt = n.deadline.start
if n.scheduled:
dt = n.scheduled.start
if n.closed:
dt = n.closed
if(isinstance(dt,orgdate.OrgDate)):
dt=dt.start
#if(isinstance(dt, datetime.datetime)):
# return datetime.datetime.combine(dt.date(), datetime.datetime.min.time())
if(isinstance(dt, datetime.date)):
return datetime.datetime.combine(dt, datetime.datetime.min.time())
return dt
def getdate(a):
n = a['node']
return getdatefromnode(n)
def getsortkey(a):
n = a['node']
dt = getdatefromnode(n)
result = 0
if dt:
result = (dt - datetime.datetime(1970, 1, 1)).total_seconds()
result = int(result)
result = float(result)
result *= 1000
# Include priority after datetime information
if n and n.priority and n.priority != "":
result += (ord(n.priority[0]) - ord('A'))*100
else:
result += 0
# Ensure todos end up before done before archived
if IsTodo(n):
result += 1
if IsDone(n):
result += 2
if IsArchived(n):
result += 3
return result
# ============================================================
class WeekView(AgendaBaseView):
def __init__(self, name, setup=True,**kwargs):
super(WeekView, self).__init__(name, setup, **kwargs)
def HighlightTime(self, date):
reg = self.DateToRegion(date)
style = self.dayhighlight
if(style == None):
style = "orgdatepicker.monthheader"
self.output.add_regions("curweek",[reg],style,"",sublime.DRAW_NO_OUTLINE)
def InsertTimeHeading(self, edit, hour):
self.startOffset = 9