forked from thatsIch/sublime-rainmeter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rainopen.py
284 lines (220 loc) · 9.43 KB
/
rainopen.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
"""Module for opening paths containing Rainmeter-specific or Windows environment variables."""
import os
import re
import threading
import sublime
import sublime_plugin
from . import rainmeter
from . import logger
# Files to open with sublime instead of the system default
SETTINGS = sublime.load_settings("Rainmeter.sublime-settings")
DEF_EXTS = SETTINGS.get("rainmeter_default_open_sublime_extensions", "")
if DEF_EXTS is not None:
DEF_EXTS = DEF_EXTS.strip().strip(r"|").strip()
else:
DEF_EXTS = ""
ADD_EXTS = SETTINGS.get("rainmeter_open_sublime_extensions", "")
if ADD_EXTS is not None:
ADD_EXTS = ADD_EXTS.strip().strip(r"|").strip()
else:
ADD_EXTS = ""
SUBLIME_FILES = re.compile("(?i).*\\.(" + ADD_EXTS + "|" + DEF_EXTS + ")\\b")
def open_path(path, transient=False):
"""Try to open a path.
A path could be opened either as:
* a file or folder path or
* URL in the system default application, or
* in Sublime if it's a text file.
Use transient=True to open a file in Sublime without assigning it a tab.
A tab will be created once the buffer is modified.
Will return False if the path doesn't exist in the file system, and
True otherwise.
"""
if not path:
return False
if not os.path.exists(path):
return False
sublime.set_timeout(lambda: sublime.status_message("Opening " + path), 10)
if SUBLIME_FILES.search(path):
if transient:
sublime.set_timeout(
lambda: sublime.active_window().open_file(path,
sublime.TRANSIENT),
10)
else:
sublime.set_timeout(
lambda: sublime.active_window().open_file(path),
10)
else:
os.startfile(path)
return True
def open_url(url):
"""Try opening a url with the system default for urls.
Will return False if it's not a url, and True otherwise.
"""
if re.match(r"(?i)(https?|ftp)://", url.strip()):
os.startfile(url)
sublime.set_timeout(lambda: sublime.status_message("Opening " + url),
10)
return True
else:
return False
class TryOpenThread(threading.Thread):
"""A wrapper method to handle threading for opening line embedded URLs."""
def __init__(self, line, region, opn):
"""Construct a thread for opening URL embedded in a line."""
self.line = line
self.region = region
self.opn = opn
threading.Thread.__init__(self)
def __find_prior_quotation_mark(self):
lastquote = self.region.a - 1
while lastquote >= 0 and self.line[lastquote] != "\"":
lastquote -= 1
return lastquote
def __open_selected_text(self):
# 1. Selected text
selected = self.line[self.region.a:self.region.b]
if self.opn(selected):
logger.info("Open selected text")
return True
def __find_next_quotation_mark(self):
nextquote = self.region.b
while nextquote == len(self.line) or self.line[nextquote] != "\"":
nextquote += 1
return nextquote
def __open_enclosed_string(self):
# 2. String enclosed in double quotes
# Find the quotes before the current point (if any)
lastquote = self.__find_prior_quotation_mark()
if not lastquote < 0 and self.line[lastquote] == "\"":
# Find the quote after the current point (if any)
nextquote = self.__find_next_quotation_mark()
if not nextquote == len(self.line) \
and self.line[nextquote] == "\"":
string = self.line[lastquote: nextquote].strip("\"")
if self.opn(string):
logger.info("Open string enclosed in quotes: " + string)
return True
def __find_front_nearest_whitespace(self):
# Find the space before the current point (if any)
lastspace = self.region.a - 1
while lastspace >= 0 \
and self.line[lastspace] != " " \
and self.line[lastspace] != "\t":
lastspace -= 1
# Set to zero if nothing was found until the start of the line
lastspace = max(lastspace, 0)
return lastspace
def __find_back_nearest_whitespace(self):
# Find the space after the current point (if any)
nextspace = self.region.b
while nextspace < len(self.line) \
and self.line[nextspace] != " " \
and self.line[nextspace] != "\t":
nextspace += 1
return nextspace
def __is_front_space(self, lastspace):
return lastspace == 0 \
or self.line[lastspace] == " " \
or self.line[lastspace] == "\t"
def __is_back_space(self, nextspace):
return nextspace >= len(self.line) \
or self.line[nextspace] == " " \
or self.line[nextspace] == "\t"
def __open_whitespaced_region(self):
# 3. Region from last whitespace to next whitespace
lastspace = self.__find_front_nearest_whitespace()
if self.__is_front_space(lastspace):
nextspace = self.__find_back_nearest_whitespace()
if self.__is_back_space(nextspace):
string = self.line[lastspace: nextspace].strip()
if self.opn(string):
logger.info("Open string enclosed in whitespace: " + string)
return True
def __open_after_equals_sign(self):
# 4. Everything after the first \"=\" until the end
# of the line (strip quotes)
mtch = re.search(r"=\s*(.*)\s*$", self.line)
if mtch and self.opn(mtch.group(1).strip("\"")):
logger.info("Open text after \"=\": " + mtch.group(1).strip("\""))
return True
def __open_whole_line(self):
# 5. Whole line (strip comment character at start)
stripmatch = re.search(r"^[ \t;]*?([^ \t;].*)\s*$", self.line)
if self.opn(stripmatch.group(1)):
logger.info("Open whole line: " + stripmatch.group(1))
return
def run(self):
"""Run the thread."""
return self.__open_selected_text() or \
self.__open_enclosed_string() or \
self.__open_whitespaced_region() or \
self.__open_after_equals_sign() or \
self.__open_whole_line()
class RainmeterOpenPathsCommand(sublime_plugin.TextCommand):
"""Try to open paths on lines in the current selection.
Will try to open paths to files, folders or URLs on each line in the
current selection. To achieve this, the following substrings of each line
intersecting the selection are tested:
1. The string inside the selection
2. The string between possible quotes preceding and following the
selection, if any
3. The string between the preceding and following whitespace
4. Everything after the first "=" on the line until the end of the line
5. The whole line, stripped of preceding semicolons
"""
def __split_selection_by_new_lines(self, selection):
# Split all regions into individual segments on lines (using nicely
# confusing python syntax).
return [
j for i in [
self.view.split_by_newlines(region)
for region in selection
]
for j in i
]
def __open_each_line_by_thread(self, lines):
"""Identify segments in selected lines and tries to open them each in a new thread.
This can be resource intensive.
"""
fnm = self.view.file_name()
def opn(string):
"""Simple callback method to apply multiple opening operations.
An URL can be either external or internal and thus is opened differently.
"""
opened = open_path(rainmeter.make_path(string, fnm)) or open_url(string)
if opened:
logger.info("found file or url '" + string + "' to open")
for linereg in lines:
wholeline = self.view.line(linereg)
thread = TryOpenThread(self.view.substr(wholeline),
sublime.Region(linereg.a - wholeline.a,
linereg.b - wholeline.a),
opn)
thread.start()
def run(self, _):
"""Detect various scenarios of file paths and try to open them one after the other.
:param _: _ edit unused
"""
selection = self.view.sel()
lines = self.__split_selection_by_new_lines(selection)
loaded_settings = sublime.load_settings("Rainmeter.sublime-settings")
max_open_lines = loaded_settings.get("rainmeter_max_open_lines", 40)
# Refuse if too many lines selected to avoid freezing
if len(lines) > max_open_lines:
accept = sublime.ok_cancel_dialog(
"You are trying to open " +
str(len(lines)) + " lines.\n" +
"That's a lot, and could take some time. Try anyway?")
if not accept:
return
self.__open_each_line_by_thread(lines)
def is_enabled(self):
"""Check if current syntax is rainmeter."""
israinmeter = self.view.score_selector(self.view.sel()[0].a,
"source.rainmeter")
return israinmeter > 0
def is_visible(self):
"""It is visible if it is in Rainmeter scope."""
return self.is_enabled()