-
Notifications
You must be signed in to change notification settings - Fork 5
/
ikog.py
2866 lines (2646 loc) · 106 KB
/
ikog.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Run the script for details of the licence
# or refer to the notice section later in the file.
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#!<^DATA
#!<^CONFIG
cfgColor = 0
cfgAutoSave = True
cfgReviewMode = True
cfgSysCalls = False
cfgEditorNt = "edit"
cfgEditorPosix = "nano,pico,vim,emacs"
cfgShortcuts = ['', '', '', '', '', '', '', '', '', '']
cfgAbbreviations = {}
cfgPAbbreviations = {}
#!<^CODE
import sys
import os
import re
from datetime import date, datetime
from datetime import timedelta
import platform
import urllib
import getpass
from hashlib import md5
import struct
import tempfile
from threading import Timer
import stat
supportAes = True
try:
import pyRijndael
except:
supportAes = False
supportReadline = True
try:
import readline
except:
supportReadline = False
usePlugin = True
try:
import ikogPlugin
except:
usePlugin = False
notice = [
"ikog.py v 1.90 2008-11-14",
"Copyright (C) 2006-2008 S. J. Butler",
"Visit http://www.henspace.co.uk for more information.",
"This program is free software; you can redistribute it and/or modify",
"it under the terms of the GNU General Public Licence as published by",
"the Free Software Foundation; either version 2 of the License, or",
"(at your option) any later version.",
"",
"This program is distributed in the hope that it will be useful,",
"but WITHOUT ANY WARRANTY; without even the implied warranty of",
"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the",
"GNU General Public License for more details. The license is available",
"from http://www.gnu.org/licenses/gpl.txt"
]
banner = [
" _ _ ",
" (_) | | __ ___ __ _",
" | | | |/ / / _ \ / _` |",
" | | | < | (_) | | (_| |",
" |_| |_|\_\ \___/ \__, |",
" _ _ _ |___/",
" (_) | |_ | | __ ___ ___ _ __ ___ ___ _ __",
" | | | __| | |/ / / _ \ / _ \ | '_ \ / __| / _ \ | '_ \ ",
" | | | |_ | < | __/ | __/ | |_) | \__ \ | (_) | | | | |",
" |_| \__| |_|\_\ \___| \___| | .__/ |___/ \___/ |_| |_|",
" |_| _",
" __ _ _ __ ___ __ __ (_) _ __ __ _ ",
" / _` | | '__| / _ \ \ \ /\ / / | | | '_ \ / _` |",
" | (_| | | | | (_) | \ V V / | | | | | | | (_| | _",
" \__, | |_| \___/ \_/\_/ |_| |_| |_| \__, | (_)",
" |___/ |___/",
]
magicTag = "#!<^"
gMaxLen = 80
try:
ruler = "~".ljust(gMaxLen - 1, "~")
divider = "_".ljust(gMaxLen - 1, "_")
except Exception:
print "Error found. Probably wrong version of Python"
gReqPythonMajor = 2
gReqPythonMinor = 4
def safeRawInput(prompt):
try:
entry = raw_input(prompt)
except:
print "\n"
entry = ""
return entry
### global compare function
def compareTodo(a, b):
return cmp(a.getEffectivePriority(), b.getEffectivePriority())
def printError(msg):
print gColor.code("error") + "ERROR: " + msg + gColor.code("normal")
def clearScreen(useSys = False):
if useSys:
if os.name == "posix":
os.system("clear")
elif os.name in ("dos", "ce", "nt"):
os.system("cls")
print "\n"*25
for l in banner:
print l
### XTEA algorithm public domain
class Xtea:
def __init__(self):
pass
def crypt(self, key,data,iv='\00\00\00\00\00\00\00\00',n=32):
def keygen(key,iv,n):
while True:
iv = self.xtea_encrypt(key,iv,n)
for k in iv:
yield ord(k)
xor = [ chr(x^y) for (x,y) in zip(map(ord,data),keygen(key,iv,n)) ]
return "".join(xor)
def xtea_encrypt(self, key,block,n=32):
v0,v1 = struct.unpack("!2L",block)
k = struct.unpack("!4L",key)
sum,delta,mask = 0L,0x9e3779b9L,0xffffffffL
for round in range(n):
v0 = (v0 + (((v1<<4 ^ v1>>5) + v1) ^ (sum + k[sum & 3]))) & mask
sum = (sum + delta) & mask
v1 = (v1 + (((v0<<4 ^ v0>>5) + v0) ^ (sum + k[sum>>11 & 3]))) & mask
return struct.pack("!2L",v0,v1)
class WordWrapper:
def __init__(self, width):
self.width = width
self.nLines = 0
self.pos = 0
def addLine(self, pos):
self.pos = pos
self.nLines = self.nLines + 1
def getNLines(self):
return self.nLines
def intelliLen(self, text):
return len(gColor.stripCodes(text))
def wrap(self, text):
self.nLines = 0
formatted = text.replace("<br>", "\n").replace("<BR>", "\n")
lines = formatted.splitlines()
out = ""
self.pos = 0
for thisline in lines:
newline = True
words = thisline.split()
if self.pos != 0:
out = out + "\n"
self.addLine(0)
for w in words:
wlen = self.intelliLen(w) + 1
if (self.pos + wlen) == self.width:
out = out + " " + w
self.addLine(0)
elif (self.pos + wlen) < self.width:
if newline:
out = out + w
self.pos = wlen
else:
out = out + " " + w
self.pos = self.pos + wlen + 1
else:
out = out + "\n" + w
self.addLine(wlen)
newline = False
return out
### Color code class for handling color text output
class ColorCoder:
NONE = -1
ANSI = 0
codes = [{"normal":"\x1b[0;37;40m",
"title":"\x1b[1;32;40m",
"heading":"\x1b[1;35;40m",
"bold":"\x1b[1;35;40m",
"important":"\x1b[1;31;40m",
"error":"\x1b[1;31;40m",
"reverse":"\x1b[0;7m",
"row0":"\x1b[0;35;40m",
"row1":"\x1b[0;36;40m"},
{"normal":"\x1b[0;37m",
"title":"\x1b[1;32m",
"heading":"\x1b[1;35m",
"bold":"\x1b[1;35m",
"important":"\x1b[1;31m",
"error":"\x1b[1;31m",
"reverse":"\x1b[0;7m",
"row0":"\x1b[0;35m",
"row1":"\x1b[0;36m"}]
def __init__(self, codeset):
self.codeSet = self.NONE
self.setCodeSet(codeset)
def stripCodes(self, text):
# strip out the ansi codes
ex = re.compile("\x1b\[[0-9;]*m")
return ex.sub("", text)
def setCodeSet(self, codeset):
old = self.codeSet
if codeset < 0:
self.codeSet = self.NONE
elif codeset < len(self.codes):
self.codeSet = codeset
return (old != self.codeSet)
def isValidSet(self, myset):
if myset < len(self.codes):
return True
else:
return False
def colorSupported(self):
return (os.name == "posix" or os.name == "mac")
def usingColor(self):
return (self.codeSet != self.NONE and self.colorSupported())
def code(self, type):
if self.codeSet == self.NONE or not self.colorSupported():
return ""
else:
return self.codes[self.codeSet][type]
def printCode(self, type):
if self.codeSet != self.NONE:
print self.code(type),
def getCodeSet(self):
return self.codeSet
### Viewer class for paging through multiple lines
class ListViewer:
def __init__(self, maxlines):
self.maxlines = maxlines
def show(self, list, pause):
count = 0
for line in list:
if count >= self.maxlines or line == pause:
io = safeRawInput("--- Press enter for more. Enter s to skip ---").strip()
print ""
if len(io) > 0 and io.upper()[0] == "S":
break
count = 0
if line != pause:
print line
count = count + 1
### Handler for encryption
class Encryptor:
TYPE_OBSCURED = "xtea_"
TYPE_AES = "aes_"
SALT_64 = "1hJ8*gpQ"
def __init__(self):
self.key = ""
self.encryptionType = self.TYPE_OBSCURED
def setType(self, codeType):
if codeType == self.TYPE_AES and supportAes == False:
self.encryptionType = self.TYPE_OBSCURED
else:
self.encryptionType = codeType
return self.encryptionType
def setKey(self, key):
self.key = key
def getKey(self):
return self.key
def enterKey(self, prompt1, prompt2):
done = False
while not done:
input1 = getpass.getpass(prompt1 + " >>>")
if prompt2 != "":
input2 = getpass.getpass(prompt2 + " >>>")
if input1 != input2:
print "You must enter the same password. Start again"
else:
done = True
else:
done = True
self.key = input1
return input1
def complexKey(self):
return md5(self.key).digest()
def getSecurityClass(self, encrypted):
if encrypted.startswith(self.TYPE_OBSCURED):
return "private xtea"
if encrypted.startswith(self.TYPE_AES):
return "secret aes"
return "unknown"
def obscure(self, plainText):
key = self.complexKey()
obscured = Xtea().crypt(key, plainText, self.SALT_64)
return self.TYPE_OBSCURED + obscured.encode('hex_codec')
def unobscure(self, obscured):
plain = ""
data = obscured[len(self.TYPE_OBSCURED):]
data = data.decode('hex_codec')
key = self.complexKey()
plain = Xtea().crypt(key, data, self.SALT_64)
return plain
def encryptAes(self, plainText):
if len(self.key) < 16:
key = self.complexKey()
else:
key = self.key
obscured = pyRijndael.EncryptData(key, plainText)
return self.TYPE_AES + obscured.encode('hex_codec')
def decryptAes(self, encrypted):
plain = ""
data = encrypted[len(self.TYPE_AES):]
data = data.decode('hex_codec')
if len(self.key) < 16:
key = self.complexKey()
else:
key = self.key
plain = pyRijndael.DecryptData(key, data)
return plain
def enterKeyAndEncrypt(self, plainText):
self.enterKey("Enter the master password.", "Re-enter the master password")
return self.encrypt(plainText)
def encrypt(self, plainText):
if self.encryptionType == self.TYPE_AES:
return self.encryptAes(plainText)
else:
return self.obscure(plainText)
def enterKeyAndDecrypt(self, encryptedText):
self.enterKey("Enter your master password", "")
return self.decrypt(encryptedText)
def decrypt(self, encryptedText):
if encryptedText.startswith(self.TYPE_AES):
if not supportAes:
return "You do not have the pyRinjdael module so the text cannot be decrypted."
else:
return self.decryptAes(encryptedText)
else:
return self.unobscure(encryptedText)
### Handler for user input
class InputParser:
def __init__(self, prompt):
self.prompt = prompt
def read(self, entry = ""):
if entry == "":
entry = safeRawInput(self.prompt)
entry = entry.strip()
if entry == "":
command = ""
line = ""
else:
if usePlugin:
entry = ikogPlugin.modifyUserInput(entry)
if entry.find(magicTag) == 0:
printError("You cannot begin lines with the sequence " + magicTag)
command = ""
line = ""
elif entry.find(TodoItem.ENCRYPTION_MARKER) >= 0:
printError ("You cannot use the special sequence " + TodoItem.ENCRYPTION_MARKER)
command = ""
line = ""
else:
n = entry.find(" ")
if n >= 0:
command = entry[:n]
line = entry[n + 1:]
else:
command = entry
line = ""
return (command, line)
class EditorLauncher:
WARNING_TEXT = "# Do not enter secret or private information!"
def __init__(self):
pass
def edit(self, text):
ed = ""
terminator = "\n"
if os.name == "posix":
ed = cfgEditorPosix
elif os.name == "nt":
ed = cfgEditorNt
terminator = "\r\n"
if ed == "":
printError("Sorry, but external editing not supported on " + os.name.upper())
success = False
else:
fname = self.makeFile(text, terminator)
if fname == "":
printError("Unable to create temporary file.")
else:
success = self.run(ed, fname)
if success:
(success, text) = self.readFile(fname)
if text == self.orgText:
print("No changes made.");
success = False
self.scrubFile(fname)
if success:
return text
else:
return ""
def scrubFile(self, fname):
try:
os.remove(fname)
except Exception, e:
printError("Failed to remove file " + fname + ". If you entered any private data you should delete this file yourself.")
def readFile(self, fname):
success = False
try:
fh = open(fname, "rt")
line = fh.readline()
text = ""
first = True
while line != "":
thisLine = self.safeString(line)
if thisLine != self.WARNING_TEXT:
if not first:
text = text + "<br>"
text = text + thisLine
first = False
line = fh.readline()
fh.close()
success = True
except Exception, e:
printError("Error reading the edited text. " + str(e))
return (success, text)
def safeString(self, text):
return text.replace("\r","").replace("\n","")
def makeFile(self, text, terminator):
fname = ""
(fh, fname) = tempfile.mkstemp(".tmpikog","ikog")
fout = os.fdopen(fh,"wt")
text = text.replace("<BR>", "<br>")
self.orgText = text
lines = text.split("<br>")
fout.write(self.WARNING_TEXT + terminator)
for thisline in lines:
fout.write(self.safeString(thisline) + terminator)
fout.close()
return fname
def run(self, program, file):
progs = program.split(",")
for prog in progs:
success = self.runProgram(prog.strip(), file)
if success:
break;
return success
def runProgram(self, program, file):
success = False
if os.name == "posix":
try:
progarg = program
os.spawnlp(os.P_WAIT, program, progarg, file)
success = True
except os.error:
pass
except Exception, e:
printError(str(e))
elif os.name == "nt":
if file.find(" ") >= 0:
file = "\"" + file + "\""
for path in os.environ["PATH"].split(os.pathsep):
try:
prog = os.path.join(path, program)
if prog.find(" ") >= 0:
progarg = "\"" + prog + "\""
else:
progarg = prog
os.spawnl(os.P_WAIT, prog, progarg, file)
success = True
if success:
break
except os.error:
pass
except Exception, e:
printError(str(e))
return success
### An abstraction over commands
class BaseCommand(object):
def __init__(self, name, shortdesc='', helpdesc='', aliases=[]):
'''func should accept two args: todolist and line'''
self.name = name
self.shortdesc = shortdesc
self.helpdesc = helpdesc
self.aliases = aliases
def run(self, todo, line):
'''This MUST be overridden'''
raise NotImplementedError
class TopCommand(BaseCommand):
def __init__(self):
BaseCommand.__init__(self, 'TOP', 'Go to top', '', ['T'])
def run(self, todo, line):
todo.currentTask = 0
if line != "":
todo.setFilterArray(True, "")
todo.showLocalFilter()
todo.printShortList(line)
truncateTask = True
class GoCommand(BaseCommand):
def __init__(self):
BaseCommand.__init__(self, 'GO', 'GO N\tDisplay task N', '', ['G'])
def run(self, todo, line):
todo.moveTo(line)
class PabCommand(BaseCommand):
def __init__(self):
BaseCommand.__init__(self, 'PAB',
'PAB :px :pfull\tProject abbreviation. :px expands to :pfull',
'')
def run(self, todo, line):
if line.strip() == "?":
todo.showPAbbreviations()
elif todo.setPAbbreviation(line):
todo.save("")
class ListFileCommand(BaseCommand):
def __init__(self):
BaseCommand.__init__(self, 'LISTF',
"LISTF [outputfile] [LISTARGS]\touptut LIST to outputfile",
'Executes LIST and redirect its output to outputfile.\n'
'If outputfile is not given, redirect to "output".\n'
'LISTARGS is any output you can give to LIST:'
'see "HELP LIST" for more details\n',
['LF'])
def run(self, todo, line):
splitted_line = [word for word in line.split(' ', 1) if word]
if not splitted_line:
output_file = 'output'
else:
output_file = splitted_line[0]
if len(splitted_line) < 2:
list_args = ''
else:
list_args = splitted_line[1]
old_out = sys.stdout
print ruler
sys.stdout = open(output_file, 'w')
todo.setFilterArray(True, list_args)
#todo.showLocalFilter()
todo.printList(False, "", "")
todo.clearFilterArray(True)
truncateTask = True
sys.stdout = old_out
print "Output sent to %s" % output_file
print ruler
class HelpCommand(BaseCommand):
def __init__(self):
BaseCommand.__init__(self, 'HELP',
"HELP [command]\tShow help. If command is given, show help for that",
'', ['H'])
def run(self, todo, line):
if not line.strip():
todo.printHelp(todo.help)
return
if len(line.strip().split()) > 1 or line.strip() not in todo.commands:
print "Can't understand. You should give a command name, or nothing to receive a complete help"
else:
cmd = todo.commands[line.strip()]
print cmd.shortdesc
if cmd.helpdesc:
print '--'
print cmd.helpdesc
class ModCommand(BaseCommand):
def __init__(self):
BaseCommand.__init__(self, 'MOD',
"MOD/M N [text] : modify task N.",
'',
['M'])
def run(self, todo, line):
if todo.modifyTask(line, TodoItem.MODIFY):
todo.sortByPriority()
todo.save("")
else:
printCurrent = False
class ListCommand(BaseCommand):
def __init__(self):
BaseCommand.__init__(self, 'LIST',
"LIST [filter]\tlist tasks",
"Filter = context, project, priority, date\n"
": or word. Contexts begin with @ and projects with :p\n"
": Dates begin with :d, anything else is a search word.\n"
": Precede term with - to exclude e.g. -@Computer\n",
['L'])
def run(self, todo, line):
print ruler
todo.setFilterArray(True, line)
todo.showLocalFilter()
todo.printList(False, "", "")
todo.clearFilterArray(True)
print ruler
truncateTask = True
class EdCommand(BaseCommand):
def __init__(self):
BaseCommand.__init__(self, 'EDIT',
"EDIT/ED [N]\tCreate task, or edit task N, using external editor.",
'', ['ED'])
def run(self, todo, line):
if not todo.sysCalls:
todo.showError("External editing needs to use system calls. Use SYS ON to enable them.")
elif line == "":
todo.addTaskExternal()
elif todo.modifyTask(line, TodoItem.MODIFY, externalEditor = True):
todo.sortByPriority()
todo.save("")
else:
printCurrent = False
class AbCommand(BaseCommand):
def __init__(self):
BaseCommand.__init__(self, 'ABBREV',
"ABBREV/AB @x @full\tCreate new abbreviation. @x expands to @full",
'', ['AB'])
def run(self, todo, line):
if line.strip() == "?":
todo.showAbbreviations()
elif todo.setAbbreviation(line):
todo.save("")
### The main todo list
class TodoList:
quickCard = ["Quick reference card:",
"? ADD/A/+ text FILTER/FI [filter]",
"HELP/H IMMEDIATE/I/++ text TOP/T [N]",
"COLOR/COLOUR/C [N] KILL/K/X/- N NEXT/N",
"MONOCHROME/MONO CLEAR PREV/P",
"EXPORT REP/R N [text] GO/G N",
"IMPORT file MOD/M N [text] LIST/L [filter]",
"REVIEW/REV ON/OFF EXTEND/E N [text] LIST>/L> [filter]",
"V0 EDIT/ED [N] @",
"V1 SUB/SU N /s1/s2/ :D",
"WEB FIRST/F N :P>",
"SAVE/S DOWN/D N @>",
"AUTOSAVE/AS ON|OFF UP/U N :D>",
"VER/VERSION NOTE/NOTES text :P>",
"CLEARSCREEN/CLS O/OPEN file SHOW N",
"SYS ON|OFF NEW file SETEDxx editor",
"!CMD command 2 ABBREV/AB @x @full",
"ABBREV/AB ? PAB ? PAB :px :pfull",
"SHORTCUT/SC N cmd SHORTCUT/SC ? =N",
"ARCHIVE/DONE N [text]",
]
help = [ "",
"Introduction",
"------------",
"The program is designed to help manage tasks using techniques",
"such as Getting Things Done by David Allen. Check out",
"http://www.henspace.co.uk for more information and detailed help.",
"To use the program, simply enter the task at the prompt.",
"All of the commands are displayed in the next section.",
"!PAUSE!",
"COMMANDS",
"--------",
"Commands that have more than one method of entry are shown separated by /",
"e.g HELP/H means that you can enter either HELP or an H.",
"All commands can be entered in upper or lower case.",
"Items shown in square brackets are optional.",
"Items shown separated by the | symbol are alternatives. e.g ON|OFF means",
"you should type either ON or OFF.",
"Note that some commands refer to adding tasks to the top or bottom of the",
"list. However the task's position in the list is also determined by its.",
"priority. So, for example, adding a task to the top will still not allow",
"it to precede tasks that have been assigned a higher priority number. ",
"!PAUSE!",
"GENERAL COMMANDS",
"----------------",
"? : displays a quick reference card",
"HELP/H : displays this help.",
"VERSION/VER : display the version.",
"WEB : Go to the website for more information",
"CLEARSCREEN/CLS : Clear the screen",
"COLOR/COLOUR/C [N] : Use colour display (not Windows) N=1 for no background",
"MONOCHROME/MONO : Use monochrome display",
"EXPORT : Export the tasks only to filename.tasks.txt",
"IMPORT file : Import tasks from the file",
"REVIEW/REV ON|OFF : If on, hitting enter moves to the next task",
" : If off, enter re-displays the current task",
"V0 : Same as REVIEW OFF",
"V1 : Same as REVIEW ON",
"SAVE/S : Save the tasks",
"O/OPEN file : Open a new data file.",
"NEW file : Create a new data file.",
"AUTOSAVE/AS ON|OFF : Switch autosave on or off",
"SYS ON|OFF : Allow the program to use system calls.",
"!CMD command : Run a system command.",
"2 : Start a two minute timer (for GTD)",
"QUIT/Q : quit the program",
"!PAUSE!",
"TASK ENTRY AND EDITING COMMANDS",
"-------------------------------",
"For the editing commands that require a task number, you can",
"replace N by '^' or 'this' to refer to the current task.",
"ADD/A/+ the task : add a task to the bottom of the list.",
" : Entering any line that does not begin with",
" : a valid command and which is greater than 10",
" : characters long is also assumed to be an addition.",
"EDIT/ED [N] : Create task, or edit task N, using external editor.",
"SUB/SU N /s1/s2/ : Replace text s1 with s2 in task N. Use \/ if you",
" : need to include the / character.",
"NOTE/NOTES text : shorthand for ADD #0 @Notes text",
"IMMEDIATE/I/++ : add a task to the top of the list to do today.",
"REP/R N [text] : replace task N",
"MOD/M N [text] : modify task N.",
"EXTEND/E N [text] : add more text to task N",
"FIRST/F N : move task N to the top.",
"DOWN/D/ N : move task N down the queue",
"UP/U/ N : move task N up the queue",
"!PAUSE!",
"TASK REMOVAL COMMANDS",
"---------------------",
"KILL/K/X/- N : kill (delete) task N. You must define N",
"DONE N [text] : Remove task N and move to an archive file",
"ARCHIVE N [text] : Same as DONE",
"CLEAR : Remove all tasks",
"!PAUSE!",
"DISPLAY COMMANDS",
"----------------",
"SHOW N : display encrypted text for task N",
"FILTER/FI [filter] : set a filter. Applies to all displays",
" : See list for details of the filter",
" : Setting the filter to nothing clears it.",
"TOP/T [N] : Go to top, list N tasks, and display the top task",
"NEXT/N : display the next task. Same as just hitting enter",
"PREV/P : display previous task",
"GO/G N : display task N",
"LIST/L [filter] : list tasks. Filter = context, project, priority, date",
" : or word. Contexts begin with @ and projects with :p",
" : Dates begin with :d, anything else is a search word.",
" : Precede term with - to exclude e.g. -@Computer",
" : e.g LIST @computer or LIST #5",
"@ : sorted list by Context.",
":D : sorted list by Dates",
":P : sorted list by Projects",
"LIST>/L> [filter] : standard list sent to an HTML report",
"@> : sorted list by Context sent to an HTML report",
":D> : sorted list by Dates sent to an HTML report",
":P> : sorted list by Projects sent to an HTML report",
" : The HTML reports are sent to todoFilename.html",
"!PAUSE!",
"ADVANCED OPTIONS",
"----------------",
"The SETEDxxx commands allow you to use an external editor.",
"Note the editor you pick should be a simple text editor. If you pick",
"something that doesn't work, try the defaults again.",
"Because some systems may have different editors installed, you can set",
"more than one by separating the editors usng commas. The program will",
"use the first one it finds.",
"For Windows the default is edit, which works quite well in the terminal",
"but you could change it to notepad.",
"For Linux, the default is nano,pico,vim,emacs.",
"To use external editors you must switch on system calls using the SYS ON",
"command",
"SETEDNT command : Set the external editor for Windows (NT).",
"SETEDPOSIX command : Set the editor for posix systems.",
" : e.g. SETEDNT edit",
" : SETEDPOSIX nano,vim",
"SHORTCUT/SC ? : list shortcuts",
"SHORTCUT/SC N cmd : Set shortcut N to command cmd",
"=N : Run shortcut N",
"!PAUSE!",
"ABBREV/AB @x @full : Create new abbreviation. @x expands to @full",
"ABBREV/AB ? : List context abbreviations.",
"PAB :px :pfull : Project abbreviation. :px expands to :pfull",
"PAB ? : List project abbreviations.",
"!PAUSE!",
"ENTERING TASKS",
"--------------",
"When you enter a task, you can embed any number of contexts in the task.",
"You can also embed a project description by preceding it with :p",
"You can assign a priority by preceding a number by #. e.g. #9.",
"If you don't enter a number, a default of 5 is used. The higher the ",
"number the more important it is. Priorities range from 1 to 10.",
"Only the first # is used for the priority so you can use # as",
"a normal character as long as you precede it with a priority number.",
"You can define a date when the task must be done by preceding the date",
"with :d, i.e :dYYYY/MM/DD or :dMM/DD or :dDD. If you omit the year/month",
"they default to the current date. Adding a date automatically creates an",
"@Date context for the task.",
"So, for example, to add a new task to e-mail Joe, we could enter:",
"+ e-mail joe @computer",
"or to add a task to the decorating project, we could enter:",
"+ buy wallpaper :pdecorating",
"to enter a task with an importance of 9 we could enter:",
"+ book that holiday #9 @Internet",
"!PAUSE!",
"MODIFYING AND EXTENDING TASKS",
"-----------------------------",
"The modify command allows you to change part of an existing task.",
"So for example, imagine you have a task:",
"[05] Buy some food #9 @Internet Projects:Shopping",
"Enter the command M 5 and then type:",
"@C",
"Because the only element we have entered is a new context, only",
"that part is modified, so we get.",
"[05] Buy some food #9 @Computer Projects:Shopping",
"Likewise, had we entered:",
"Buy some tea :pEating",
"We would have got",
"[05] Buy some tea #9 @Internet Projects:Eating",
"The extend command is similar but it appends the entry. So had",
"we used the command E 5 instead of M 5 the result would have been",
"[05] Buy some food ... Buy some tea #9 @Internet Projects:Eating",
"!PAUSE!",
"CONTEXTS",
"--------",
"Any word preceded by @ will be used as a context. Contexts are like",
"sub-categories or sub-lists. There are a number of pre-defined",
"abbreviations that you can use as well. The recognised abbreviations",
"are:",
"@A = @Anywhere (this is the default)",
"@C = @Computer",
"@D = @Desk",
"@E = @Errands",
"@H = @Home",
"@I = @Internet",
"@L = @Lunch",
"@M = @Meeting",
"@N = @Next",
"@O = @Other",
"@P = @Phone",
"@PW= @Password",
"@S = @Someday/maybe",
"@W4= @Waiting_for",
"@W = @Work",
"!PAUSE!",
"ENTERING DATES",
"--------------",
"An @Date context is created if you embed a date in the task.",
"Dates are embedded using the :dDATE format.",
"Valid DATE formats are yyyy-mm-dd, mm-dd or dd",
"You can also use : or / as the separators. So, for example:",
":d2006/12/22 or :d2006-11-7 or :d9/28 are all valid entries.",
"",
"If you set a date, then until that date is reached, the task is given",
"an effective priority of 0. Once the date is reached, the task's",
"priority is increased by 11, moving it to the of the list.",
"",
"A date entry of :d0 can be used to clear a date entry.",
"A date entry of :d+X can be used to create a date entry of today + X days.",
"So :d+1 is tomorrow and :d+0 is today.",
"!PAUSE!",
"ENCRYPTING TEXT",
"---------------",
"If you want to encrypt text you can use the <private> or <secret> tags or",
"their abbreviations <p> and <s>.",
"These tags will result in all text following the tag to be encrypted.",
"Note that any special commands, @contexts for example, are treated as plain",
"text in the encrypted portion.",
"To display the text you will need to use the SHOW command.",
"",
"The <private> tag uses the inbuilt XTEA algorithm. This is supposedly a",
"relatively secure method but probably not suitable for very sensitive data.",
"",
"The <secret> tag can only be used if you have the pyRijndael.py module.",
"This uses a 256 bit Rinjdael cipher. The module can be downloaded from ",
"http://jclement.ca/software/pyrijndael/",
"You can install this in your Python path or just place it alongside your",
"ikog file.",
"Note you cannot use the extend command with encrypted text.",
"",
"!PAUSE!",
"MARKING TASKS AS COMPLETE",
"-------------------------",
"The normal way to mark a task as complete is just to remove it using the",
"KILL command. If you want to keep track of tasks you have finished, you",
"can use the ARCHIVE or DONE command. This gives the task an @Archived",
"context, changes the date to today and then moves it from the current",
"file to a file with archive.dat appended. The archive file is a valid",
"ikog file so you can use the OPEN command to view it, edit it and run",
"reports in the normal way. So assuming your current script is ikog.py,",
"to archive the current task you could enter:",
"",
"ARCHIVE ^ I have finished this",
"",
"This would move the task to a file called ikog.py.archive.dat",
"",
"!PAUSE!",
"USING EXTERNAL DATA",
"-------------------",
"Normally the tasks are embedded in the main program file so all you have",
"to carry around with you is the ikog.py file. The advantage is that you",
"only have one file to look after; the disadvantage is that every time you",
"save a task you have to save the program as well. If you want, you can",
"keep your tasks in a separate file.",
"To do this, use the EXPORT function to create a file ikog.py.tasks.txt",
"Use the CLEAR command to remove the tasks from your main ikog.py program.",
"Rename the exported file from ikog.py.tasks.txt to ikog.py.dat",
"Ikog will now use this file for storing your tasks.",
"",
"!PAUSE!",
"PASSING TASKS VIA THE COMMAND LINE",
"----------------------------------",
"It is possible to add tasks via the command line. The general format of",
"the command line is:",
" ikog.py filename commands",
"The filename is the name of the data file containing your tasks. You",
"can use . to represent the default internal tasks.",
"Commands is a set of normal ikog commands separated by the / ",
"character. Note there must be a space either side of the /.",
"So to add a task and then exit the program we could just enter:",
" ikog.py . + here is my task / QUIT",
"Note that we added the quit command to exit ikog.",
"You must make sure that you do not use any commands that require user",
"input. Deleting tasks via the command line is more complicated as you",
"need to find the task automatically. If you do try to delete this way,",
"use the filter command to find some unique text and then delete it. eg.",
" ikog.py . FI my_unique_text / KILL THIS / QUIT",
"Use THIS instead of ^ as a caret has a special meaning in Windows.",
"If you do intend automating ikog from the command line, you should add",
"a unique reference to each task so you can find it later using FILTER. eg.",
"+ this is my task ref_1256",
"!PAUSE!"]
MOVE_DOWN = 0
MOVE_UP = 1
MOVE_TOP = 2
MAX_SHORTCUTS = 10
def __init__(self, todoFile, externalDataFile):
self.setShortcuts()
self.dirty = False
self.code = []
self.todo = []
self.autoSave = True
self.review = True
self.sysCalls = False
self.currentTask = 0
self.globalFilterText = ""
self.globalFilters = []
self.localFilterText = ""
self.localFilters = []
# split the file into the source code and the todo list
self.filename = todoFile
self.commands = {}
for Command in BaseCommand.__subclasses__():
cmd_instance = Command()
self.commands[cmd_instance.name] = cmd_instance
try: