forked from SublimeText-Markdown/MarkdownEditing
-
Notifications
You must be signed in to change notification settings - Fork 0
/
footnotes.py
198 lines (151 loc) · 6.16 KB
/
footnotes.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
import sublime
import sublime_plugin
import re
try:
from MarkdownEditing.mdeutils import *
except ImportError:
from mdeutils import *
DEFINITION_KEY = 'MarkdownEditing-footnote-definitions'
REFERENCE_KEY = 'MarkdownEditing-footnote-references'
REFERENCE_REGEX = "\[\^([^\]]*)\]"
DEFINITION_REGEX = "^ *\[\^([^\]]*)\]:"
def get_footnote_references(view):
ids = {}
for ref in view.get_regions(REFERENCE_KEY):
if not re.match(DEFINITION_REGEX, view.substr(view.line(ref))):
id = view.substr(ref)[2:-1]
if id in ids:
ids[id].append(ref)
else:
ids[id] = [ref]
return ids
def get_footnote_definition_markers(view):
ids = {}
for defn in view.get_regions(DEFINITION_KEY):
id = view.substr(defn).strip()[2:-2]
ids[id] = defn
return ids
def get_footnote_identifiers(view):
ids = list(get_footnote_references(view).keys())
ids.sort()
return ids
def get_last_footnote_marker(view):
ids = sorted([int(a) for a in get_footnote_identifiers(view) if a.isdigit()])
if len(ids):
return int(ids[-1])
else:
return 0
def get_next_footnote_marker(view):
return get_last_footnote_marker(view) + 1
def is_footnote_definition(view):
line = view.substr(view.line(view.sel()[-1]))
return re.match(DEFINITION_REGEX, line)
def is_footnote_reference(view):
refs = view.get_regions(REFERENCE_KEY)
for ref in refs:
if ref.contains(view.sel()[0]):
return True
return False
def strip_trailing_whitespace(view, edit):
tws = view.find('\s+\Z', 0)
if tws:
view.erase(edit, tws)
class MarkFootnotes(sublime_plugin.EventListener):
def update_footnote_data(self, view):
if view_is_markdown(view):
view.add_regions(REFERENCE_KEY, view.find_all(REFERENCE_REGEX), '', 'cross', sublime.HIDDEN)
view.add_regions(DEFINITION_KEY, view.find_all(DEFINITION_REGEX), '', 'cross', sublime.HIDDEN)
def on_modified_async(self, view):
self.update_footnote_data(view)
def on_load(self, view):
self.update_footnote_data(view)
class GatherMissingFootnotesCommand(MDETextCommand):
def run(self, edit):
refs = get_footnote_identifiers(self.view)
defs = get_footnote_definition_markers(self.view)
missingnotes = [note_token for note_token in refs if not note_token in defs]
if len(missingnotes):
self.view.insert(edit, self.view.size(), "\n")
for note in missingnotes:
self.view.insert(edit, self.view.size(), '\n [^%s]: ' % note)
class InsertFootnoteCommand(MDETextCommand):
def run(self, edit):
view = self.view
markernum = get_next_footnote_marker(view)
markernum_str = '[^%s]' % markernum
for sel in view.sel():
startloc = sel.end()
if bool(view.size()):
targetloc = view.find('(\s|$)', startloc).begin()
else:
targetloc = 0
view.insert(edit, targetloc, markernum_str)
if len(view.sel()) > 0:
view.insert(edit, view.size(), '\n' + markernum_str + ': ')
view.sel().clear()
view.sel().add(sublime.Region(view.size(), view.size()))
view.run_command('set_motion', {"inclusive": True, "motion": "move_to", "motion_args": {"extend": True, "to": "eof"}})
if view.settings().get('command_mode'):
view.run_command('enter_insert_mode', {"insert_command": "move", "insert_args": {"by": "characters", "forward": True}})
class GoToFootnoteDefinitionCommand(MDETextCommand):
def run(self, edit):
defs = get_footnote_definition_markers(self.view)
regions = self.view.get_regions(REFERENCE_KEY)
sel = self.view.sel()
if len(sel) == 1:
target = None
selreg = sel[0]
for region in regions:
if selreg.intersects(region):
target = self.view.substr(region)[2:-1]
if not target:
try:
target = self.view.substr(self.view.find(REFERENCE_REGEX, sel[-1].end()))[2:-1]
except:
pass
if target:
self.view.sel().clear()
self.view.sel().add(defs[target])
self.view.show(defs[target])
class GoToFootnoteReferenceCommand(MDETextCommand):
def run(self, edit):
refs = get_footnote_references(self.view)
match = is_footnote_definition(self.view)
if match:
target = match.groups()[0]
self.view.sel().clear()
[self.view.sel().add(a) for a in refs[target]]
self.view.show(refs[target][0])
class MagicFootnotesCommand(MDETextCommand):
def run(self, edit):
if (is_footnote_definition(self.view)):
self.view.run_command('go_to_footnote_reference')
elif (is_footnote_reference(self.view)):
self.view.run_command('go_to_footnote_definition')
else:
self.view.run_command('insert_footnote')
class SwitchToFromFootnoteCommand(MDETextCommand):
def run(self, edit):
if (is_footnote_definition(self.view)):
self.view.run_command('go_to_footnote_reference')
else:
self.view.run_command('go_to_footnote_definition')
class SortFootnotesCommand(MDETextCommand):
def run(self, edit):
strip_trailing_whitespace(self.view, edit)
defs = get_footnote_definition_markers(self.view)
notes = {}
erase = []
keyorder = map(lambda x: self.view.substr(x)[2:-1], self.view.get_regions(REFERENCE_KEY))
keys = []
[keys.append(r) for r in keyorder if not r in keys]
for (key, item) in defs.items():
fnend = self.view.find('(\s*\Z|\n\s*\n(?!\ {4,}))', item.end())
fnreg = sublime.Region(item.begin(), fnend.end())
notes[key] = self.view.substr(fnreg).strip()
erase.append(fnreg)
erase.sort()
erase.reverse()
[self.view.erase(edit, reg) for reg in erase]
for key in keys:
self.view.insert(edit, self.view.size(), '\n\n ' + notes[key])