Repository navigation
Expand file tree
/
Copy pathPythonBreakpoints.py
More file actions
397 lines (307 loc) · 11.8 KB
/
Copy pathPythonBreakpoints.py
File metadata and controls
397 lines (307 loc) · 11.8 KB
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
# -*- coding: utf-8 -*-
"""
Python Breakpoints plugin for Sublime Text editor
Author: Oscar Ibatullin (github.com/obormot)
"""
from __future__ import print_function
import ast
import re
import uuid
import sublime
import sublime_plugin
debug = lambda *a: None # replace with debug = print if needed
############
# Settings #
############
settings = None
pdb_block = ''
tab_size = 4
def plugin_loaded():
global settings
settings = sublime.load_settings("PythonBreakpoints.sublime-settings")
global tab_size
tab_size = settings.get('tab_size')
if tab_size == 'auto' or tab_size is None:
g_settings = sublime.load_settings('Preferences.sublime-settings')
tab_size = g_settings.get('tab_size', 4)
global pdb_block
pdb_block = """\
# do not edit! added by PythonBreakpoints
from %s import set_trace as _breakpoint
""" % settings.get('debugger', 'pdb')
# for ST2
plugin_loaded()
#############
# Constants #
#############
bp_regex = r"^[\t ]*_breakpoint\(\) # ([a-f0-9]{8})"
bp_re = re.compile(bp_regex, re.DOTALL)
EXPR_PRE = ['class', 'def', 'if', 'for', 'try', 'while', 'with']
EXPR_PST = ['elif', 'else', 'except', 'finally']
expr_re0 = re.compile(r"^[\t ]*(%s)[: ]" % '|'.join(EXPR_PRE))
expr_re1 = re.compile(r"^[\t ]*(%s)[: ]" % '|'.join(EXPR_PRE + EXPR_PST))
expr_re2 = re.compile(r"^[\t ]*(%s)[: ]" % '|'.join(EXPR_PST))
class Breakpoint(object):
"""
Breakpoint object with its UID
"""
def __init__(self, from_text=None):
self.uid = None
if from_text is not None:
m = bp_re.match(from_text)
if m:
self.uid = m.groups()[0]
else:
self.uid = str(uuid.uuid4())[-8:]
@property
def rg_key(self):
"""breakpoint's region ID"""
return 'bp-%s' % self.uid
def format(self, indent):
"""format breakpoint string"""
return "%s_breakpoint() # %s\n" % (' ' * indent, self.uid)
def highlight(self, view, rg):
"""colorize the breakpoint's region"""
scope = settings.get('highlight', 'invalid')
view.add_regions(self.rg_key, [rg], scope)
###################
# Helper routines #
###################
def is_python(view):
return view.match_selector(0, 'source.python')
def save_file(view):
save_on_toggle = settings.get('save_on_toggle', True)
if save_on_toggle and view.is_dirty() and view.file_name():
view.run_command('save')
def ln_from_region(view, rg): # line number from region
return view.rowcol(rg.end())[0]
def goto_position(view, pos): # move cursor to position
view.sel().clear()
view.sel().add(pos)
def calc_pdb_position(view):
"""
find and return injection spot for the pdb_block; None on failure
"""
size = view.size()
text = view.substr(sublime.Region(0, size))
lines = view.lines(sublime.Region(0, size))
# make a few tries to compile the AST
# if code contains errors strip at line before the error and retry
for i in range(5):
try:
# parse through import statements to find a sweet spot for the
# pdb_block injection, outside of any complex/multiline import
# constructs, preferrably after the last import statement
fst = imp = nxt = None
for node in ast.iter_child_nodes(ast.parse(text)):
tx = view.substr(lines[node.lineno - 1])
if type(node) in (ast.Import, ast.ImportFrom):
if not fst:
fst = node.lineno
imp = node.lineno
elif not fst:
fst = node.lineno
elif imp and not (tx.endswith('"""') or tx.endswith("'''")):
nxt = node.lineno
break
ln = nxt if nxt else imp if imp else fst
return view.text_point(ln - 1 if ln > 1 else ln, 0)
except (IndentationError, SyntaxError) as e:
debug('err in line %d %r' % (
e.lineno, view.substr(lines[e.lineno - 1])))
size = lines[e.lineno - 2].begin()
text = view.substr(sublime.Region(0, size))
lines = view.lines(sublime.Region(0, size))
def calc_indent(view, rg):
"""
calculate indentation for the inserted breakpoint statement
"""
ln = None
# clean up regions that are empty or comment lines
lines = view.lines(sublime.Region(0, view.size()))
for l in list(lines):
if l == rg: # don't remove the current line
ln = lines.index(l)
else:
line = view.substr(l).strip()
if not line or line.startswith('#'):
lines.remove(l)
elif ln is not None:
break # reached current and next line
# a couple of hacks to handle corner cases
if not ln:
ln = -1
if ln + 1 >= len(lines):
lines.append(lines[-1])
# calculate vertical distance to previous and next lines
prev_dist = lines[ln].begin() - lines[ln - 1].end()
next_dist = lines[ln + 1].begin() - lines[ln].end()
debug('distance p', prev_dist, 'n', next_dist)
if next_dist < 0:
next_dist = 0xff
curr_line = view.substr(lines[ln])
prev_line = view.substr(lines[ln - 1])
next_line = view.substr(lines[ln + 1])
# calculate indent of current, previous and next lines
_indent = lambda x: len(x) - len(x.lstrip())
curr_indent = _indent(curr_line)
prev_indent = _indent(prev_line)
next_indent = _indent(next_line)
debug('indent p', prev_indent, 'c', curr_indent, 'n', next_indent)
def _result(msg, indent):
debug(msg)
# check if previous or next line already contains a breakpoint
# at the same indent level
c1 = indent == prev_indent and bp_re.match(prev_line)
c2 = indent == next_indent and bp_re.match(next_line) and not curr_line
if not (c1 or c2):
return indent
# order of checks is critical!
if expr_re1.match(prev_line):
if prev_dist < next_dist:
return _result('re1-1', prev_indent + tab_size)
else:
return _result('re1-2', curr_indent)
if expr_re0.match(curr_line):
if prev_dist < next_dist:
return _result('re0-1', prev_indent)
else:
return _result('re0-2', curr_indent)
if expr_re2.match(next_line):
if prev_dist <= next_dist:
return _result('re2-1', curr_indent)
else:
return _result('re2-3', next_indent)
if expr_re1.match(curr_line):
return _result('re1-3', curr_indent + tab_size)
# go heuristic - choose the closest indent
if curr_line:
return _result('he0', curr_indent)
elif prev_dist <= next_dist:
return _result('he1-1', prev_indent)
else:
return _result('he1-2', next_indent)
def find_pdb_block(view):
"""return position of the pdb_block, or None"""
rg = view.find(pdb_block.strip(), 0, sublime.LITERAL)
if rg:
return rg.begin()
def find_breakpoint(view):
"""return position of the 1st breakpoint, or None"""
rg = view.find(bp_regex, 0)
if rg:
return rg.end()
def remove_pdb_block(edit, view):
pos = find_pdb_block(view)
rg = sublime.Region(pos, pos + len(pdb_block))
assert pdb_block in view.substr(rg), rg
view.erase(edit, rg)
def remove_breakpoint(edit, view, rg):
"""
find and remove the breakpoint, return True on success
"""
rg = view.full_line(rg)
lines = view.lines(sublime.Region(0, rg.end()))
ln = min(ln_from_region(view, rg), len(lines) - 1)
for line in (lines[ln], lines[ln - 1]): # search current and prev lines
bp = Breakpoint(view.substr(line))
if bp.uid:
view.erase(edit, view.full_line(line))
view.erase_regions(bp.rg_key)
return True
return False
def insert_pdb_block(edit, view):
"""
inject the pdb_block construct, return its position
"""
pos = calc_pdb_position(view)
if pos is not None:
view.insert(edit, pos, pdb_block)
return pos
def insert_breakpoint(edit, view, rg):
bp = Breakpoint()
rg_a = rg.begin()
indent = calc_indent(view, rg)
if indent is not None:
bp_rg_sz = view.insert(edit, rg_a, bp.format(indent))
color_rg = sublime.Region(rg_a, rg_a + bp_rg_sz)
bp.highlight(view, color_rg)
goto_position(view, rg_a + indent)
###############
# ST commands #
###############
class ToggleBreakpointCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
# don't handle non-Python and selected text
if not (is_python(view) and view.sel()[0].empty()):
return
# check/insert the pdb_block
pdb_pos = find_pdb_block(view)
if pdb_pos is None:
pdb_pos = insert_pdb_block(edit, view)
# remove/insert the breakpoint
rg = view.line(view.sel()[0])
if remove_breakpoint(edit, view, rg):
# if no more breakpoints remove pdb_block
if not find_breakpoint(view):
remove_pdb_block(edit, view)
else:
# inserting a new breakpoint below pdb_block
if pdb_pos and rg.begin() >= pdb_pos + len(pdb_block):
insert_breakpoint(edit, view, rg)
# if insertion didn't happen undo the pdb_block
elif not find_breakpoint(view) and find_pdb_block(view):
remove_pdb_block(edit, view)
save_file(view)
class GotoBreakpointCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
if not is_python(view):
return
bp_regions = view.find_all(bp_regex, 0)
items = [[] for __ in bp_regions]
lines = view.lines(sublime.Region(0, view.size()))
for i, rg in enumerate(bp_regions):
rg = view.full_line(rg)
ln = ln_from_region(view, rg)
# grab 2 next non-empty code lines
for j, l in enumerate(lines[ln - 1:]):
s = view.substr(l)
if not s.strip(): # skip empty lines
continue
if not j: # strip the 1st line
s = s.strip()
lnn = ln_from_region(view, l) + 1
items[i].append('%d: %s' % (lnn, s))
if len(items[i]) > 2:
break
def on_done(idx):
if idx > -1:
goto_position(view, bp_regions[idx].end())
view.show_at_center(bp_regions[idx])
if items:
view.window().show_quick_panel(items, on_done)
class ClearAllBreakpointsCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
if is_python(view):
for i in range(999): # put a hard limit, just in case
rg = find_breakpoint(view)
if not (rg and remove_breakpoint(edit, view, rg)):
break
if find_pdb_block(view):
remove_pdb_block(edit, view)
save_file(view)
##################
# Event listener #
##################
class PythonBreakpointEventListener(sublime_plugin.EventListener):
def on_load(self, view):
"""
on file load, scan it for breakpoints and highlight them
"""
if is_python(view) and find_pdb_block(view):
for rg in view.find_all(bp_regex, 0):
bp = Breakpoint(view.substr(rg))
bp.highlight(view, rg)