forked from ihdavids/orgextended
-
Notifications
You must be signed in to change notification settings - Fork 0
/
orgtableformula.py
2746 lines (2513 loc) · 91.6 KB
/
orgtableformula.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 sublime
import sublime_plugin
import datetime
import re
#from pathlib import Path
import os
#import fnmatch
#import OrgExtended.orgparse.node as node
import OrgExtended.orgutil.util as util
import logging
#import sys
import traceback
import OrgExtended.orgdb as db
import OrgExtended.asettings as sets
import OrgExtended.pymitter as evt
import OrgExtended.orginsertselected as ins
import OrgExtended.simple_eval as simpev
import OrgExtended.orgextension as ext
import OrgExtended.orgparse.date as orgdate
import OrgExtended.orgduration as orgduration
import OrgExtended.orgtableplot as orgplot
import math
import random
import ast
import operator as op
import subprocess
import platform
import time
import json
import ast
random.seed()
RE_TABLE_LINE = re.compile(r'\s*[|]')
RE_PRINTFSTYLE = re.compile(r"(?P<formatter>[%][0-9]*\.[0-9]+f)")
RE_ISCOMMENT = re.compile(r"^\s*[#][+]")
RE_AUTOLINE = re.compile(r"^\s*[|]\s*[#]\s*[|]")
RE_AUTOCOMPUTE = re.compile(r"^\s*[|]\s*(?P<a>[#_$^*!/ ])\s*[|]")
RE_END_BLOCK = re.compile(r'^\s*[#][+](END|end)[:]\s*')
MAX_STRING_LENGTH = 100000
MAX_COMPREHENSION_LENGTH = 10000
MAX_POWER = 4000000 # highest exponent
highlightEnabled = True
log = logging.getLogger(__name__)
def isTable(view,at=None):
if(at == None):
at = view.sel()[0].end()
names = view.scope_name(at)
return 'orgmode.table' in names
def isTableFormula(view):
names = view.scope_name(view.sel()[0].end())
return 'orgmode.tblfm' in names
def isTableLine(line):
return RE_TABLE_LINE.search(line)
def isAutoComputeRow(view):
return None != RE_AUTOLINE.search(view.curLineText())
opsTable = None
def GetOps():
global opsTable
if(opsTable == None):
o = simpev.DEFAULT_OPERATORS.copy()
o[ast.Mult] = safe_mult
o[ast.Add] = safe_add
o[ast.Pow] = safe_pow
o[ast.Sub] = tsub
o[ast.Div] = tdiv
o[ast.Mod] = tmod
o[ast.Eq] = teq
o[ast.NotEq] = tneq
o[ast.Gt] = tgt
o[ast.Lt] = tlt
o[ast.GtE] = tge
o[ast.LtE] = tle
o[ast.Not] = tnot
o[ast.USub] = tusub
o[ast.UAdd] = tuadd
opsTable = o
return opsTable
def add_dynamic_symbols(s):
exts = sets.Get("enableTableExtensions",None)
if(exts):
dynamic = ext.find_extension_modules('orgtable', [])
for k in dynamic.keys():
if(hasattr(dynamic[k],"AddSymbols")):
try:
dynamic[k].AddSymbols(s)
except:
log.error("Failed to add symbols from: " + str(k) + "\n" + traceback.format_exc())
else:
if(not hasattr(dynamic[k],"Execute")):
log.warning("Dynamic table module does not have method AddSymbols, cannot use: " + k)
constsTable = None
def GetConsts():
global constsTable
reloadExtensions = sets.Get("forceLoadExternalExtensions",False)
if(constsTable == None or reloadExtensions):
n = simpev.DEFAULT_NAMES.copy()
n['pi'] = 3.1415926535897932385
n['t'] = True
n['true'] = True
n['True'] = True
n['false'] = False
n['False'] = False
n['nil'] = None
n['None'] = None
add_dynamic_symbols(n)
constsTable = n
return constsTable
# These are table extensions you would like to add
# for performance reasons we only reload them when you start sublime
# you can however turn on forceLoadExternalExtensions to reload the
# extension dynamically ALL THE TIME. do not leave that one though!
def add_dynamic_functions(f):
exts = sets.Get("enableTableExtensions",None)
if(exts):
dynamic = ext.find_extension_modules('orgtable', [])
for k in dynamic.keys():
if(hasattr(dynamic[k],"Execute")):
f[k] = dynamic[k].Execute
else:
if(not hasattr(dynamic[k],"AddSymbols")):
log.warning("Dynamic table module does not have method Execute, cannot use: " + k)
functionsTable = None
def GetFunctions():
global functionsTable
reloadExtensions = sets.Get("forceLoadExternalExtensions",False)
if(functionsTable == None or reloadExtensions):
f = simpev.DEFAULT_FUNCTIONS.copy()
f['vmean'] = vmean
f['vmedian'] = vmedian
f['vmax'] = vmax
f['vmin'] = vmin
f['vsum'] = vsum
f['tan'] = tan
f['cos'] = cos
f['sin'] = sin
f['atan'] = atan
f['acos'] = acos
f['asin'] = asin
f['tanh'] = tanh
f['cosh'] = cosh
f['sinh'] = sinh
f['atanh'] = atanh
f['acosh'] = acosh
f['asinh'] = asinh
f['degrees'] = degrees
f['radians'] = radians
f['exp'] = exp
f['sqrt'] = sqrt
f['pow'] = pow
f['log'] = mylog
f['log10'] = mylog10
f['log2'] = mylog2
f['floor'] = myfloor
f['ceil'] = myceil
f['round'] = myround
f['trunc'] = mytrunc
f['remote'] = remote
f['now'] = mynow
f['year'] = myyear
f['day'] = myday
f['month'] = mymonth
f['hour'] = myhour
f['minute'] = myminute
f['second'] = mysecond
f['time'] = mytime
f['date'] = mydate
f['weekday'] = myweekday
f['yearday'] = myyearday
f['duration'] = myduration
f['randomf'] = randomFloat
f['random'] = randomDigit
f['abs'] = myabs
f['bool'] = mybool
f['int'] = myint
f['float'] = myfloat
f['highlight'] = myhighlight
add_dynamic_functions(f)
functionsTable = f
return functionsTable
class TableCache:
def __init__(self):
self.cachedTables = {}
self.change_count = -1
def _ViewName(self,view):
name = view.file_name()
if(not name):
name = "view_" + view.id()
return name
def _FindTable(self,row,view):
name = self._ViewName(view)
if(not name in self.cachedTables):
self.cachedTables[name] = []
cache = self.cachedTables[name]
if(self.change_count >= view.change_count()):
for t in cache:
if row >= t[0][0] and row <= t[0][1]:
return t[1]
else:
self.change_count = view.change_count()
self.cachedTables[name] = []
return None
def GetTable(self,view,at=None):
row = view.curRow()
if(at != None):
row,_ = view.rowcol(at)
td = self._FindTable(row,view)
if(not td):
td = create_table(view,at)
name = self._ViewName(view)
self.cachedTables[name].append(((td.start,td.end),td))
return td
tableCache = TableCache()
def TableConversion(indentDepth,data):
# figure out what our separator is.
# replace the separator with |
indent = ""
if(indentDepth > 0):
indent = (" " * indentDepth) + " "
try:
# Try AST and see if we can parse it that way.
# This if for things like: [[a,b,c],[1,2,3],[4,5,6]]
l = ast.literal_eval(data)
d = ""
if(isinstance(l,list)):
for r in l:
if (isinstance(r,list)):
d += indent + "|"
for c in r:
d += str(c) + "|"
else:
d += "|" + str(r) + "|"
d += "\n"
return (d, True)
except:
# It is okay if we fail.
pass
# Nope use the heuristic processing way.
lines = data.split('\n')
separator = ','
possibles = {",": [], ";": [], "\t": [], " ": []}
for l in lines:
if(l.strip() == ""):
continue
for k,v in possibles.items():
v.append(l.count(k))
vars = {}
for k,d in possibles.items():
s = sum(d)
mean = s / len(d)
if(mean > 0):
variance = math.sqrt(sum([ (x-mean)*(x-mean) for x in d ]) / len(d))
vars[k] = variance
#print(str(vars))
separator = min(vars, key=vars.get)
# We prefer comma if the variance is the same for the min and comma.
if(separator != ',' and ',' in vars and vars[','] == vars[separator]):
separator = ','
log.info("SEPARATOR CHOSEN: " + separator)
data = ""
for l in lines:
if(l.strip() == ""):
continue
data += indent + '|' + l.strip().replace(separator,'|') + '|\n'
return (data, True)
def insert_file_data(indentDepth, data, view, edit, onDone=None, replace=False):
data,_ = TableConversion(indentDepth, data)
if(replace):
view.run_command("org_internal_replace", {"start": view.sel()[0].begin(), "end": view.sel()[0].end(), "text": data, "onDone": onDone})
else:
view.run_command("org_internal_insert", {"location": view.sel()[0].begin(), "text": data, "onDone": onDone})
class OrgConvertSelectionToTableCommand(sublime_plugin.TextCommand):
def OnDone(self):
self.view.sel().clear()
self.view.sel().add(sublime.Region(self.pos.begin() +1, self.pos.begin()+1))
self.view.run_command('table_editor_next_field')
evt.EmitIf(self.onDone)
def run(self, edit, onDone=None):
self.edit = edit
self.onDone = onDone
self.pos = self.view.sel()[0]
curNode = db.Get().AtInView(self.view)
level = 1
if(None != curNode):
level = curNode.level
fileData = self.view.substr(self.view.sel()[0])
if(len(fileData) > 6):
insert_file_data(level,fileData,self.view, self.edit, evt.Make(self.OnDone), True)
table_phantoms = []
class OrgHideTableRowsCommand(sublime_plugin.TextCommand):
def OnDone(self):
evt.EmitIf(self.onDone)
def run(self, edit, onDone=None):
self.onDone = onDone
for f in table_phantoms:
self.view.erase_phantoms(f)
self.OnDone()
class OrgShowTableRowsCommand(sublime_plugin.TextCommand):
def OnDone(self):
evt.EmitIf(self.onDone)
def ToRomanNumeral(self,input):
if not 0 < input < 4000:
raise ValueError("Argument must be between 1 and 3999")
ints = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1)
nums = ('M', 'CM', 'D', 'CD','C', 'XC','L','XL','X','IX','V','IV','I')
result = []
for i in range(len(ints)):
count = int(input / ints[i])
result.append(nums[i] * count)
input -= ints[i] * count
return ''.join(result)
def RowToCellRow(self,r):
for i in range(1,len(self.td.lineToRow)+1):
if(self.td.lineToRow[i] == r):
return str(i)
count = 0;
for h in self.td.hlines:
if h == r:
return self.ToRomanNumeral(count+1)
++count
return "U"
def run(self, edit, onDone=None):
self.onDone = onDone
self.td = create_table(self.view)
if(self.td):
hline = self.td.start-1
if(self.td.hlines and len(self.td.hlines) > 0):
hline = self.td.hlines[0]
line = self.view.line(self.view.text_point(self.td.start,0))
indent = self.view.substr(line).find("|")
for r in range(self.td.start,self.td.end+1):
pt = self.view.text_point(r,indent)
region = sublime.Region(pt,pt)
idx = self.RowToCellRow(r)
body = """
<body id="table-index-popup">
<style>
div.heading {{
color: #880077;
padding: 0px;
font-weight: bold;
}}
</style>
<div class="heading">{0}</div>
</body>
""".format(idx)
key = "table_" + str(self.td.start) + "_row_" + str(r)
table_phantoms.append(key)
self.view.add_phantom("table_" + str(self.td.start) + "_row_" + str(r),region,body,sublime.LAYOUT_INLINE)
for c in range(1,self.td.Width()+1):
if(not idx.isnumeric()):
break
#print("II: " + str(idx) + "x" + str(c))
reg = self.td.FindCellRegion(int(idx),c)
if(not reg):
continue
row,col = self.view.rowcol(reg.begin())
pt1 = self.view.text_point(row,col)
pt2 = self.view.text_point(self.td.end,col)
region = sublime.Region(pt1,pt1)
body = """
<body id="table-index-popup">
<style>
div.heading {{
color: #880077;
padding: 0px;
font-weight: bold;
}}
</style>
<div class="heading">{0}</div>
</body>
""".format(c)
key = "table_" + str(self.td.start) + "_row_"+str(r)+"_col_" + str(c)
table_phantoms.append(key)
self.view.add_phantom(key,region,body,sublime.LAYOUT_INLINE)
#p = Phantom(region, content, sublime.LAYOUT_INLINE)
#phantoms.append(p)
self.OnDone()
class OrgPlotTableCommand(sublime_plugin.TextCommand):
def OnDone(self):
if(None != self.origCur):
self.view.sel().clear()
self.view.sel().add(self.origCur)
evt.EmitIf(self.onDone)
def run(self, edit, onDone=None):
self.onDone = onDone
if(self.view.sel()):
self.origCur = self.view.sel()[0]
row = self.view.curRow()
line = self.view.getLine(row)
if("#+PLOT:" in line):
pt = self.view.text_point(row,0)
while(not isTable(self.view,pt)):
row += 1
pt = self.view.text_point(row,0)
self.origCur = pt
self.view.sel().clear()
self.view.sel().add(self.origCur)
self.td = create_table(self.view)
orgplot.plot_table_command(self.td,self.view)
self.edit = edit
self.view.run_command("org_cycle_images",{"onDone": evt.Make(self.OnDone)})
# Grab the function table and dump a table of all the functions and their doc strings.
# Build a table of that information.
class OrgDocTableCommand(sublime_plugin.TextCommand):
def run(self, edit):
td = create_table(self.view)
out = ""
keys = list(td.functions.keys())
keys.sort()
for k in keys:
v = td.functions[k]
if(k == "ridx" or k == "cidx" or k == "symorcell" or k == "getcell" or k == "getcolcell" or k == "getrowcell"):
continue
if(not v.__doc__):
out += " - " + k + " :: " + "Not Yet Documented \n"
else:
out += " - " + k + " :: " + str(v.__doc__).replace("\n","\n ") + "\n"
out += "----------------------NAMES--------------------------------\n"
for k,v in td.names.items():
out += " - " + k + " :: " + str(v) + " \n"
self.view.insert(edit,self.view.line(self.view.size()).begin(),out)
class OrgImportTableFromCsvCommand(sublime_plugin.TextCommand):
def OnFile(self, filename=None):
self.inHan = None
if(None == filename):
return
if(os.path.exists(filename) and os.path.isfile(filename)):
fileData = ""
with open(filename,'r') as f:
fileData = f.read()
self.pos = self.view.sel()[0]
curNode = db.Get().AtInView(self.view)
level = 1
if(None != curNode):
level = curNode.level
insert_file_data(level,fileData,self.view, self.edit, evt.Make(self.OnDone))
def OnDone(self):
self.view.sel().clear()
self.view.sel().add(sublime.Region(self.pos.begin() +1, self.pos.end()+1))
self.view.run_command('table_editor_next_field')
evt.EmitIf(self.onDone)
def run(self, edit, onDone=None):
self.edit = edit
self.onDone = onDone
self.inHan = ins.OrgInput()
self.inHan.isFileBox = True
self.inHan.run("CSV", None, evt.Make(self.OnFile))
class OrgInsertBlankTableCommand(sublime_plugin.TextCommand):
def OnDims(self, text):
if(text == None):
return
dims = text.split('x')
if(len(dims) != 2):
log.error("DIMENSIONS ARE NOT RIGHT!")
return
w = int(dims[0])
h = int(dims[1])
curNode = db.Get().AtInView(self.view)
level = 1
if(None != curNode):
level = curNode.level
indent = (" " * level) + " "
data = ""
for y in range(0,h+1):
line = indent + "|"
for x in range(0,w):
line += "|"
data += line + '\n'
if(y == 0):
data += '|-\n'
self.pos = self.view.sel()[0]
self.view.run_command("org_internal_insert", {"location": self.view.sel()[0].begin(), "text": data, "onDone": self.onDone})
self.OnDone()
def OnDone(self):
self.view.sel().clear()
self.view.sel().add(sublime.Region(self.pos.begin() +1, self.pos.end()+1))
self.view.run_command('table_editor_next_field')
evt.EmitIf(self.onDone)
def run(self, edit, onDone=None):
self.edit = edit
self.onDone = onDone
self.input = ins.OrgInput()
self.input.run("WxH", None, evt.Make(self.OnDims))
RE_TABLE_HLINE = re.compile(r'\s*[|][-][+-]*[|]')
RE_FMT_LINE = re.compile(r'\s*[#][+](TBLFM|tblfm)[:]\s*(?P<expr>.*)')
RE_TARGET = re.compile(r'\s*(([@](?P<rowonly>[-]?[0-9><]+))|([$](?P<colonly>[-]?[0-9><]+))|([@](?P<row>[-]?[0-9><]+)[$](?P<col>[-]?[0-9><]+)))\s*$')
RE_NAMED_TARGET = re.compile(r'\s*[$](?P<name>[a-zA-Z][a-zA-Z0-9]+)')
def formula_rowcol(expr,table):
fields = expr.split('=')
if(len(fields) < 2):
return (None, None, None)
target = fields[0]
formula = "=".join(fields[1:]) if len(fields[1:]) > 1 else fields[1]
targets = target.split('..')
if(len(targets)==2):
r1 = formula_rowcol(targets[0] + "=",table)
r2 = formula_rowcol(targets[1] + "=",table)
return [r1[0] + r2[0],formula,None]
m = RE_TARGET.search(target)
if(m):
row = m.group('row')
col = m.group('col')
if not row and not col:
row = m.group('rowonly')
if(row):
if(isNumeric(row)):
row = int(row)
col = '*'
return [[row,col],formula,None]
else:
col = m.group('colonly')
if(isNumeric(col)):
col = int(col)
row = '*'
return [[row,col],formula,None]
else:
if(isNumeric(row)):
row = int(row)
if(isNumeric(col)):
col = int(col)
return [[row,col],formula,None]
else:
mn = RE_NAMED_TARGET.search(target)
if(mn):
cell = table.symbolOrCell(mn.group('name').strip())
if(isinstance(cell,Cell)):
return [[cell.r,cell.c],formula,cell.rowFilter]
return (None, None, None)
def isNumeric(v):
return v.lstrip('-').lstrip('+').isnumeric()
def isFunc(v):
return 'ridx()' in v or 'cidx()' in v
RE_TARGET_A = re.compile(r'\s*(([@](?P<row>(?P<rsign>[+-])?([0-9]+)|([>]+)|([<]+)|[#])[$](?P<col>((?P<csign>[+-])?([0-9]+)|([>]+)|([<]+)|[#])|(ridx\(\))|(cidx\(\))))|([@](?P<rowonly>((?P<rosign>[+-])?([0-9]+)|([>]+)|([<]+)|[#])|(ridx\(\))|(cidx\(\))))|([$](?P<colonly>((?P<cosign>[+-])?([0-9]+)|([>]+)|([<]+)|[#])|(ridx\(\))|(cidx\(\)))))(?P<end>[^@$]|$)')
RE_ROW_TOKEN = re.compile(r'[@][#]')
RE_COL_TOKEN = re.compile(r'[$][#]')
RE_SYMBOL_OR_CELL_NAME = re.compile(r'[$](?P<name>[a-zA-Z][a-zA-Z0-9_-]*)')
def replace_cell_references(expr):
#print("EXPS: " + str(expr))
while(True):
expr = RE_ROW_TOKEN.sub('ridx()',expr)
expr = RE_COL_TOKEN.sub('cidx()',expr)
m = RE_TARGET_A.search(expr)
if(m):
row = m.group('row')
col = m.group('col')
rs = m.group('rsign')
cs = m.group('csign')
end = m.group('end')
if(not end):
end = ""
if not row and not col:
row = m.group('rowonly')
if(row):
rs = m.group('rosign')
rs = '1' if rs else '0'
if(isNumeric(row) or isFunc(row)):
expr = RE_TARGET_A.sub(' getrowcell(' + str(row) + ',' + rs + ') ' + end,expr,1)
else:
expr = RE_TARGET_A.sub(' getrowcell(\'' + str(row) + '\''+","+rs+') ' + end,expr,1)
else:
col = m.group('colonly')
cs = m.group('cosign')
cs = '1' if cs else '0'
if(isNumeric(col) or isFunc(col)):
expr = RE_TARGET_A.sub(' getcolcell(' + str(col) + ',' + cs + ') ' + end,expr,1)
else:
expr = RE_TARGET_A.sub(' getcolcell(\'' + str(col) + '\'' +","+cs+ ') ' + end,expr,1)
else:
rowmarkers = '' if not isNumeric(row) or isFunc(row) else '\''
colmarkers = '' if not isNumeric(col) or isFunc(col) else '\''
cs = '1' if cs else '0'
rs = '1' if rs else '0'
expr = RE_TARGET_A.sub(' getcell(' + rowmarkers + str(row) + rowmarkers + "," + rs + "," + colmarkers + str(col) + colmarkers + "," + cs + ") " + end,expr,1)
else:
break
while(True):
m = RE_SYMBOL_OR_CELL_NAME.search(expr)
if(m):
name = m.group('name')
expr = RE_SYMBOL_OR_CELL_NAME.sub(' symorcell(\'' + name + '\') ',expr,1)
else:
break
#print("EXP: " + str(expr))
return expr
def formula_sources(expr):
ms = RE_TARGET.findall(expr)
matches = []
for m in ms:
row = m.group('row')
col = m.group('col')
if not row and not col:
row = m.group('rowonly')
if(row):
row = int(row)
col = '*'
matches.append([row,col])
else:
col = m.group('colonly')
col = int(col)
row = '*'
matches.append([row,col])
else:
row = int(row)
col = int(col)
matches.append([row,col])
return matches
# ============================================================
class Formula:
def __init__(self,expr, reg, formatters, table):
self.table = table
self.formatters = formatters
self.printfout = None
if(self.formatters):
m = RE_PRINTFSTYLE.search(self.formatters)
if(m):
self.printfout = m.group('formatter')
self.target, self.expr, self.rowFilter = formula_rowcol(expr,table)
# print("TARGET: " + str(self.target) + " -> " + str(expr))
# Never allow our expr to be empty. If we failed to parse it our EXPR is current cell value
if(self.expr == None):
self.expr = "$0"
if(self.target == None):
self.target = "@0$0"
self.expr = replace_cell_references(self.expr.replace("..","//"))
self.formula = expr
self.reg = reg
def EmptyIsZero(self):
return 'N' in self.formatters
def CellRowIterator(table,start,end, arit=None, brit=None):
c = table.CurCol()
if not arit:
arit = NullFilter()
if not brit:
brit = NullFilter()
if(start < table.StartRow()):
start = table.StartRow()
for r in range(start,end+1):
if(table.ShouldIgnoreRow(r) or arit.filter(r) or brit.filter(r)):
continue
cell = Cell(r,c,table)
yield cell
def CellColIterator(table,start,end):
r = table.CurRow()
for c in range(start,end+1):
cell = Cell(r,c,table)
yield cell
def CellBoxIterator(table,a,b):
sr = a.GetRow()
er = b.GetRow()
if(a.GetRow() > b.GetRow()):
sr = b.GetRow()
er = a.GetRow()
sc = a.GetCol()
ec = b.GetCol()
if(a.GetCol() > b.GetCol()):
sc = b.GetCol()
ec = a.GetCol()
if(sr < table.StartRow()):
sr = table.StartRow()
for r in range(sr,er+1):
if(table.ShouldIgnoreRow(r) or a.ShouldIgnoreRow(r) or b.ShouldIgnoreRow(r)):
continue
for c in range(sc,ec+1):
cell = Cell(r,c,table)
yield cell
def CellIterator(table,cell):
r = cell.r
c = cell.c
filter = cell.rowFilter
if(None == filter):
filter = NullFilter()
if(r == '*'):
rrange = range(table.StartRow(),table.Height()+1)
else:
rrange = range(cell.GetRow(),cell.GetRow()+1)
if(c == '*'):
crange = range(table.StartCol(),table.Width()+1)
else:
crange = range(cell.GetCol(),cell.GetCol()+1)
for r in rrange:
if(table.ShouldIgnoreRow(r) or filter.filter(r)):
continue
for c in crange:
cell = Cell(r,c,table)
yield cell
def RCIterator(table,r,c):
if(r == '*'):
rrange = range(table.StartRow(),table.Height()+1)
else:
rrange = range(r,r+1)
if(c == '*'):
crange = range(table.StartCol(),table.Width()+1)
else:
crange = range(c,c+1)
for r in rrange:
if(table.ShouldIgnoreRow(r)):
continue
for c in crange:
yield [r,c]
# ============================================================
# This represents a cell REFERENCE in the table.
# It has a reference to the table itself and looks
# up the actual data dynamically WHEN ASKED TO!
# That is important since the current target changes
# and many cell references are RELATIVE to the current
# target.
class Cell:
def __init__(self,r,c,table,rrelative=0,crelative=0,rowFilter=None):
self.r = r
self.c = c
self.table = table
self.rrelative = rrelative
self.crelative = crelative
self.rowFilter = rowFilter
def __str__(self):
return self.GetText()
def __eq__(self, other):
if isinstance(other, Cell):
if self.r == other.r and self.c == other.c:
return True
return self.GetText() == other.GetText()
return NotImplemented
def rc(self):
return (self.r,self.c)
def ShouldIgnoreRow(self, r):
if(self.rowFilter):
rv = self.rowFilter.filter(r)
return rv
return False
def GetRow(self):
r = None
if(isinstance(self.r,str)):
if(self.r == "*"):
r = self.table.CurRow()
elif(self.r.startswith('>')):
cnt = len(self.r.strip())
r = self.table.Height() - (cnt-1)
elif(self.r.startswith("<")):
cnt = len(self.r.strip())
r = self.table.StartRow() + (cnt-1)
else:
if(util.numberCheck(self.r)):
r = int(self.r)
elif(self.r < 0 or self.rrelative):
r = self.table.CurRow() + self.r
elif(self.r == 0):
return self.table.CurRow()
else:
r = self.r
if(None == r):
r = self.table.CurRow()
if(r < 1):
r = 1
if(r > self.table.Height()):
r = self.table.Height()
return r
def GetCol(self):
c = None
if(isinstance(self.c,str)):
if(self.c == "*"):
c = self.table.CurCol()
elif(self.c.startswith(">")):
cnt = len(self.c.strip())
c = self.table.Width() - (cnt-1)
elif(self.c.startswith("<")):
cnt = len(self.c.strip())
c = self.table.StartCol() + (cnt-1)
else:
if(util.numberCheck(self.c)):
c = int(self.c)
elif(self.c < 0 or self.crelative):
c = self.table.CurCol() + self.c
elif(self.c == 0):
return self.table.CurCol()
else:
c = self.c
if(None == c):
c = self.table.CurCol()
if(c < 1):
c = 1
if(c > self.table.Width()):
c = self.table.Width()
return c
def GetText(self):
return self.table.GetCellText(self.GetRow(), self.GetCol())
def GetInt(self):
return int(self.GetText())
def GetFloat(self):
return float(self.GetText())
def GetVal(self):
txt = self.GetText().strip()
if(util.numberCheck(txt)):
if('.' in txt):
return float(txt)
return int(txt)
if(txt.endswith("%")):
t = txt[:-1]
if(util.numberCheck(t)):
f = float(t)
f = (f / 100.0)
return f
l = txt.lower()
if(l == "true" or l == "t"):
return True
if(l == "false"):
return False
return txt
def GetNum(self):
txt = self.GetText().strip()
if(util.numberCheck(txt)):
if('.' in txt):
return float(txt)
return int(txt)
if(txt.endswith("%")):
t = txt[:-1]
if(util.numberCheck(t)):
f = float(t)
f = (f / 100.0)
return f
return 0
def GetVal(i):
if(isinstance(i,Cell)):
return i.GetVal()
return i
def GetNum(i):
if(isinstance(i,Cell)):
return i.GetNum()
return i
# ============================================================
# Functions
# ============================================================
def myabs(a):
"""Convert value to a positive value"""
return abs(GetVal(a))
def safe_mult(a, b): # pylint: disable=invalid-name
if hasattr(a, '__len__') and b * len(a) > MAX_STRING_LENGTH:
raise IterableTooLong('Sorry, I will not evalute something that long.')
if hasattr(b, '__len__') and a * len(b) > MAX_STRING_LENGTH:
raise IterableTooLong('Sorry, I will not evalute something that long.')
a = GetVal(a)
b = GetVal(b)
if(isinstance(a,float) or isinstance(b,float)):
if(isinstance(a,str) or isinstance(b,str)):
return 0
return a * b
def safe_pow(a, b): # pylint: disable=invalid-name
a = GetVal(a)
b = GetVal(b)
if abs(a) > MAX_POWER or abs(b) > MAX_POWER:
raise NumberTooHigh("Sorry! I don't want to evaluate {0} ** {1}"
.format(a, b))
return a ** b
def safe_add(a, b): # pylint: disable=invalid-name
if hasattr(a, '__len__') and hasattr(b, '__len__'):
if len(a) + len(b) > MAX_STRING_LENGTH:
raise IterableTooLong("Sorry, adding those two together would"
" make something too long.")
a = GetVal(a)
b = GetVal(b)
return a + b
def tsub(a, b): # pylint: disable=invalid-name
return GetVal(a) - GetVal(b)
def tdiv(a, b): # pylint: disable=invalid-name
return GetNum(a) / GetNum(b)
def tmod(a, b): # pylint: disable=invalid-name
return GetVal(a) % GetVal(b)
def teq(a,b):
return GetVal(a) == GetVal(b)
def tneq(a,b):
return GetVal(a) != GetVal(b)
def tgt(a,b):
return GetVal(a) > GetVal(b)
def tlt(a,b):
return GetVal(a) < GetVal(b)
def tge(a,b):
return GetVal(a) >= GetVal(b)
def tle(a,b):
return GetVal(a) <= GetVal(b)
def tnot(a):
return not GetVal(a)
def tusub(a):
return - GetVal(a)
def tuadd(a):
return + GetVal(a)
def vmean(rng):
"""Computes the average value of a column or row. Takes a range of cells"""
n = 0
s = 0
for i in rng:
num = GetNum(i)
s += num
n += 1
if(n != 0):
return float(s) / float(n)
return 0
def vsum(rng):
"""Computes the sum of a range of cells"""
s = 0
for i in rng:
s += GetNum(i)
return s
def vmedian(rng):
"""Computes the median (middle) value of a sorted range of cells"""
data = list(rng)
for i in range(0,len(data)):
data[i] = GetVal(data[i])
data.sort()
dl = len(data)
v = math.floor(dl/2)
if(dl == 1):
return data[0]
if(v*2 != dl):
return data[v]
else:
if(v <= 0):
return data[0]