-
Notifications
You must be signed in to change notification settings - Fork 58
/
sublime_zk.py
executable file
·2521 lines (2227 loc) · 91 KB
/
sublime_zk.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
"""
___. .__ .__ __
________ _\_ |__ | | |__| _____ ____ _______| | __
/ ___/ | \ __ \| | | |/ \_/ __ \ \___ / |/ /
\___ \| | / \_\ \ |_| | Y Y \ ___/ / /| <
/____ >____/|___ /____/__|__|_| /\___ > /_____ \__|_ \
\/ \/ \/ \/ \/ \/
The SublimeText Zettelkasten
"""
import sublime
import sublime_plugin
import os
import re
import subprocess
import glob
import datetime
from collections import defaultdict, deque
import threading
import io
from subprocess import Popen, PIPE
import struct
import imghdr
import unicodedata
from collections import Counter
from operator import itemgetter
import base64
import urllib.request
class ZkConstants:
"""
Some constants used over and over
"""
Settings_File = 'sublime_zk.sublime-settings'
Syntax_File = 'Packages/sublime_zk/sublime_zk.sublime-syntax'
Link_Prefix = '['
Link_Prefix_Len = len(Link_Prefix)
Link_Postfix = ']'
# characters at which a #tag is cut off (#tag, -> #tag)
Tag_Stops = '.,\/!$%\^&\*;\{\}[]\'"=`~()<>\\'
TAG_PREFIX = '#'
# search for tags in files
def RE_TAGS():
prefix = re.escape(ZkConstants.TAG_PREFIX)
return r"(?<=\s|^)(?<!`)(" + prefix + r"+([^" + prefix + r"\s.,\/!$%\^&\*;{}\[\]'\"=`~()<>”\\]|:[a-zA-Z0-9])+)"
# Same RE just for ST python's re module
# un-require line-start, sublimetext python's RE doesn't like it
def RE_TAGS_PY():
prefix = re.escape(ZkConstants.TAG_PREFIX)
return r"(?<=\s)(?<!`)(" + prefix + r"+([^" + prefix + r"\s.,\/!$%\^&\*;{}\[\]'\"=`~()<>”\\]|:[a-zA-Z0-9])+)"
# match note links in text
Link_Matcher = re.compile('(\[+|§)([0-9.]{12,18})(\]+|.?)')
# Above RE doesn't really care about closing ] andymore
# This works in our favour so we support [[201711122259 This is a note]]
# when expanding overview notes
# image links with attributes
RE_IMG_LINKS = '(!\[)(.*)(\])(\()(.*)(\))(\{)(.*)(\})'
# TOC markers
TOC_HDR = '<!-- table of contents (auto) -->'
TOC_END = '<!-- (end of auto-toc) -->'
class ZKMode:
ZKM_Results_Syntax_File = 'Packages/sublime_zk/zk-mode/sublime_zk_results.sublime-syntax'
ZKM_SavedSearches_Syntax_File = 'Packages/sublime_zk/zk-mode/sublime_zk_search.sublime-syntax'
ZKM_SavedSearches_File = '.saved_searches.zks'
@staticmethod
def saved_searches_file(folder):
""" Return the name of the external search results file. """
return os.path.join(folder, ZKMode.ZKM_SavedSearches_File)
@staticmethod
def do_layout(window):
window.run_command('set_layout', {
'cols': [0.0, 0.7, 1.0],
'rows': [0.0, 0.8, 1.0],
'cells': [[0, 0, 1, 2], [1, 0, 2, 1], [1, 1, 2, 2]]
})
@staticmethod
def enter(window):
global PANE_FOR_OPENING_RESULTS
global PANE_FOR_OPENING_NOTES
PANE_FOR_OPENING_RESULTS = 1
PANE_FOR_OPENING_NOTES = 0
# check if we have a folder
if window.project_file_name():
folder = os.path.dirname(window.project_file_name())
else:
# no project. try to create one
window.run_command('save_project_as')
# if after that we still have no project (user canceled save as)
folder = os.path.dirname(window.project_file_name())
if not folder:
# I don't know how to save_as the file so there's nothing sane I
# can do here. Non-obtrusively warn the user that this failed
window.status_message(
'Zettelkasten mode cannot be entered without a project or an open folder!')
return False
ZKMode.do_layout(window)
results_file = ExternalSearch.external_file(folder)
lines = """# Welcome to Zettelkasten Mode!
#! ... Show all Tags
[! ... Show all notes
#? ... Browse & insert tag
[[ ... Browse notes & insert link
shift + enter ... Create new note
ctrl + enter ... Follow link under cursor and open note
ctrl + enter ... Follow #tag or citekey under cursor and
show referencing notes
alt + enter ... Show notes referencing link under cursor
ctrl + . ... Create list of referencing notes in the
current note
(link, #tag, or citekey under cursor)
""".split('\n')
if not os.path.exists(results_file):
# create it
with open(results_file, mode='w', encoding='utf-8') as f:
f.write('\n'.join(lines))
# now open and show the file
ExternalSearch.show_search_results(window, folder, 'Welcome', lines,
'show_all_tags_in_new_pane')
# now open saved searches
searches_file = ZKMode.saved_searches_file(folder)
if not os.path.exists(searches_file):
with open(searches_file, mode='w', encoding='utf-8') as f:
f.write("""# Saved Searches
All Notes: [!
All Tags: #!
## tag1 or tag2
Tag1orTag2: #tag1 #tag2
## tag1 and not tag2
Complex: #tag1, !#tag2
""")
new_view = window.open_file(searches_file)
window.set_view_index(new_view, 2, 0)
new_view.set_syntax_file(ZKMode.ZKM_SavedSearches_Syntax_File)
window.focus_group(PANE_FOR_OPENING_NOTES)
window.set_sidebar_visible(False)
# global magic
F_EXT_SEARCH = False
PANE_FOR_OPENING_NOTES = 0
PANE_FOR_OPENING_RESULTS = 1
DISTRACTION_FREE_MODE_ACTIVE = defaultdict(bool)
VIEWS_WITH_IMAGES = set()
AUTO_SHOW_IMAGES = False
SECONDS_IN_ID = False
def get_settings():
return sublime.load_settings(ZkConstants.Settings_File)
def settings_changed():
global PANE_FOR_OPENING_RESULTS
global PANE_FOR_OPENING_NOTES
global AUTO_SHOW_IMAGES
global SECONDS_IN_ID
settings = get_settings()
value = settings.get("pane_for_opening_notes", None)
if value is not None:
PANE_FOR_OPENING_NOTES = value
value = settings.get("pane_for_opening_results", None)
if value is not None:
PANE_FOR_OPENING_RESULTS = value
AUTO_SHOW_IMAGES = settings.get('auto_show_images', False)
value = settings.get("seconds_in_id", None)
if value is not None:
SECONDS_IN_ID = value
value = settings.get("tag_prefix", None)
if value is not None:
ZkConstants.TAG_PREFIX = value
def plugin_loaded():
global F_EXT_SEARCH
F_EXT_SEARCH = os.system(ExternalSearch.SEARCH_COMMAND + ' --help') == 0
if F_EXT_SEARCH:
print('Sublime_ZK: Using ag!')
else:
settings = get_settings()
ag = settings.get('path_to_ag', '/usr/local/bin/ag')
if ag:
if os.system(ag + ' --help') == 0:
ExternalSearch.SEARCH_COMMAND = ag
F_EXT_SEARCH = True
print('Sublime_ZK: Using ', ag)
else:
print('Sublime_ZK: Not using ag!')
else:
print('Sublime_ZK: Not using ag!')
settings = get_settings()
settings.clear_on_change("sublime_zk_notify")
settings.add_on_change("sublime_zk_notify", settings_changed)
settings_changed()
class TagSearch:
"""
Advanced tag search.
Grammar:
```
search-spec: search-term [, search-term]*
search-term: tag-spec [ tag-spec]*
tag-spec: [!]#tag-name[*]
tag-name: {any valid tag string}
```
"""
@staticmethod
def advanced_tag_search(search_spec, folder, extension):
"""
Return ids of all notes matching the search_spec.
"""
if search_spec.startswith('[!'):
sublime.active_window().run_command('zk_show_all_notes')
return
elif search_spec.startswith('#!'):
sublime.active_window().run_command('zk_show_all_tags')
return
note_tag_map = find_all_notes_all_tags_in(folder, extension)
print('Note Tag Map for ', folder, extension)
for k, v in note_tag_map.items():
print('{} : {}'.format(k, v))
for sterm in [s.strip() for s in search_spec.split(',')]:
# iterate through all notes and apply the search-term
sterm_results = {}
for note_id, tags in note_tag_map.items():
if not note_id:
continue
# apply each tag-spec match to all tags
for tspec in sterm.split():
if tspec[0] == '!':
if tspec[-1] == '*':
match = TagSearch.match_not_startswith(tspec, tags)
else:
match = TagSearch.match_not(tspec, tags)
else:
if tspec[-1] == '*':
match = TagSearch.match_startswith(tspec, tags)
else:
match = TagSearch.match_tag(tspec, tags)
if match:
sterm_results[note_id] = tags # remember this note
# use the results for the next search-term
note_tag_map = sterm_results
result = list(sterm_results.keys())
result.sort()
return result
@staticmethod
def match_not(tspec, tags):
return tspec[1:] not in tags
@staticmethod
def match_tag(tspec, tags):
return tspec in tags
@staticmethod
def match_not_startswith(tspec, tags):
tspec = tspec[1:-1]
return len([t for t in tags if t.startswith(tspec)]) == 0
@staticmethod
def match_startswith(tspec, tags):
tspec = tspec[:-1]
return [t for t in tags if t.startswith(tspec)]
class ImageHandler:
"""
Static class to bundle image handling.
"""
Phantoms = defaultdict(set)
@staticmethod
def show_images(view, edit, max_width=1024):
"""
markup.underline.link.image.markdown
"""
global DISTRACTION_FREE_MODE_ACTIVE
global VIEWS_WITH_IMAGES
folder = get_path_for(view)
if not folder:
return
skip = 0
while True:
img_regs = view.find_by_selector(
'markup.underline.link.image.markdown')[skip:]
skip += 1
if not img_regs:
break
region = img_regs[0]
rel_p = view.substr(region)
if rel_p.startswith('http'):
img = rel_p
local_filename, headers = urllib.request.urlretrieve(rel_p)
size = ImageHandler.get_image_size(local_filename)
if size:
w, h, ttype = size
FMT = u'''
<img src="data:image/{}" class="centerImage" {}>
'''
img = ttype + ";base64," + get_as_base64(img)
else:
FMT = '''
<img src="file://{}" class="centerImage" {}>
'''
img = os.path.join(folder, rel_p)
size = ImageHandler.get_image_size(img)
if not size:
continue
w, h, t = size
line_region = view.line(region)
imgattr = ImageHandler.check_imgattr(view, line_region, region)
if not imgattr:
if w > max_width:
m = max_width / w
h *= m
w = max_width
imgattr = 'width="{}" height="{}"'.format(w, h)
settings = sublime.load_settings(
'Distraction Free.sublime-settings')
spaces = settings.get('wrap_width', 80)
centered = settings.get('draw_centered', True)
view.erase_phantoms(str(region))
html_img = FMT.format(img, imgattr)
if centered and DISTRACTION_FREE_MODE_ACTIVE[view.window().id()]:
line_str = view.substr(line_region)
line_len = len(line_str)
spaces -= line_len + 1
view.insert(edit, region.b, ' ' * spaces)
view.add_phantom(
str(region),
sublime.Region(line_region.b + spaces,
line_region.b + spaces),
html_img,
sublime.LAYOUT_BELOW)
else:
view.add_phantom(str(region), region,
html_img,
sublime.LAYOUT_BLOCK)
ImageHandler.Phantoms[view.id()].add(str(region))
VIEWS_WITH_IMAGES.add(view.id())
@staticmethod
def check_imgattr(view, line_region, link_region=None):
# find attrs for this link
full_line = view.substr(line_region)
link_till_eol = full_line[link_region.a - line_region.a:]
# find attr if present
m = re.match(r'.*\)\{(.*)\}', link_till_eol)
if m:
return m.groups()[0]
@staticmethod
def hide_images(view, edit):
"""
Hide all imgs; use buffered identifiers
"""
print("here")
for rel_p in ImageHandler.Phantoms[view.id()]:
print(rel_p)
view.erase_phantoms(rel_p)
del ImageHandler.Phantoms[view.id()]
skip = 0
while True:
img_regs = view.find_by_selector(
'markup.underline.link.image.markdown')[skip:]
skip += 1
if not img_regs:
break
region = img_regs[0]
rel_p = view.substr(region)
line_region = view.line(region)
line_str = view.substr(line_region)
view.replace(edit, line_region, line_str.strip())
VIEWS_WITH_IMAGES.discard(view.id())
@staticmethod
def get_image_size(img):
"""
Determine the image type of img and return its size.
"""
with open(img, 'rb') as f:
head = f.read(24)
ttype = None
# print('head:\n', repr(head))
if len(head) != 24:
return
if imghdr.what(img) == 'png':
ttype = "png"
check = struct.unpack('>i', head[4:8])[0]
if check != 0x0d0a1a0a:
return
width, height = struct.unpack('>ii', head[16:24])
elif imghdr.what(img) == 'gif':
ttype = "gif"
width, height = struct.unpack('<HH', head[6:10])
elif imghdr.what(img) == 'jpeg':
ttype = "jpeg"
try:
f.seek(0) # Read 0xff next
size = 2
ftype = 0
while not 0xc0 <= ftype <= 0xcf:
f.seek(size, 1)
byte = f.read(1)
while ord(byte) == 0xff:
byte = f.read(1)
ftype = ord(byte)
size = struct.unpack('>H', f.read(2))[0] - 2
# SOFn block
f.seek(1, 1) # skip precision byte.
height, width = struct.unpack('>HH', f.read(4))
except Exception:
return
else:
return
return width, height, ttype
class Autobib:
"""
Static class to group all auto-bibliography functions.
"""
citekey_matcher = re.compile('^@.*{([^,]*)[,]?')
author_matcher = re.compile(r'^\s*author\s*=\s*(.*)', re.IGNORECASE)
title_matcher = re.compile(r'^\s*title\s*=\s*(.*)', re.IGNORECASE)
year_matcher = re.compile(r'^\s*year\s*=\s*(.*)', re.IGNORECASE)
@staticmethod
def look_for_bibfile(view, settings):
"""
Look for a bib file in the view's folder.
If no bib file there, then query the setting.
"""
folder = get_path_for(view)
if folder:
pattern = os.path.join(folder, '*.bib')
bibs = glob.glob(pattern)
if bibs:
print('Using local', bibs[0])
return bibs[0]
# try the setting
bibfile = settings.get('bibfile', None)
if bibfile:
if os.path.exists(bibfile):
print('Using global', bibfile)
return bibfile
else:
print('bibfile not found:', bibfile)
return None
@staticmethod
def extract_all_citekeys(bibfile):
"""
Parse the bibfile and return all citekeys.
"""
citekeys = set()
if not os.path.exists(bibfile):
print('bibfile not found:', bibfile)
return []
with open(bibfile, mode='r', encoding='utf-8') as f:
for line in f:
match = Autobib.citekey_matcher.findall(line)
if not match:
continue
citekeys.add(match[0])
return citekeys
@staticmethod
def extract_all_entries(bibfile):
"""
Return dict: {citekey: {title, authors, year}}
"""
entries = defaultdict(lambda: defaultdict(str))
if not os.path.exists(bibfile):
print('bibfile not found:', bibfile)
return {}
current_citekey = None
with open(bibfile, mode='r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if line.endswith(','):
line = line[:-1]
match = Autobib.citekey_matcher.findall(line)
if match:
current_citekey = match[0]
continue
match = Autobib.author_matcher.findall(line)
if match:
authors = match[0]
authors = Autobib.parse_authors(authors)
entries[current_citekey]['authors'] = authors
continue
match = Autobib.title_matcher.findall(line)
if match:
title = match[0]
title = Autobib.remove_latex_commands(title)
entries[current_citekey]['title'] = title
continue
match = Autobib.year_matcher.findall(line)
if match:
year = match[0]
year = Autobib.remove_latex_commands(year)
entries[current_citekey]['year'] = year
continue
return entries
@staticmethod
def parse_authors(line):
line = Autobib.remove_latex_commands(line)
authors = line.split(' and')
author_tuples = []
for author in authors:
first = ''
last = author.strip()
if ',' in author:
last, first = [x.strip() for x in author.split(',')][:2]
author_tuples.append((last, first))
if len(author_tuples) > 2:
authors = '{} et al.'.format(author_tuples[0][0]) # last et al
else:
authors = ' & '.join(x[0] for x in author_tuples)
return authors
@staticmethod
def remove_latex_commands(s):
"""
Simple function to remove any LaTeX commands or brackets from the string,
replacing it with its contents.
"""
chars = []
FOUND_SLASH = False
for c in s:
if c == '{':
# i.e., we are entering the contents of the command
if FOUND_SLASH:
FOUND_SLASH = False
elif c == '}':
pass
elif c == '\\':
FOUND_SLASH = True
elif not FOUND_SLASH:
chars.append(c)
elif c.isspace():
FOUND_SLASH = False
return ''.join(chars)
@staticmethod
def find_citations(text, citekeys):
"""
Find all mentioned citekeys in text
"""
citekey_stops = r"[@',\#}{~%\[\]\s]"
citekeys_re = [re.escape('@' + citekey) for citekey in citekeys]
citekeys_re.extend([re.escape('[#' + citekey) for citekey in citekeys])
citekeys_re = [ckre + citekey_stops for ckre in citekeys_re]
# print('\n'.join(citekeys_re))
finder = re.compile('|'.join(citekeys_re))
founds_raw = finder.findall(text)
founds = []
for citekey in founds_raw:
if citekey.startswith('[#'):
citekey = citekey[1:]
founds.append(citekey[:-1]) # don't add stop char
founds = set(founds)
return founds
@staticmethod
def create_bibliography(text, bibfile, pandoc='pandoc'):
"""
Create a bibliography for all citations in text in form of a dictionary.
"""
citekeys = Autobib.extract_all_citekeys(bibfile)
if not citekeys:
return {}
citekeys = Autobib.find_citations(text, citekeys)
citekey2bib = {}
for citekey in citekeys:
pandoc_input = citekey.replace('#', '@', 1)
pandoc_out = Autobib.run(pandoc, bibfile, pandoc_input)
citation, bib = Autobib.parse_pandoc_out(pandoc_out)
citekey2bib[citekey] = bib
return citekey2bib
@staticmethod
def parse_pandoc_out(pandoc_out):
"""
Splits pandoc output into citation and bib part
"""
# print('pandoc_out:', repr(pandoc_out))
pdsplit = pandoc_out.split('\n\n')
citation = '(no citation generated)'
bib = '(no bib generated)'
if len(pdsplit) >= 1:
citation = pdsplit[0]
if len(pdsplit) >= 2:
bib = pdsplit[1]
citation = citation.replace('\n', ' ')
bib = bib.replace('\n', ' ')
return citation, bib
@staticmethod
def run(pandoc_bin, bibfile, stdin):
args = [pandoc_bin, '-t', 'plain', '--bibliography', bibfile]
# using universal_newlines here gets us into decoding troubles as the
# encoding then is guessed and can be ascii which can't deal with
# unicode characters. hence, we handle \r ourselves
p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate(bytes(stdin, 'utf-8'))
# make me windows-safe
stdout = stdout.decode('utf-8', errors='ignore').replace('\r', '')
stderr = stderr.decode('utf-8', errors='ignore').replace('\r', '')
# print('pandoc says:', stderr)
return stdout
class ExternalSearch:
"""
Static class to group all external search related functions.
"""
SEARCH_COMMAND = 'ag'
EXTERNALIZE = '.search_results.zkr' # '' to skip
@staticmethod
def search_all_tags(folder, extension):
"""
Create a list of all #tags of all notes in folder.
"""
output = ExternalSearch.search_in(folder, ZkConstants.RE_TAGS(),
extension, tags=True)
tags = set()
for line in output.split('\n'):
if line:
tags.add(line)
if ExternalSearch.EXTERNALIZE:
with open(ExternalSearch.external_file(folder), mode='w',
encoding='utf-8') as f:
f.write('# All Tags\n\n')
for tag in sorted(tags):
f.write(u'* {}\n'.format(tag))
return list(tags)
@staticmethod
def notes_and_tags_in(folder, extension):
"""
Return a dict {note_id: tags}.
"""
args = [ExternalSearch.SEARCH_COMMAND, '--nocolor', '--ackmate']
args.extend(['--nonumbers', '-o', '--silent', '-G', '.*\\' + extension,
ZkConstants.RE_TAGS(), folder])
ag_out = ExternalSearch.run(args, folder)
if not ag_out:
return {}
note_tags = defaultdict(list)
note_id = None
lines = deque(ag_out.split('\n'))
lindex = 0
num_lines = len(lines)
while lines:
line = lines.popleft()
if not line.startswith(':'):
continue
note_id = get_note_id_of_file(line[1:])
line = lines.popleft()
while line: # until newline
# parse findspec
positions, txt_line = line.split(':', 1)
for position in positions.split(','):
start, width = position.split()
start = int(start)
width = int(width)
tag = txt_line[start:start + width]
note_tags[note_id].append(tag.strip())
line = lines.popleft()
return note_tags
@staticmethod
def search_tagged_notes(folder, extension, tag, externalize=True):
"""
Return a list of note files containing #tag.
"""
output = ExternalSearch.search_in(folder, tag, extension)
prefix = 'Notes referencing {}:'.format(tag)
if externalize:
ExternalSearch.externalize_note_links(
output, folder, extension, prefix)
return output.split('\n')
@staticmethod
def search_friend_notes(folder, extension, note_id):
"""
Return a list of notes referencing note_id.
"""
regexp = '(\[' + note_id + ')|(§' + note_id + ')' # don't insist on ]
output = ExternalSearch.search_in(folder, regexp, extension)
link_prefix, link_postfix = get_link_pre_postfix()
prefix = 'Notes referencing {}{}{}:'.format(link_prefix, note_id,
link_postfix)
ExternalSearch.externalize_note_links(output, folder, extension,
prefix)
return output.split('\n')
@staticmethod
def search_in(folder, regexp, extension, tags=False):
"""
Perform an external search for regexp in folder.
tags == True : only matching words are returned.
tags == False: only names of files with matches are returned.
"""
args = [ExternalSearch.SEARCH_COMMAND, '--nocolor']
if tags:
args.extend(['--nofilename', '--nonumbers', '--only-matching'])
else:
args.extend(['-l', '--ackmate'])
args.extend(['--silent', '-G', '.*\\' + extension, regexp, folder])
return ExternalSearch.run(args, folder)
@staticmethod
def run(args, folder):
"""
Execute ag to run a search, handle errors & timeouts.
Return output of stdout as string.
"""
output = b''
verbose = False
if verbose or True:
print('cmd:', ' '.join(args))
try:
output = subprocess.check_output(args, shell=False, timeout=10000)
except subprocess.CalledProcessError as e:
print('sublime_zk: search unsuccessful:')
print(e.returncode)
print(e.cmd)
for line in e.output.decode('utf-8', errors='ignore').split('\n'):
print(' ', line)
except subprocess.TimeoutExpired:
print('sublime_zk: search timed out:', ' '.join(args))
if verbose:
print(output.decode('utf-8', errors='ignore'))
return output.decode('utf-8', errors='ignore').replace('\r', '')
@staticmethod
def externalize_note_links(ag_out, folder, extension, prefix=None):
"""
If enabled, write ag file name output into external search results file
in `[[note_id]] note title` style.
"""
if ExternalSearch.EXTERNALIZE:
link_prefix, link_postfix = get_link_pre_postfix()
with open(ExternalSearch.external_file(folder),
mode='w', encoding='utf-8') as f:
if prefix:
f.write(u'{}\n\n'.format(prefix))
results = []
for line in sorted(ag_out.split('\n')):
if not line.strip():
continue
if line.endswith(extension):
line = os.path.basename(line)
line = line.replace(extension, '')
if not ' ' in line:
line += ' '
note_id, title = line.split(' ', 1)
note_id = os.path.basename(note_id)
results.append((note_id, title))
settings = get_settings()
sort_order = settings.get('sort_notelists_by', 'id').lower()
if sort_order not in ('id', 'title'):
sort_order = 'id'
column = 0
if sort_order == 'title':
column = 1
results.sort(key=itemgetter(column))
for note_id, title in results:
f.write(u'* {}{}{} {}\n'.format(link_prefix, note_id,
link_postfix, title))
@staticmethod
def external_file(folder):
""" Return the name of the external search results file. """
return os.path.join(folder, ExternalSearch.EXTERNALIZE)
@staticmethod
def show_search_results(window, folder, title, lines, new_pane_setting):
"""
Helper method to display the results either in the external file
or, if not available, in a new window
"""
global PANE_FOR_OPENING_RESULTS
if ExternalSearch.EXTERNALIZE:
new_view = window.open_file(ExternalSearch.external_file(folder))
window.set_view_index(new_view, PANE_FOR_OPENING_RESULTS, 0)
new_view.set_syntax_file(ZKMode.ZKM_Results_Syntax_File)
else:
settings = get_settings()
new_pane = settings.get(new_pane_setting)
if new_pane:
window.run_command('set_layout', {
'cols': [0.0, 0.5, 1.0],
'rows': [0.0, 1.0],
'cells': [[0, 0, 1, 1], [1, 0, 2, 1]]
})
# goto right-hand pane
window.focus_group(1)
tagview = window.new_file()
tagview.set_name(title)
tagview.set_scratch(True)
tagview.run_command(
"insert", {"characters": ' ' + '\n'.join(lines)})
tagview.set_syntax_file(ZkConstants.Syntax_File)
# return back to note
window.focus_group(0)
class TextProduction:
"""
Static class grouping functions for text production from overview notes.
"""
@staticmethod
def read_full_note(note_id, folder, extension):
"""
Return contents of note with ID note_id.
"""
note_file = note_file_by_id(note_id, folder, extension)
if not note_file:
return None, None
with open(note_file, mode='r', encoding='utf-8') as f:
return note_file, f.read()
@staticmethod
def embed_note(note_id, folder, extension, link_prefix, link_postfix):
"""
Put the contents of a note into a comment block.
"""
result_lines = []
note_file, content = TextProduction.read_full_note(note_id, folder,
extension)
footer = '<!-- (End of note ' + note_id + ') -->'
if not content:
header = '<!-- Note not found: ' + note_id + ' -->'
result_lines.append(header)
else:
filename = os.path.basename(note_file).replace(extension, '')
filename = filename.split(' ', 1)[1]
header = link_prefix + note_id + link_postfix + ' ' + filename
header = '<!-- ! ' + header + ' -->'
result_lines.append(header)
result_lines.extend(content.split('\n'))
result_lines.append(footer)
return result_lines
@staticmethod
def expand_links(text, folder, extension, replace_lines=False):
"""
Expand all note-links in text, replacing their lines by note contents.
"""
result_lines = []
for line in text.split('\n'):
link_results = ZkConstants.Link_Matcher.findall(line)
if link_results:
if not replace_lines:
result_lines.append(line)
for pre, note_id, post in link_results:
result_lines.extend(TextProduction.embed_note(note_id,
folder, extension, pre, post))
else:
result_lines.append(line)
return '\n'.join(result_lines)
@staticmethod
def refresh_result(text, folder, extension):
"""
Refresh the result of expand_links with current contents of referenced
notes.
"""
result_lines = []
state = 'default'
note_id = pre = post = None
for line in text.split('\n'):
if state == 'skip_lines':
if not line.startswith('<!-- (End of note'):
continue
# insert note
result_lines.extend(TextProduction.embed_note(note_id, folder,
extension, pre, post))
state = 'default'
continue
if line.startswith('<!-- !'):
# get note id
note_links = ZkConstants.Link_Matcher.findall(line)
if note_links:
pre, note_id, post = note_links[0]
state = 'skip_lines'
else:
result_lines.append(line)
return '\n'.join(result_lines)
@staticmethod
def expand_link_in(view, edit, folder, extension):
"""
Expand note-link under cursor inside the current view
"""
linestart_till_cursor_str, link_region = select_link_in(view)
cursor_pos = view.sel()[0].begin()
line_region = view.line(cursor_pos)
pre, post = get_link_pre_postfix()
link_text = ''
if link_region:
link_text = view.substr(link_region)
link_is_citekey = link_text.startswith(
'@') or link_text.startswith('#')
if link_region and not link_is_citekey:
# we're in a link, so expand it
note_id = cut_after_note_id(view.substr(link_region))
result_lines = TextProduction.embed_note(note_id, folder, extension,
pre, post)
# append a newline for empty line after exp.
result_lines.append('')
view.insert(edit, line_region.b, '\n' + '\n'.join(result_lines))
else:
if link_is_citekey:
tag = link_text
else:
# check if we're in a tag
full_line = view.substr(line_region)
line_start = line_region.begin()
cursor_pos_in_line = cursor_pos - line_start
tag, (begin, end) = tag_at(full_line, cursor_pos_in_line)
if not tag:
tag, (begin, end) = pandoc_citekey_at(full_line,
cursor_pos_in_line)
if not tag:
return
# we have a #tag so let's search for tagged notes
note_list = ExternalSearch.search_tagged_notes(folder, extension,
tag, externalize=False)
bullet_list = []
results = []
for line in sorted(note_list):
if not line:
continue
if line.endswith(extension):
line = os.path.basename(line)
line = line.replace(extension, '')
note_id, title = line.split(' ', 1)
note_id = os.path.basename(note_id)
results.append((note_id, title))
settings = get_settings()
sort_order = settings.get('sort_notelists_by', 'id').lower()
if sort_order not in ('id', 'title'):
sort_order = 'id'
column = 0
if sort_order == 'title':
column = 1
results.sort(key=itemgetter(column))
for note_id, title in results:
bullet_line = '* {}{}{} {}'.format(pre, note_id, post, title)
bullet_list.append(bullet_line)
view.insert(edit, line_region.b, '\n' + '\n'.join(bullet_list))
def timestamp():