forked from timlockridge/SublimeEvernote
-
Notifications
You must be signed in to change notification settings - Fork 104
/
sublime_evernote.py
1667 lines (1392 loc) · 64.1 KB
/
sublime_evernote.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
#coding:utf-8
import sys
import os
import json
import re
try:
import ssl
except:
ssl = None
if sys.version_info < (3, 3):
raise RuntimeError('The Evernote plugin works with Sublime Text 3 only')
# NOTE: OAuth was not implemented, because the Python 3 that is built into Sublime Text 3 was
# built without SSL. So, among other things, this means no http.client.HTTPSRemoteConnection
package_file = os.path.normpath(os.path.abspath(__file__))
package_path = os.path.dirname(package_file)
lib_path = os.path.join(package_path, "lib")
if lib_path not in sys.path:
sys.path.append(lib_path)
import evernote.edam.type.ttypes as Types
from evernote.edam.error.ttypes import EDAMErrorCode, EDAMUserException, EDAMSystemException, EDAMNotFoundException
# import evernote.edam.userstore.UserStore as UserStore
import evernote.edam.notestore.NoteStore as NoteStore
import thrift.protocol.TBinaryProtocol as TBinaryProtocol
import thrift.transport.THttpClient as THttpClient
from socket import gaierror
import sublime
import sublime_plugin
import webbrowser
import markdown2
import html2text
from datetime import datetime
from base64 import b64encode, b64decode
EVERNOTE_PLUGIN_VERSION = "2.7.3"
USER_AGENT = {'User-Agent': 'SublimeEvernote/' + EVERNOTE_PLUGIN_VERSION}
EVERNOTE_SETTINGS = "Evernote.sublime-settings"
SUBLIME_EVERNOTE_COMMENT_BEG = "<!-- Sublime:"
SUBLIME_EVERNOTE_COMMENT_END = "-->"
DEBUG = False
def LOG(*args):
if DEBUG:
print("Evernote:", *args)
def extractTags(tags):
try:
tags = json.loads(tags)
except:
tags = [t.strip(' \t') for t in tags and tags.split(",") or []]
return tags
# From markdown2.py
# I know this is ugly but will do until we have a better general solution for metadata
METADATA_PAT = re.compile("""^---[ \t]*\n((?:[ \t]*[^ \t:]+[ \t]*:[^\n]*\n)+)---[ \t]*\n""")
def extract_metadata(text):
metadata = {}
tail = text
if text.startswith("---"): # fast test
match = METADATA_PAT.match(text)
if match:
tail = text[match.end():]
metadata_str = match.group(1).strip()
for line in metadata_str.split('\n'):
key, value = line.split(':', 1)
metadata[key.strip()] = value.strip()
if "tags" in metadata:
metadata["tags"] = extractTags(metadata["tags"])
return {"metadata": metadata, "contents": tail.lstrip('\n')}
METADATA_HEADER = """\
---
title: %s
tags: %s
notebook: %s
---
"""
def metadata_header(title="", tags=[], notebook="", **kw):
return METADATA_HEADER % (title, json.dumps(tags, ensure_ascii=False), notebook)
def set_view_metadata(view, note, reset_modified=True):
view.settings().set("$evernote", True)
view.settings().set("$evernote_guid", note.guid)
view.settings().set("$evernote_title", note.title)
view.settings().set("$evernote_created", note.created)
if reset_modified:
note_is_current(view)
def note_is_current(view):
view.settings().set("$evernote_modified", view.change_count())
def insert_to_view(view, text):
view.run_command('insert', {
'characters': text,
})
return view
def replace_view_text(view, text):
view.run_command('replace_view_text', {
'characters': text
})
return view
def find_syntax(lang, default=None):
res = sublime.find_resources("%s.*Language" % lang)
if res:
return res[-1]
else:
return (default or ("Packages/%s/%s.tmLanguage" % (lang, lang)))
def language_name(scope):
for s in scope.split(' '):
names = s.split('.')
if s.startswith("source."):
return names[1]
elif s.startswith("text."):
if "markdown" in names: # deal with plugins for MD
return "markdown"
elif "latex" in names: # deal with plugins for LaTeX
return "latex"
elif names[1] == "plain":
return ""
else:
return names[-1]
return ""
def datestr(d):
d = datetime.fromtimestamp(d // 1000)
n = datetime.now()
delta = n - d
if delta.days == 0:
if delta.seconds <= 3600 == 0:
if delta.seconds <= 60 == 0:
return "just now"
else:
return "few minutes ago"
else:
return "few hours ago"
elif delta.days == 1:
return "yesterday"
elif delta.days == 2:
return "2 days ago"
return d.strftime("on %d/%m/%y")
ecode = EDAMErrorCode
error_groups = {
'server': ('Internal server error', [ecode.UNKNOWN, ecode.INTERNAL_ERROR, ecode.SHARD_UNAVAILABLE, ecode.UNSUPPORTED_OPERATION ]),
'data': ('User supplied data is invalid or conflicting', [ecode.BAD_DATA_FORMAT, ecode.DATA_REQUIRED, ecode.DATA_CONFLICT, ecode.LEN_TOO_SHORT, ecode.LEN_TOO_LONG, ecode.TOO_FEW, ecode.TOO_MANY]),
'permission': ('Action not allowed, permission denied or limits exceeded', [ecode.PERMISSION_DENIED, ecode.LIMIT_REACHED, ecode.QUOTA_REACHED, ecode.TAKEN_DOWN, ecode.RATE_LIMIT_REACHED]),
'auth': ('Authorisation error, consider re-configuring the plugin', [ecode.INVALID_AUTH, ecode.AUTH_EXPIRED]),
'contents': ('Illegal note contents', [ecode.ENML_VALIDATION])
}
def errcode2name(err):
name = ecode._VALUES_TO_NAMES.get(err.errorCode, "UNKNOWN")
name = name.replace("_", " ").capitalize()
return name
def err_reason(err):
for reason, group in error_groups.values():
if err.errorCode in group:
return reason
return "Unknown reason"
def explain_error(err):
if isinstance(err, EDAMUserException):
printError("Evernote error: [%s]\n\t%s" % (errcode2name(err), err.parameter))
if err.errorCode in error_groups["contents"][1]:
explanation = "The contents of the note are not valid.\n"
msg = err.parameter.split('"')
what = msg[0].strip().lower()
if what == "element type":
return explanation +\
"The inline HTML tag '%s' is not allowed in Evernote notes." %\
msg[1]
elif what == "attribute":
if msg[1] == "class":
return explanation +\
"The note contains a '%s' HTML tag "\
"with a 'class' attribute; this is not allowed in a note.\n"\
"Please use inline 'style' attributes or customise "\
"the 'inline_css' setting." %\
msg[3]
else:
return explanation +\
"The note contains a '%s' HTML tag"\
" with a '%s' attribute; this is not allowed in a note." %\
(msg[3], msg[1])
return explanation + err.parameter
else:
return err_reason(err)
elif isinstance(err, EDAMSystemException):
printError("Evernote error: [%s]\n\t%s" % (errcode2name(err), err.message))
return "Evernote cannot perform the requested action:\n" + err_reason(err)
elif isinstance(err, EDAMNotFoundException):
printError("Evernote error: [%s = %s]\n\tNot found" % (err.identifier, err.key))
return "Cannot find %s" % err.identifier.split('.', 1)[0]
elif isinstance(err, gaierror):
printError("Evernote error: [socket]\n\t%s" % str(err))
return 'The Evernote services seem unreachable.\n'\
'Please check your connection and retry.'
else:
printError("Evernote plugin error: %s" % str(err))
return 'Evernote plugin error, please see the console for more details.\nThen contact developer at\n'\
'https://github.com/bordaigorl/sublime-evernote/issues'
def printError(msg):
print(msg)
last_cmd, last_args, _ = sublime.active_window().active_view().command_history(-1)
print("\tLast command: %s %s" % (last_cmd, last_args or {}))
print("\tBEFORE SUBMITTING AN ISSUE (https://github.com/bordaigorl/sublime-evernote/issues):")
print("\t 1. Enable the `debug` setting in your Evernote.sublime-settings file and try again. If the problem persists take a note of the output in the console.\n\t Make sure you delete personal information (e.g. Developer Token) from the output before posting it in an issue.")
print("\t 2. Check the wiki at https://github.com/bordaigorl/sublime-evernote/wiki")
print("\t 3. Search for similar issues at https://github.com/bordaigorl/sublime-evernote/issues?q=is%3Aissue")
print("\t(Evernote plugin v%s, ST %s, Python %s, %s %s%s)" % (
EVERNOTE_PLUGIN_VERSION,
sublime.version(),
"%s.%s.%s" % sys.version_info[:3],
sublime.platform(),
sublime.arch(),
', debug' if DEBUG else '' ))
def async_do(f, progress_msg="Evernote operation", done_msg="", on_completion=None):
if done_msg == "":
done_msg = progress_msg + ': ' + "done!"
status = {'done': False, 'i': 0}
def do_stuff(s):
try:
f()
except:
pass
finally:
s['done'] = True
if on_completion:
on_completion()
def progress(s):
if s['done']:
if done_msg is not None:
sublime.status_message(done_msg)
else:
i = s['i']
bar = "... [%s=%s]" % (' '*i, ' '*(7-i))
sublime.status_message(progress_msg + bar)
s['i'] = (i + 1) % 8
sublime.set_timeout(lambda: progress(s), 100)
sublime.set_timeout(lambda: progress(status), 0)
sublime.set_timeout_async(lambda: do_stuff(status), 0)
class EvernoteDo():
_noteStore = None
_notebook_by_guid = None
_notebook_by_name = None
_notebooks_cache = None
_tag_name_cache = {}
_tag_guid_cache = {}
MD_EXTRAS = {
'footnotes' : None,
'cuddled-lists' : None,
'metadata' : None,
'markdown-in-html' : None,
'fenced-code-blocks' : {'noclasses': True, 'cssclass': "", 'style': "default"}
}
def token(self):
return self.settings.get("token")
def get_shard_id(self, token=None):
token_parts = (token or self.token()).split(":")
id = token_parts[0][2:]
return id
def get_user_id(self, token=None):
token_parts = (token or self.token()).split(":")
id = token_parts[1][2:]
return int(id, 16)
def load_settings(self):
global DEBUG
self.settings = sublime.load_settings(EVERNOTE_SETTINGS)
DEBUG = bool(self.settings.get('debug'))
pygm_style = self.settings.get('code_highlighting_style')
if pygm_style:
if pygm_style == "github":
from pygmstyles.github import GithubStyle
pygm_style = GithubStyle
elif pygm_style == "github2014":
from pygmstyles.github2014 import Github2014Style
pygm_style = Github2014Style
EvernoteDo.MD_EXTRAS['fenced-code-blocks']['style'] = pygm_style
if self.settings.get("code_friendly"):
EvernoteDo.MD_EXTRAS['code-friendly'] = None
html2text.EMPHASIS_MARK = "*"
else:
html2text.EMPHASIS_MARK = self.settings.get('emphasis_mark', html2text.EMPHASIS_MARK)
if self.settings.get("wiki_tables"):
EvernoteDo.MD_EXTRAS['wiki-tables'] = None
if self.settings.get("gfm_tables"):
EvernoteDo.MD_EXTRAS['tables'] = None
css = self.settings.get("inline_css")
if css is not None:
for tag in css:
css[tag] = css[tag].strip()
if len(css[tag]) > 0 and not css[tag].endswith(";"):
css[tag] = css[tag] + ";"
EvernoteDo.MD_EXTRAS['inline-css'] = css
self.md_syntax = self.settings.get("md_syntax")
if not self.md_syntax:
self.md_syntax = find_syntax("Evernote")
html2text.UL_ITEM_MARK = self.settings.get('item_mark', html2text.UL_ITEM_MARK)
html2text.STRONG_MARK = self.settings.get('strong_mark', html2text.STRONG_MARK)
def message(self, msg):
sublime.status_message(msg)
def update_status_info(self, note, view=None):
view = view or (self.view if hasattr(self, "view") else None)
if not view:
return
info = "Note created %s, updated %s, %s attachments" % (
datestr(note.created), datestr(note.updated), len(note.resources or []))
view.set_status("Evernote-info", info)
if view.file_name() is None:
if self.settings.has("tab_title"): # this way we avoid extra work if feature not needed
try:
nb = self.notebook_from_guid(note.notebookGuid)
note_data = {
"date": datetime.fromtimestamp(note.created // 1000).strftime("%d/%m/%y"),
"title": note.title,
"notebook": nb.name,
"stack": nb.stack,
"prefix": self.settings.get("tab_prefix", "")
}
view.set_name(self.settings.get("tab_title", "").format(**note_data))
except Exception:
view.set_name(self.settings.get("tab_prefix", "") + note.title)
else:
view.set_name(self.settings.get("tab_prefix", "") + note.title)
def connect(self, callback, **kwargs):
self.message("initializing..., please wait...")
def __connect(token, noteStoreUrl):
if noteStoreUrl.startswith("https://") and not ssl:
LOG("Not using SSL")
noteStoreUrl = "http://" + noteStoreUrl[8:]
self.settings.set("token", token)
self.settings.set("noteStoreUrl", noteStoreUrl)
sublime.save_settings(EVERNOTE_SETTINGS)
callback(**kwargs)
def __derive_note_store_url(token):
id = self.get_shard_id(token)
url = "www.evernote.com/shard/" + id + "/notestore"
if ssl:
url = "https://" + url
else:
url = "http://" + url
return url
def on_token(token):
noteStoreUrl = self.settings.get("noteStoreUrl")
if not noteStoreUrl:
noteStoreUrl = __derive_note_store_url(token)
p = self.window.show_input_panel(
"NoteStore URL (required):", noteStoreUrl,
lambda x: __connect(token, x),
None, None)
p.sel().add(sublime.Region(0, p.size()))
else:
__connect(token, noteStoreUrl)
token = self.token()
noteStoreUrl = self.settings.get("noteStoreUrl")
if not token or not noteStoreUrl:
webbrowser.open_new_tab("https://www.evernote.com/api/DeveloperToken.action")
self.window.show_input_panel(
"Developer Token (required):", token or "",
on_token, None, None)
def get_note_store(self):
if EvernoteDo._noteStore:
return EvernoteDo._noteStore
noteStoreUrl = self.settings.get("noteStoreUrl")
noteStoreHttpClient = THttpClient.THttpClient(noteStoreUrl)
noteStoreHttpClient.setCustomHeaders(USER_AGENT)
noteStoreProtocol = TBinaryProtocol.TBinaryProtocol(noteStoreHttpClient)
noteStore = NoteStore.Client(noteStoreProtocol)
EvernoteDo._noteStore = noteStore
return noteStore
def get_notebooks(self):
if EvernoteDo._notebooks_cache:
LOG("Using cached notebooks list")
return EvernoteDo._notebooks_cache
notebooks = None
try:
noteStore = self.get_note_store()
self.message("Fetching notebooks, please wait...")
notebooks = noteStore.listNotebooks(self.token())
self.message("Fetched all notebooks!")
if self.settings.get("sort_notebooks"):
notebooks.sort(key=lambda nb: nb.name)
except Exception as e:
sublime.error_message(explain_error(e))
LOG(e)
return []
EvernoteDo._notebook_by_name = dict([(nb.name, nb) for nb in notebooks])
EvernoteDo._notebook_by_guid = dict([(nb.guid, nb) for nb in notebooks])
EvernoteDo._notebooks_cache = notebooks
return notebooks
def create_notebook(self, name):
try:
noteStore = self.get_note_store()
notebook = Types.Notebook()
notebook.name = name
notebooks = noteStore.createNotebook(self.token(), notebook)
except Exception as e:
sublime.error_message(explain_error(e))
LOG(e)
return None
EvernoteDo._notebooks_cache = None # To force notebook cache refresh
return self.notebook_from_name(name)
def get_note_link(self, guid):
linkformat = 'evernote:///view/{userid}/{shardid}/{noteguid}/{noteguid}/'
return linkformat.format(userid=self.get_user_id(), shardid=self.get_shard_id(), noteguid=guid)
def notebook_from_guid(self, guid):
self.get_notebooks() # To trigger caching
return EvernoteDo._notebook_by_guid[guid]
def notebook_from_name(self, name):
self.get_notebooks() # To trigger caching
return EvernoteDo._notebook_by_name[name]
def tag_from_guid(self, guid):
if guid not in EvernoteDo._tag_name_cache:
name = self.get_note_store().getTag(self.token(), guid).name
EvernoteDo._tag_name_cache[guid] = name
EvernoteDo._tag_guid_cache[name] = guid
return EvernoteDo._tag_name_cache[guid]
def tag_from_name(self, name):
if name not in EvernoteDo._tag_guid_cache:
# This requires downloading the full list
self.cache_all_tags()
return EvernoteDo._tag_guid_cache[name]
def cache_all_tags(self):
tags = self.get_note_store().listTags(self.token())
for tag in tags:
EvernoteDo._tag_name_cache[tag.guid] = tag.name
EvernoteDo._tag_guid_cache[tag.name] = tag.guid
@staticmethod
def clear_cache():
EvernoteDo._noteStore = None
EvernoteDo._notebook_by_name = None
EvernoteDo._notebook_by_guid = None
EvernoteDo._notebooks_cache = None
EvernoteDo._tag_guid_cache = {}
EvernoteDo._tag_name_cache = {}
def populate_note(self, note, contents):
if isinstance(contents, sublime.View):
contents = contents.substr(sublime.Region(0, contents.size()))
body = markdown2.markdown(contents, extras=EvernoteDo.MD_EXTRAS)
wrapper_style = ''
if 'inline-css' in EvernoteDo.MD_EXTRAS:
wrapper_style = EvernoteDo.MD_EXTRAS['inline-css'].get('body', "")
if len(wrapper_style) > 0:
wrapper_style = ' style="%s"' % wrapper_style
meta = body.metadata or {}
content = '<?xml version="1.0" encoding="UTF-8"?>'
content += '<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">'
content += '<en-note%s>' % wrapper_style
if self.settings.get('use_legacy_comments', False):
hidden = ('\n%s%s%s\n' %
(SUBLIME_EVERNOTE_COMMENT_BEG,
b64encode(contents.encode('utf8')).decode('utf8'),
SUBLIME_EVERNOTE_COMMENT_END))
content += hidden
content += body
LOG(body)
content += '</en-note>'
note.title = meta.get("title", note.title)
tags = meta.get("tags", note.tagNames)
if tags is not None:
tags = extractTags(tags)
LOG(tags)
note.tagNames = tags
note.content = content
if "notebook" in meta:
notebooks = self.get_notebooks()
for nb in notebooks:
if nb.name == meta["notebook"]:
note.notebookGuid = nb.guid
break
return note
class EvernoteDoText(EvernoteDo, sublime_plugin.TextCommand):
def message(self, msg, timeout=5000):
self.view.set_status("Evernote", msg)
if timeout:
sublime.set_timeout(lambda: self.view.erase_status("Evernote"), timeout)
def run(self, edit, **kwargs):
if DEBUG:
from imp import reload
reload(markdown2)
reload(html2text)
self.window = self.view.window()
self.load_settings()
try:
if not self.token():
self.connect(lambda **kw: self.do_run(edit, **kw), **kwargs)
else:
self.do_run(edit, **kwargs)
except Exception as e:
sublime.error_message('Evernote error:\n%s' % explain_error(e))
class EvernoteDoWindow(EvernoteDo, sublime_plugin.WindowCommand):
def run(self, **kwargs):
if DEBUG:
from imp import reload
reload(markdown2)
reload(html2text)
self.view = self.window.active_view()
self.load_settings()
try:
if not self.token():
self.connect(self.do_run, **kwargs)
else:
self.do_run(**kwargs)
except Exception as e:
sublime.error_message('Evernote error:\n%s' % explain_error(e))
class SendToEvernoteCommand(EvernoteDoText):
def do_run(self, edit, **kwargs):
self.do_send(**kwargs)
def do_send(self, **args):
noteStore = self.get_note_store()
note = Types.Note()
view = self.view
if "title" in args:
note.title = args["title"]
if "notebook" in args:
try:
note.notebookGuid = self.notebook_from_name(args["notebook"]).guid
except:
note.notebookGuid = None
if "tags" in args:
note.tagNames = extractTags(args["tags"])
on_send_completion = None
if "on_completion" in args:
on_send_completion = args["on_completion"]
default_tags = args.get("default_tags", "")
default_title = ""
contents = ""
clip = args.get("clip", False)
if clip:
if not view.has_non_empty_selection_region():
sels = [sublime.Region(0, view.size())]
else:
sels = view.sel()
import re
INDENT = re.compile(r'^\s*', re.M)
snippets = []
for region in sels:
if region.size() > 0:
lang = language_name(view.scope_name(region.begin()))
snippet = view.substr(region)
# deindent if necessary
strip = None
for m in INDENT.findall(snippet):
l = len(m)
if l <= (strip or l):
strip = l
if strip == 0:
break
# strip = min([len(m) for m in INDENT.findall(snippet)])
if strip > 0:
snippet = '\n'.join([line[strip:] for line in snippet.splitlines()])
snippets.append("```%s\n%s\n```" % (lang, snippet))
contents = "\n\n".join(snippets) + "\n"
if view.file_name():
default_title = "Clip from "+os.path.basename(view.file_name())
else:
contents = view.substr(sublime.Region(0, view.size()))
notebooks = self.get_notebooks()
self.populate_note(note, contents)
def on_cancel():
self.message("Note not sent.")
def choose_title():
if not note.title:
self.window.show_input_panel(
"Title (required):", default_title, choose_tags, None, on_cancel)
else:
choose_tags()
def choose_tags(title=None):
if title is not None:
note.title = title
if note.tagNames is None:
self.window.show_input_panel(
"Tags (Optional):", default_tags, choose_notebook, None, on_cancel)
else:
choose_notebook()
def choose_notebook(tags=None):
if tags is not None:
note.tagNames = extractTags(tags)
if note.notebookGuid is None:
self.window.show_quick_panel([notebook.name for notebook in notebooks], on_notebook)
else:
__send_note(note.notebookGuid)
def on_notebook(notebook):
if notebook >= 0:
__send_note(notebooks[notebook].guid)
else:
on_cancel()
def __send_note(notebookGuid):
async_do(lambda: __send_note_async(notebookGuid), "Sending note", on_completion=on_send_completion)
def __send_note_async(notebookGuid):
note.notebookGuid = notebookGuid
LOG(note.title)
LOG(note.tagNames)
LOG(note.notebookGuid)
LOG(note.content)
try:
self.message("Posting note, please wait...")
cnote = noteStore.createNote(self.token(), note)
if not clip:
set_view_metadata(view, cnote)
view.set_syntax_file(self.md_syntax)
self.message("Successfully posted note: guid:%s" % cnote.guid, 10000)
self.update_status_info(cnote)
except EDAMUserException as e:
args = dict(title=note.title, notebookGuid=note.notebookGuid, tags=note.tagNames)
if e.errorCode == 9:
self.connect(self.do_send, **args)
else:
if sublime.ok_cancel_dialog('Evernote complained:\n\n%s\n\nRetry?' % explain_error(e)):
self.connect(self.do_send, **args)
except EDAMSystemException as e:
sublime.error_message('Evernote error:\n%s' % explain_error(e))
except Exception as e:
sublime.error_message('Evernote plugin error %s' % e)
choose_title()
class SaveEvernoteNoteCommand(EvernoteDoText):
def do_run(self, edit, **args):
note = Types.Note()
noteStore = self.get_note_store()
on_save_completion = None
if "on_completion" in args:
on_save_completion = args["on_completion"]
note.title = self.view.settings().get("$evernote_title")
note.guid = self.view.settings().get("$evernote_guid")
self.populate_note(note, self.view)
self.message("Updating note, please wait...")
def __update_note():
try:
cnote = noteStore.updateNote(self.token(), note)
set_view_metadata(self.view, cnote)
self.message("Successfully updated note: guid:%s" % cnote.guid)
self.update_status_info(cnote)
except Exception as e:
if sublime.ok_cancel_dialog('Evernote complained:\n\n%s\n\nRetry?' % explain_error(e)):
self.connect(self.__update_note)
async_do(__update_note, "Updating note", on_completion=on_save_completion)
def is_enabled(self, **kw):
if self.view.settings().get("$evernote_guid", False):
return True
return False
DELETE_MSG = "You are about to delete '%s'.\nYour note will still be recoverable from the Trash.\nDo you want to proceed?"
class DeleteEvernoteNoteCommand(EvernoteDoText):
def do_run(self, edit, guid=None, prompt=True):
if guid is None:
guid = self.view.settings().get("$evernote_guid")
if guid:
title = self.view.settings().get("$evernote_title", "Untitled")
noteStore = self.get_note_store()
if not prompt or sublime.ok_cancel_dialog(DELETE_MSG % title):
noteStore.deleteNote(self.token(), guid)
self.view.settings().set("$evernote_guid", None)
self.view.settings().set("$evernote_modified", self.view.change_count())
self.view.close()
return
def is_enabled(self, **kw):
if self.view.settings().get("$evernote_guid", False):
return True
return False
class OpenEvernoteNoteCommand(EvernoteDoWindow):
def do_run(self, note_guid=None, by_searching=None,
from_notebook=None, with_tags=None,
order=None, ascending=None, max_notes=None, **kwargs):
notebooks = self.get_notebooks()
search_args = {}
order = order or self.settings.get("notes_order", "default").upper()
search_args['order'] = Types.NoteSortOrder._NAMES_TO_VALUES.get(order.upper()) # None = default
search_args['ascending'] = ascending or self.settings.get("notes_order_ascending", False)
if from_notebook:
try:
search_args['notebookGuid'] = self.notebook_from_name(from_notebook).guid
except:
sublime.error_message("Notebook %s not found!" % from_notebook)
return
if with_tags:
if isinstance(with_tags, str):
with_tags = [with_tags]
try:
search_args['tagGuids'] = [self.tag_from_name(name) for name in with_tags]
except KeyError as e:
sublime.error_message("Tag %s not found!" % e)
def notes_panel(notes, show_notebook=False):
if not notes:
self.message("No notes found!") # Should it be a dialog?
return
def on_note(i):
if i < 0:
return
self.message('Retrieving note "%s"...' % notes[i].title)
self.open_note(notes[i].guid, **kwargs)
if len(notes) == 1 and self.settings.get("open_single_result"):
on_note(0)
return
if show_notebook:
menu = ["[%s] » %s" % (self.notebook_from_guid(note.notebookGuid).name, note.title) for note in notes]
# menu = [[note.title, self.notebook_from_guid(note.notebookGuid).name] for note in notes]
else:
menu = [note.title for note in notes]
self.window.show_quick_panel(menu, on_note)
def on_notebook(notebook):
if notebook < 0:
return
search_args['notebookGuid'] = notebooks[notebook].guid
notes = self.find_notes(search_args, max_notes)
async_do(lambda: notes_panel(notes), "Fetching notes list", done_msg=None)
def do_search(query):
self.message("Searching notes...")
search_args['words'] = query
async_do(lambda: notes_panel(self.find_notes(search_args, max_notes), True), "Fetching notes list", done_msg=None)
if note_guid:
if note_guid == "prompt":
self.window.show_input_panel("Note GUID or link:", "", lambda x: self.open_note(x, **kwargs), None, None)
return
elif note_guid == "clipboard":
note_guid = sublime.get_clipboard(2000)
self.open_note(note_guid, **kwargs)
return
if by_searching:
if isinstance(by_searching, str):
do_search(by_searching)
else:
p = self.window.show_input_panel("Enter search query:", "", do_search, None, None)
if isinstance(by_searching, dict):
p.run_command("insert_snippet", {"contents": by_searching.get("snippet", "")})
return
if from_notebook or with_tags:
notes_panel(self.find_notes(search_args, max_notes), not from_notebook)
elif len(notebooks) == 1:
on_notebook(0)
else:
if self.settings.get("show_stacks", True):
menu = ["%s » %s" % (nb.stack, nb.name) if nb.stack else nb.name for nb in notebooks]
else:
menu = [nb.name for nb in notebooks]
self.window.show_quick_panel(menu, on_notebook)
def find_notes(self, search_args, max_notes=None):
return self.get_note_store().findNotesMetadata(
self.token(),
NoteStore.NoteFilter(**search_args),
None, max_notes or self.settings.get("max_notes", 100),
NoteStore.NotesMetadataResultSpec(includeTitle=True, includeNotebookGuid=True)).notes
def open_note(self, guid, convert=True, **unk_args):
try:
guid = guid.strip().split('/')[-1]
except Exception:
pass
async_do(lambda: self.do_open_note(guid, convert, **unk_args), "Retrieving note")
def do_open_note(self, guid, convert=True, **unk_args):
try:
noteStore = self.get_note_store()
note = noteStore.getNote(self.token(), guid, True, False, False, False)
nb_name = self.notebook_from_guid(note.notebookGuid).name
LOG(note.content)
LOG(note.guid)
if convert:
# tags = [noteStore.getTag(self.token(), guid).name for guid in (note.tagGuids or [])]
# tags = [self.tag_from_guid(guid) for guid in (note.tagGuids or [])]
tags = noteStore.getNoteTagNames(self.token(), note.guid)
meta = metadata_header(note.title, tags, nb_name)
body_start = note.content.find('<en-note')
if body_start < 0:
body_start = 0
else:
body_start = note.content.find('>', body_start) + 1
builtin = note.content.find(SUBLIME_EVERNOTE_COMMENT_BEG, body_start, body_start+100)
if builtin >= 0:
try:
builtin_end = note.content.find(SUBLIME_EVERNOTE_COMMENT_END, builtin)
bmdtxt = note.content[builtin+len(SUBLIME_EVERNOTE_COMMENT_BEG):builtin_end]
mdtxt = b64decode(bmdtxt.encode('utf8')).decode('utf8')
parts = extract_metadata(mdtxt)
if parts["metadata"]:
if parts["metadata"].get("title") == note.title and \
"tags" in parts["metadata"] and \
set(parts["metadata"].get("tags")) == set(tags) and \
parts["metadata"].get("notebook") == nb_name:
meta = ""
else:
LOG("Overridding metadata")
mdtxt = parts["contents"]
LOG("Loaded from built-in comment")
except Exception as e:
mdtxt = ""
LOG("Loading from built-in comment failed", e)
if builtin < 0 or mdtxt == "":
try:
mdtxt = html2text.html2text(note.content)
LOG("Conversion ok")
except Exception as e:
mdtxt = note.content
LOG("Conversion failed", e)
if unk_args.get('open_new_file', True) == False:
newview = self.window.active_view()
else:
newview = self.window.new_file()
set_view_metadata(newview, note, False)
syntax = self.md_syntax
note_contents = meta+mdtxt
else:
newview = self.window.new_file()
syntax = find_syntax("XML")
note_contents = note.content
newview.set_syntax_file(syntax)
newview.set_scratch(True)
replace_view_text(newview, note_contents)
self.message('Note "%s" opened!' % note.title)
self.update_status_info(note, newview)
note_is_current(newview)
except Exception as e:
sublime.error_message(explain_error(e))
class OpenEvernoteNotesCommand(EvernoteDoWindow):
def do_run(self, note_guid=None, by_searching=None,
from_notebook=None, with_tags=None,
order=None, ascending=None, max_notes=None, **kwargs):
notebooks = self.get_notebooks()
search_args = {}
order = order or self.settings.get("notes_order", "default").upper()
search_args['order'] = Types.NoteSortOrder._NAMES_TO_VALUES.get(order.upper()) # None = default
search_args['ascending'] = ascending or self.settings.get("notes_order_ascending", False)
if from_notebook:
try:
search_args['notebookGuid'] = self.notebook_from_name(from_notebook).guid
except:
sublime.error_message("Notebook %s not found!" % from_notebook)
return
if with_tags:
if isinstance(with_tags, str):
with_tags = [with_tags]
try:
search_args['tagGuids'] = [self.tag_from_name(name) for name in with_tags]
except KeyError as e:
sublime.error_message("Tag %s not found!" % e)
def notes_panel(notes, show_notebook=False):
if not notes:
self.message("No notes found!") # Should it be a dialog?
return
for note in notes:
self.message('Retrieving note "%s"...' % note.title)
self.open_note(note.guid, **kwargs)
def on_notebook(notebook):
if notebook < 0:
return
search_args['notebookGuid'] = notebooks[notebook].guid
notes = self.find_notes(search_args, max_notes)
async_do(lambda: notes_panel(notes), "Fetching notes list", done_msg=None)
def do_search(query):
self.message("Searching notes...")
search_args['words'] = query
async_do(lambda: notes_panel(self.find_notes(search_args, max_notes), True), "Fetching notes list", done_msg=None)
if note_guid:
if note_guid == "prompt":
self.window.show_input_panel("Note GUID or link:", "", lambda x: self.open_note(x, **kwargs), None, None)
return
elif note_guid == "clipboard":