-
-
Notifications
You must be signed in to change notification settings - Fork 245
/
bh_plugin.py
executable file
·198 lines (149 loc) · 5.51 KB
/
bh_plugin.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
"""
BracketHighlighter.
Copyright (c) 2013 - 2016 Isaac Muse <[email protected]>
License: MIT
"""
import sublime
import sublime_plugin
from os.path import normpath, join
import imp
from collections import namedtuple
import sys
import traceback
import re
from .bh_logging import log
class Payload(object):
"""Plugin payload."""
status = False
plugin = None
args = None
@classmethod
def clear(cls):
"""Clear payload."""
cls.status = False
cls.plugin = None
cls.args = None
class BracketRegion (namedtuple('BracketRegion', ['begin', 'end'])):
"""Bracket regions for plugins."""
def move(self, begin, end):
"""Move bracket region to different points."""
return self._replace(begin=begin, end=end)
def size(self):
"""Get the size of the region."""
return abs(self.begin - self.end)
def toregion(self):
"""Convert to sublime region."""
return sublime.Region(self.begin, self.end)
def is_bracket_region(obj):
"""Check if object is a `BracketRegion`."""
return isinstance(obj, BracketRegion)
def sublime_format_path(pth):
"""Format path for Sublime internally."""
m = re.match(r"^([A-Za-z]{1}):(?:/|\\)(.*)", pth)
if sublime.platform() == "windows" and m is not None:
pth = m.group(1) + "/" + m.group(2)
return pth.replace("\\", "/")
def load_modules(obj, loaded):
"""Load bracket plugin modules."""
plib = obj.get("plugin_library")
if plib is None:
return
try:
module = _import_module(plib, loaded)
obj["compare"] = getattr(module, "compare", None)
obj["post_match"] = getattr(module, "post_match", None)
obj["validate"] = getattr(module, "validate", None)
obj["highlighting"] = getattr(module, "highlighting", None)
loaded.add(plib)
except Exception:
log("Could not load module %s\n%s" % (plib, str(traceback.format_exc())))
raise
def _import_module(module_name, loaded=None):
"""
Import the module.
Import the module and track which modules have been loaded
so we don't load already loaded modules.
"""
# Pull in built-in and custom plugin directory
if module_name.startswith("bh_modules."):
path_name = join("Packages", "BracketHighlighter", normpath(module_name.replace('.', '/')))
else:
path_name = join("Packages", normpath(module_name.replace('.', '/')))
path_name += ".py"
if loaded is not None and module_name in loaded:
module = sys.modules[module_name]
else:
module = imp.new_module(module_name)
sys.modules[module_name] = module
exec(
compile(
sublime.load_resource(sublime_format_path(path_name)),
module_name,
'exec'
),
sys.modules[module_name].__dict__
)
return module
def import_module(module, attribute=None):
"""Import module or module attribute."""
mod = _import_module(module)
return getattr(mod, attribute) if attribute is not None else mod
class BracketPluginRunCommand(sublime_plugin.TextCommand):
"""Sublime run command to run BH plugins."""
def run(self, edit):
"""Run the plugin."""
try:
Payload.args["edit"] = edit
Payload.plugin.run(**Payload.args)
Payload.status = True
except Exception:
print("BracketHighlighter: Plugin Run Error:\n%s" % str(traceback.format_exc()))
class BracketPlugin(object):
"""Class for preparing and running plugins."""
def __init__(self, plugin, loaded):
"""Load plugin module."""
self.enabled = False
self.args = plugin['args'] if ("args" in plugin) else {}
self.plugin = None
if 'command' in plugin:
plib = plugin['command']
try:
module = _import_module(plib, loaded)
self.plugin = getattr(module, 'plugin')()
loaded.add(plib)
self.enabled = True
except Exception:
print('BracketHighlighter: Load Plugin Error: %s\n%s' % (plugin['command'], traceback.format_exc()))
def is_enabled(self):
"""Check if plugin is enabled."""
return self.enabled
def run_command(self, view, name, left, right, selection):
"""Load arguments into plugin and run."""
nobracket = False
refresh_match = False
Payload.status = False
Payload.plugin = self.plugin()
setattr(Payload.plugin, "left", left)
setattr(Payload.plugin, "right", right)
setattr(Payload.plugin, "view", view)
setattr(Payload.plugin, "selection", selection)
setattr(Payload.plugin, "nobracket", False)
setattr(Payload.plugin, "refresh_match", False)
self.args["edit"] = None
self.args["name"] = name
Payload.args = self.args
# Call a `TextCommand` to run the plugin so it can feed in the `Edit` object
view.run_command("bracket_plugin_run")
if Payload.status:
left = Payload.plugin.left
right = Payload.plugin.right
selection = Payload.plugin.selection
nobracket = Payload.plugin.nobracket
refresh_match = Payload.plugin.refresh_match
Payload.clear()
return left, right, selection, nobracket, refresh_match
class BracketPluginCommand(object):
"""Bracket Plugin base class."""
def run(self, bracket, content, selection):
"""Run the plugin class."""
pass