-
Notifications
You must be signed in to change notification settings - Fork 15
/
orgcheckbox.py
495 lines (447 loc) · 17 KB
/
orgcheckbox.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
import sublime
import sublime_plugin
import re
import logging
import OrgExtended.orgdb as db
import OrgExtended.asettings as sets
log = logging.getLogger(__name__)
# Stolen from the original orgmode
class CheckState:
Unchecked, Checked, Indeterminate, Error = range(1, 5)
indent_regex = re.compile(r'^(\s*).*$')
summary_regex = re.compile(r'(\[\d*[/%]\d*\])')
checkbox_regex = re.compile(r'(\[[xX\- ]\])')
checkbox_line_regex = re.compile(r'\s*[-+]?\s*(\[[xX\- ]\])\s+')
unordered_line_regex = re.compile(r'\s*[-+]\s+')
# Extract the indent of this checkbox.
# RETURNS: a string with the indent of this line.
def get_indent(view, content):
if isinstance(content, sublime.Region):
content = view.substr(content)
match = indent_regex.match(content)
if (match):
return match.group(1)
else:
log.debug("Could not match indent: " + content)
return ""
RE_HEADING = re.compile('^[*]+ ')
def check_type(line):
if checkbox_regex.search(line):
return "C"
if unordered_line_regex.search(line):
return "L"
ls = line.strip()
if len(ls) > 0 and ls[0] == "*":
return "H"
# Try to find the parent of a region (by indent)
def find_parent(view, region):
row, col = view.rowcol(region.begin())
content = view.substr(view.line(region))
indent = len(get_indent(view, content))
row -= 1
found = False
# Look upward
while row >= 0:
point = view.text_point(row, 0)
content = view.substr(view.line(point))
if len(content.strip()):
if (RE_HEADING.search(content)):
break
cur_indent = len(get_indent(view, content))
if cur_indent < indent:
found = True
break
row -= 1
if found:
# return the parent we found.
return view.line(view.text_point(row,0))
def find_heading(view, region):
row, col = view.rowcol(region.begin())
row -= 1
found = False
while row >= 0:
point = view.text_point(row, 0)
content = view.substr(view.line(point))
if len(content.strip()):
if RE_HEADING.search(content) and get_summary(view, view.line(point)):
found = True
break
row -= 1
if found:
# return the heading we found.
return view.line(view.text_point(row, 0))
def find_children(view, region, cre = checkbox_regex, includeSiblings=False, recursiveChildFind=False):
row, col = view.rowcol(region.begin())
line = view.line(region)
content = view.substr(line)
# print content
indent = get_indent(view, content)
if(not indent):
log.debug("Unable to locate indent for line: " + str(row))
indent = len(indent)
# print repr(indent)
row += 1
child_indent = None
children = []
last_row, _ = view.rowcol(view.size())
check = None
while row <= last_row:
point = view.text_point(row, 0)
line = view.line(point)
content = view.substr(line)
summary = get_summary(view, line)
lc = content.lstrip()
if lc.startswith("*") or lc.startswith('#'):
break
if cre.search(content):
if check is None:
check = check_type(content)
cur_indent = len(get_indent(view, content))
# check for end of descendants
if includeSiblings and cur_indent < indent:
break
elif not includeSiblings and cur_indent <= indent:
break
# only immediate children (and siblings)
if(not recursiveChildFind):
if child_indent is None:
child_indent = cur_indent
if cur_indent == child_indent:
children.append(line)
if(includeSiblings and cur_indent < child_indent):
children.append(line)
else:
children.append(line)
else:
if check is not None:
lineType = check_type(content)
if check != "H" and lineType != check:
break
row += 1
return children
def find_siblings(view, child, parent):
row, col = view.rowcol(parent.begin())
parent_indent = get_indent(view, parent)
child_indent = get_indent(view, child)
siblings = []
row += 1
last_row, _ = view.rowcol(view.size())
while row <= last_row: # Don't go past end of document.
line = view.text_point(row, 0)
line = view.line(line)
content = view.substr(line)
# print content
if len(content.strip()):
cur_indent = get_indent(view, content)
if len(cur_indent) <= len(parent_indent):
break # Indent same as parent found!
if len(cur_indent) == len(child_indent):
siblings.append((line, content))
row += 1
return siblings
def get_summary(view, line):
row, _ = view.rowcol(line.begin())
content = view.substr(line)
match = summary_regex.search(content)
if not match:
return None
col_start, col_stop = match.span()
return sublime.Region(
view.text_point(row, col_start),
view.text_point(row, col_stop),
)
def get_checkbox(view, line):
row, _ = view.rowcol(line.begin())
content = view.substr(line)
# print content
match = checkbox_regex.search(content)
if not match:
return None
# checkbox = match.group(1)
# print repr(checkbox)
# print dir(match), match.start(), match.span()
col_start, col_stop = match.span()
return sublime.Region(
view.text_point(row, col_start),
view.text_point(row, col_stop),
)
def get_check_state(view, line):
if '[-]' in view.substr(line):
return CheckState.Indeterminate
if '[ ]' in view.substr(line):
return CheckState.Unchecked
if '[X]' in view.substr(line) or '[x]' in view.substr(line):
return CheckState.Checked
return CheckState.Error
def get_check_char(view, check_state):
if check_state == CheckState.Unchecked:
return ' '
elif check_state == CheckState.Checked:
return 'x'
elif check_state == CheckState.Indeterminate:
return '-'
else:
return 'E'
def recalc_summary(view, region):
recursive = sets.Get("checkboxSummaryRecursive",False)
at = db.Get().AtInView(view)
if(at):
props = at.properties
if(props and 'COOKIE_DATA' in props):
cook = props['COOKIE_DATA']
if(cook and 'notrecursive' in cook):
recursive = False
elif(cook and 'recursive' in cook):
recursive = True
children = None
children = find_children(view, region, checkbox_regex, False, recursive)
if not len(children) > 0:
return (0, 0)
num_children = len(children)
checked_children = len(
[child for child in children if (get_check_state(view,child) == CheckState.Checked)])
# print ('checked_children: ' + str(checked_children) + ', num_children: ' + str(num_children))
return (num_children, checked_children)
def update_line(view, edit, region, parent_update=True, children_update=False):
#print ('update_line', self.view.rowcol(region.begin())[0]+1)
(num_children, checked_children) = recalc_summary(view, region)
# No children we don't have to update anything else.
if num_children <= 0:
return False
# update region checkbox
if checked_children == num_children:
newstate = CheckState.Checked
else:
if checked_children != 0:
newstate = CheckState.Indeterminate
else:
newstate = CheckState.Unchecked
toggle_checkbox(view, edit, region, newstate)
# update region summary
update_summary(view, edit, region, checked_children, num_children)
if children_update:
children = find_children(view, region)
for child in children:
line = view.line(child)
summary = get_summary(view, view.line(child))
if summary:
return update_line(view, edit, line, parent_update=False, children_update=True)
if parent_update:
parent = find_parent(view, region)
if parent:
update_line(view, edit, parent)
else:
# ok, no parent, but may be there is heading with summary?
heading = find_heading(view, region)
if heading and get_summary(view, heading):
update_line(view, edit, heading, parent_update=False)
return True
def update_summary(view, edit, region, checked_children, num_children):
# print('update_summary', self.view.rowcol(region.begin())[0]+1)
summary = get_summary(view, region)
if not summary:
return False
# print('checked_children: ' + str(checked_children) + ', num_children: ' + str(num_children))
line = view.substr(summary)
if("%" in line):
view.replace(edit, summary, '[{0}%]'.format(int(checked_children/num_children*100)))
else:
view.replace(edit, summary, '[%d/%d]' % (checked_children, num_children))
def toggle_checkbox(view, edit, region, checked=None, recurse_up=False, recurse_down=False):
# print 'toggle_checkbox', self.view.rowcol(region.begin())[0]+1
checkbox = get_checkbox(view, region)
if not checkbox:
return False
if checked is None:
check_state = get_check_state(view, region)
if (check_state == CheckState.Unchecked) | (check_state == CheckState.Indeterminate):
check_state = CheckState.Checked
elif (check_state == CheckState.Checked):
check_state = CheckState.Unchecked
else:
check_state = checked
view.replace(edit, checkbox, '[%s]' % ( get_check_char(view, check_state)))
if recurse_down:
# all children should follow
children = find_children(view, region)
for child in children:
toggle_checkbox(view, edit, child, check_state, recurse_down=True)
if (get_summary(view, child)):
update_line(view, edit, child, parent_update=False)
if get_summary(view, region):
(num_children, checked_children) = recalc_summary(view, region)
update_summary(view, edit, region, checked_children, num_children)
if recurse_up:
# update parent
parent = find_parent(view, region)
if parent:
update_line(view, edit, parent)
else:
# ok, no parent, but may be there is heading with summary?
heading = find_heading(view, region)
if heading and get_summary(view, heading):
update_line(view, edit, heading, parent_update=False)
def is_checkbox(view, sel):
names = view.scope_name(sel.end())
return 'orgmode.checkbox' in names or 'orgmode.checkbox.checked' in names or 'orgmode.checkbox.blocked' in names
def is_checkbox_line(view,sel=None):
point = None
if(sel == None):
row = view.curRow()
point = view.text_point(row, 0)
else:
point = sel.end()
line = view.line(point)
content = view.substr(line)
return checkbox_line_regex.search(content)
def find_all_summaries(view):
return view.find_by_selector("orgmode.checkbox.summary")
def recalculate_checkbox_summary(view, sel, edit):
line = view.line(sel.begin())
update_line(view, edit, line)
def recalculate_all_checkbox_summaries(view, edit):
sums = find_all_summaries(view)
for sel in sums:
recalculate_checkbox_summary(view, sel, edit)
cline_info_regex = re.compile(r'^(\s*)([-+0-9](\.)?)?.*$')
class OrgInsertCheckboxCommand(sublime_plugin.TextCommand):
def run(self, edit,insertHere=True):
row = self.view.curRow()
line = self.view.getLine(row)
match = cline_info_regex.match(line)
indent = match.group(1)
start = match.group(2)
if(start):
indent = indent + start + " [ ] "
reg = self.view.curLine()
list_regex = re.compile(r'\s*(([-+]\s\[)|[^#*|+-])')
children = find_children(self.view, reg, list_regex, not insertHere)
if(children and len(children) > 0):
reg = children[len(children) - 1]
row,_ =self.view.rowcol(reg.begin())
self.view.insert(edit,reg.end(),"\n" + indent)
# Move to end of line
row = row + 1
pt = self.view.text_point(row,0)
ln = self.view.line(pt)
self.view.sel().clear()
self.view.sel().add(ln.end())
uline_info_regex = re.compile(r'^(\s*)([-+]) .*$')
def isUnorderedList(line):
return uline_info_regex.match(line)
RE_THING = re.compile(r'^\s*[+-](\s\[[ xX-]\])?\s(?P<data>.*)$')
RE_NOTHEADERS = re.compile(r'^\s*[\#|0-9]')
def getListAtPointForSorting(view):
parent = view.findParentByIndent(view.curLine(),RE_NOTHEADERS, RE_THING)
if(None != parent):
prow, _ = view.rowcol(parent.begin())
list_regex = re.compile(r'\s*(([-+]\s\[)|[^#*|+-])')
children = find_children(view, parent, list_regex, True)
sortby = view.getLine(prow)
m = RE_THING.search(sortby)
if(m):
sortby = m.group('data')
things = [[[prow,0],sortby]]
for c in children:
srow, _ = view.rowcol(c.begin())
if(len(things) > 0):
things[len(things)-1][0][1] = srow
sortby = view.getLine(srow)
m = RE_THING.search(sortby)
if(m):
sortby = m.group('data')
things.append([[srow,0],sortby])
if(len(things) > 0):
srow, _ = view.rowcol(children[len(children)-1].end())
things[len(things)-1][0][1] = srow+1
return things
return None
def getListAtPoint(view,pt=None):
if(pt):
line = view.line(pt)
else:
line = view.curLine()
parent = view.findParentByIndent(line,RE_NOTHEADERS, RE_THING)
if(None != parent):
prow, _ = view.rowcol(parent.begin())
list_regex = re.compile(r'\s*(([-+]\s\[)|[^#*|+-])')
children = find_children(view, parent, list_regex, True)
sortby = view.getLine(prow)
m = RE_THING.search(sortby)
if(m):
sortby = m.group('data')
things = []
lastAppend = False
for c in children:
srow, _ = view.rowcol(c.begin())
if(lastAppend and len(things) > 0):
things[len(things)-1][0][1] = srow
lastAppend = False
sortby = view.getLine(srow)
m = RE_THING.search(sortby)
if(m):
sortby = m.group('data')
things.append([[srow,0],sortby])
lastAppend = True
if(len(things) > 0):
srow, _ = view.rowcol(children[len(children)-1].end())
things[len(things)-1][0][1] = srow+1
return things
return None
class OrgInsertUnorderedListCommand(sublime_plugin.TextCommand):
def run(self, edit,insertHere=True):
row = self.view.curRow()
line = self.view.getLine(row)
match = uline_info_regex.match(line)
indent = match.group(1)
start = match.group(2)
if(start):
indent = indent + start + " "
reg = self.view.curLine()
list_regex = re.compile(r'\s*([-+]|[^#*|])')
children = find_children(self.view, reg, list_regex, not insertHere)
if(children and len(children) > 0):
reg = children[len(children) - 1]
row,_ =self.view.rowcol(reg.begin())
self.view.insert(edit,reg.end(),"\n" + indent)
# Move to end of line
row = row + 1
pt = self.view.text_point(row,0)
ln = self.view.line(pt)
self.view.sel().clear()
self.view.sel().add(ln.end())
cbsline_info_regex = re.compile(r'^(\s*)(.*)\[\s*[0-9]*/[0-9]\s*\]\s*$')
class OrgInsertCheckboxSummaryCommand(sublime_plugin.TextCommand):
def run(self, edit):
row = self.view.curRow()
line = self.view.getLine(row)
match = cbsline_info_regex.match(line)
if(not match):
reg = self.view.curLine()
self.view.insert(edit,reg.end()," [/] ")
recalculate_all_checkbox_summaries(self.view, edit)
class OrgToggleCheckboxCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
for sel in view.sel():
if(not is_checkbox_line(view, sel)):
continue
line = view.line(sel.end())
toggle_checkbox(view, edit, line, recurse_up=True, recurse_down=True)
class OrgRecalcCheckboxSummaryCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
backup = []
for sel in view.sel():
if 'orgmode.checkbox.summary' not in view.scope_name(sel.end()):
continue
backup.append(sel)
#summary = view.extract_scope(sel.end())
line = view.line(sel.end())
update_line(view, edit, line)
view.sel().clear()
for region in backup:
view.sel().add(region)
class OrgRecalcAllCheckboxSummariesCommand(sublime_plugin.TextCommand):
def run(self, edit):
recalculate_all_checkbox_summaries(self.view, edit)