forked from ihdavids/orgextended
-
Notifications
You must be signed in to change notification settings - Fork 0
/
orgagenda.py
1563 lines (1399 loc) · 57.9 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 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 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
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 IsTodo(n.parent)) or (IsTodo(n) and n.parent and n.parent.is_root() and HasChildTasks(n))
def IsBlockedProject(n):
if(IsTodo(n) and n.num_children > 0):
isProject = False
isBlocked = True
for c in n.children:
if(IsTodo(c)):
isProject = True
if(c.todo and c.todo == 'NEXT'):
isBlocked = False
return isProject and isBlocked
else:
return False
def IsProject(n):
#if(n.heading == "Project1"):
# print("CHILDREN: " + str(n.num_children))
# for c in n.children:
# print(c.heading)
# if(IsTodo(c)):
# print("FOUND TASK")
if(IsTodo(n) and n.num_children > 0):
for c in n.children:
if(IsTodo(c)):
return True
return False
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)):
if (t.month >= (now.month-1) and t.month <= (now.month+1)):
return t
else:
if (t.start.month >= (now.month-1) and t.start.month <= (now.month+1)):
return t.start
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)
return next.hour == hour
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.
class AgendaBaseView:
def __init__(self, name, setup=True, **kwargs):
self.name = name
self.SetTagFilter(kwargs)
self.SetPriorityFilter(kwargs)
self.hasclock = "hasclock" 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
if(setup):
self.SetupView()
else:
self.BasicSetup()
def BasicSetup(self):
self.UpdateNow()
self.entries = []
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 MatchHas(self, node):
if(self.hasclock and not n.clock):
return False
if(self.hasdeadline and not n.deadline):
return False
if(self.hasclose and not n.closed):
return False
if(self.hasschedule and not n.scheduled):
return False
if(self.noclock and n.clock):
return False
if(self.nodeadline and n.deadline):
return False
if(self.noclose and n.closed):
return False
if(self.noschedule and n.scheduled):
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 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):
self.StartEditing()
self.RenderView(edit)
self.DoneEditing()
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 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):
pass
def FilterEntries(self):
for file in db.Get().Files:
#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.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)
dayOffset = sets.GetDateAsIndex("firstDayOfWeek","Sunday")
self.dv = dpick.DateView("orgagenda.now",firstDayOffset = dayOffset)
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):
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
if(isinstance(dt, datetime.date)):
return datetime.datetime.combine(dt.today(), datetime.datetime.min.time())
return dt
# ============================================================
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
self.cellSize = 5
pt = self.view.size()
row, c = self.view.rowcol(pt)
dayStart = sets.Get("agendaDayStartTime",6)
dayEnd = sets.Get("agendaDayEndTime",19)
if(dayEnd > 23):
dayEnd = 23
if(dayStart < 0):
dayStart = 0
if(dayStart > dayEnd):
dayStart = 0
dayEnd = 23
header = " "
for i in range(dayStart, dayEnd+1):
if(i == 10):
header += " "
header += " {:2d}".format(i)
header +=" \n"
#header = " 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 \n"
self.view.insert(edit, self.view.size(), header)
dayStart = sets.Get("agendaDayStartTime",6)
col = self.startOffset + (hour-dayStart)*self.cellSize
s = self.view.text_point(row,col)
e = self.view.text_point(row,col+2)
reg = sublime.Region(s, e)
style = "orgagenda.now"
self.view.add_regions("curw",[reg],style,"",sublime.DRAW_NO_OUTLINE)
def InsertDay(self, name, date, edit):
pt = self.view.size()
row, c = self.view.rowcol(pt)
if(date.day == datetime.datetime.now().day):
if(date.day == self.now.day):
self.view.insert(edit, self.view.size(),"@" + name + " " + "{0:2}".format(date.day) + "W[")
else:
self.view.insert(edit, self.view.size(),"#" + name + " " + "{0:2}".format(date.day) + "W[")
elif(date.day == self.now.day):
self.view.insert(edit, self.view.size(),"&" + name + " " + "{0:2}".format(date.day) + "W[")
else:
self.view.insert(edit, self.view.size()," " + name + " " + "{0:2}".format(date.day) + "W[")
daydata = []
for entry in self.entries:
n = entry['node']
timestamps = n.get_timestamps(active=True,point=True,range=True)
shouldContinue = False
for t in timestamps:
if(t.start.day == date.day):
daydata.append(entry)
entry['ts'] = t
shouldContinue = True
break
if(shouldContinue):
continue
if(n.scheduled and (EnsureDate(n.scheduled.start) < EnsureDate(date) and not IsDone(n) and not IsArchived(n) or EnsureDate(n.scheduled.start) == EnsureDate(date))):
daydata.append(entry)
entry['ts'] = n.scheduled
continue
if(n.deadline and (EnsureDate(n.deadline.deadline_start) < EnsureDate(date) and not IsDone(n) and not IsArchived(n) or EnsureDate(n.deadline.deadline_start) == EnsureDate(date))):
daydata.append(entry)
entry['ts'] = n.deadline
continue
daydata.sort(key=bystartnodedatekey)
lastMatchStart = 0
lastMatch = None
lastMatchEntry = None
matchCount = 0
doneMatchCount = 0
dayStart = sets.Get("agendaDayStartTime",6)
dayEnd = sets.Get("agendaDayEndTime",19)
if(dayEnd > 23):
dayEnd = 23
if(dayStart < 0):
dayStart = 0
if(dayStart > dayEnd):
dayStart = 0
dayEnd = 23
for hour in range(dayStart,dayEnd+1):
for minSlot in range(0,self.cellSize):
match = None
matche = None
for entry in daydata:
n = entry['node']
ts = IsInHourAndMinute(n, hour, minSlot*12, (minSlot+1)*12,date)
entry['ts'] = ts
if(ts):
match = n
matche = entry
if(lastMatch != match and lastMatch != None):
s = self.view.text_point(row,lastMatchStart)
e = self.view.text_point(row,self.startOffset + (hour-dayStart)*self.cellSize + minSlot)
reg = sublime.Region(s, e)
if(IsDone(lastMatch) or IsArchived(lastMatch)):
style = "orgagenda.week.done." + str(doneMatchCount)
doneMatchCount = (doneMatchCount + 1) % 2
self.MarkEntryAtRegion(lastMatchEntry,reg)
self.view.add_regions("week_done_" + str(date.day) + "_" + str(hour) + "_" + str(minSlot),[reg],style,"", sublime.DRAW_SQUIGGLY_UNDERLINE)
else:
style = "orgagenda.week." + str(matchCount)
matchCount = (matchCount + 1) % 10
self.MarkEntryAtRegion(lastMatchEntry,reg)
self.view.add_regions("week_" + str(date.day) + "_" + str(hour) + "_" + str(minSlot),[reg],style,"",sublime.DRAW_NO_FILL)
if(match != None):
if(lastMatch != match):
lastMatch = match
lastMatchEntry = matche
lastMatchStart = self.startOffset + (hour-dayStart)*self.cellSize + minSlot
d = distanceFromStart(matche, hour, minSlot)
# If the time slot is larger than the name we space pad it
c = " "
if(d < len(match.heading) and d >= 0):
c = match.heading[d:d+1]
self.view.insert(edit, self.view.size(), c)
else:
if(lastMatch != match):
lastMatch = match
lastMatchStart = self.startOffset + (hour-dayStart)*self.cellSize + minSlot
lastMatchEntry = matche
if(minSlot < 4):
self.view.insert(edit, self.view.size(), ".")
else:
self.view.insert(edit, self.view.size(), "_")
self.view.insert(edit, self.view.size(),"]\n")
def RenderView(self, edit):
self.InsertAgendaHeading(edit)
self.InsertTimeHeading(edit,self.now.hour)
toHighlight = []
#print(str(self.now))
wday = self.now.weekday()
# Adjust for Sunday being day 6 and we start with dunday
if(wday >= 6):
wday = -1
wstart = self.now + datetime.timedelta(days=-(wday+1))
dayNames = ["Sun","Mon", "Tue", "Wed", "Thr", "Fri", "Sat"]
dayOffset = sets.GetDateAsIndex("firstDayOfWeek","Sunday")
numDays = sets.Get("agendaWeekViewNumDays",7)
for i in range(0,numDays):
index = dayOffset + i
if(index == 0):
self.InsertDay(dayNames[index % len(dayNames)], wstart, edit)
else:
self.InsertDay(dayNames[index % len(dayNames)], wstart + datetime.timedelta(days=index) , edit)
def FilterEntry(self, n, filename):
rc = (not self.onlyTasks or (IsTodo(node) or IsDone(n))) and not IsProject(n) and HasTimestamp(n)
return rc
# ============================================================
class AgendaView(AgendaBaseView):
def __init__(self, name, setup=True, **kwargs):
super(AgendaView, self).__init__(name, setup, **kwargs)
self.blocks = [None,None,None,None,None,None,None]
self.sym = ("$","@","!","#","%","^","&")
self.symUsed = [-1,-1,-1,-1,-1,-1,-1]
def RenderDateHeading(self, edit, now):
headerFormat = sets.Get("agendaHeaderFormat","%A \t%d %B %Y")
self.view.insert(edit, self.view.size(), now.strftime(headerFormat) + "\n\n")
def BuildHabitDisplay(self, n):
if(n.scheduled and n.get_property("STYLE",None)):
#OrgDateRepeatedTask
repeats = n.repeated_tasks
habitbar = "[_____________________]"
hb = list(habitbar)
# not schedule but done
# not schedule not done
# scheduled but not done
# scheduled but last day
# late
# done
if(repeats):
start = self.now-drel.relativedelta(days=20)
cur = self.now-drel.relativedelta(days=21)
while(cur < self.now):
cur = n.scheduled.next_repeat_from(cur)
if(cur < self.now):
diff = (self.now - cur).days
diff = 21 - diff
hb[diff] = '.'
for i in range(0,21):
cur = start + drel.relativedelta(days=i)
for r in repeats:
if r.has_overlap(cur):
hb[i+1] = '*'
pass
return "H" + ''.join(hb)
return ""
def GetUnusedSymbol(self, blk):
start = 0
for i in range(0,len(self.symUsed)):
if(self.symUsed[i] >= 0):
start = i
break
for i in range(start,len(self.symUsed)):
if(self.symUsed[i] < 0):
self.symUsed[i] = blk
return i
return -1
def ReleaseSymbol(self, blk):
for i in range(0,len(self.symUsed)):
if(self.symUsed[i] == blk):
self.symUsed[i] = -1
break
def FindSymbol(self, blk):
for i in range(0,len(self.symUsed)):
if(self.symUsed[i] == blk):
return i
return 0
def ClearAgendaBlocks(self,h):
for i in range(0, len(self.blocks)):
n = self.blocks[i]
if(not IsInHour(n, h,self.now)):
self.ReleaseSymbol(i)
self.blocks[i] = None
def UpdateWithThisBlock(self, n, h):
idx = -1
for i in range(0, len(self.blocks)):
if(idx == -1 and self.blocks[i] == None):
idx = i
if(self.blocks[i] == n):
idx = -1
return i
if(idx != -1):
self.blocks[idx] = n
return idx
return 0
def GetAgendaBlocks(self,n,h):
out = ""
if(n != None):
symIdx = self.GetUnusedSymbol(0)
self.ClearAgendaBlocks(h)
myIdx = self.UpdateWithThisBlock(n, h)
self.symUsed[symIdx] = myIdx
else:
self.ClearAgendaBlocks(h)
spaceSym = "."
for i in range(0, len(self.blocks)):
if(self.blocks[i]):
spaceSym = " "
if(spaceSym == "."):
out = ".."
for i in range(0, len(self.blocks)):
if(not self.blocks[i]):
out = out + spaceSym
else:
symIdx = self.FindSymbol(i)
out = out + self.sym[symIdx]
return out
def RenderAgendaEntry(self,edit,filename,n,h,ts):
view = self.view
if(IsRawDate(ts)):
view.insert(edit, view.size(), "{0:12} {1:02d}:{2:02d}B[{7}] {3} {4:45} {5}{6}\n".format(filename if (len(filename) <= 12) else filename[:11] + ":" , h, ts.minute, n.todo if n.todo else "", n.heading, self.BuildDeadlineDisplay(n), self.BuildHabitDisplay(n), self.GetAgendaBlocks(n,h)))
else:
view.insert(edit, view.size(), "{0:12} {1:02d}:{2:02d}B[{7}] {3} {4:45} {5}{6}\n".format(filename if (len(filename) <= 12) else filename[:11] + ":" , h, ts.start.minute, n.todo if n.todo else "", n.heading, self.BuildDeadlineDisplay(n), self.BuildHabitDisplay(n), self.GetAgendaBlocks(n,h)))
def BuildDeadlineDisplay(self, node):
if(node.deadline):
if(EnsureDateTime(node.deadline.deadline_start) <= self.now):
if(EnsureDateTime(node.deadline.start).date() < self.now.date()):
return "D: Overdue"
elif(EnsureDateTime(node.deadline.start).date() == self.now.date()):
return "D: Due Today"
else:
return "D:@" + str(EnsureDateTime(node.deadline.start).date())
else:
return ""
def RenderView(self, edit):
self.InsertAgendaHeading(edit)
self.RenderDateHeading(edit, self.now)
view = self.view
dayStart = sets.Get("agendaDayStartTime",6)
dayEnd = sets.Get("agendaDayEndTime",19)
allDat = []