-
Notifications
You must be signed in to change notification settings - Fork 13
/
code_editor.py
1318 lines (1126 loc) · 44.1 KB
/
code_editor.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
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
import bpy
import gpu
import blf
from gpu_extras.batch import batch_for_shader
from bpy.types import Operator
from collections import defaultdict, deque
from itertools import repeat
bl_info = {
"name": "Code Editor",
"location": "Text Editor > Right Click Menu",
"version": (0, 2, 0),
"blender": (3, 2, 2),
"description": "Better editor for coding",
"author": "Jerryno, tintwotin, kaio",
"category": "Text Editor",
}
is_text = bpy.types.Text.__instancecheck__ # Faster than isinstance(x, bpy.types.Text)
sh_2d_vert = """
uniform mat4 ModelViewProjectionMatrix;
in vec2 pos;
void main() {
gl_Position = ModelViewProjectionMatrix * vec4(pos, 0.0, 1.0);
}
"""
sh_2d_frag = """
uniform vec4 color;
out vec4 final_color;
void main() {
final_color = color;
}
"""
sh_2d = gpu.types.GPUShader(sh_2d_vert, sh_2d_frag)
sh_2d_uniform_float = sh_2d.uniform_float
sh_2d_bind = sh_2d.bind
if bpy.app.version < (4, 0):
blf_size = blf.size
else:
def blf_size(font_id, font_size, dpi_unused):
blf.size(font_id, font_size)
# emulate list of integers with slicing
# capability. use with tracking indents
class DefaultInt(defaultdict):
__slots__ = ('_setitem', '_delitem', '_get')
def __init__(self):
sclass = super(__class__, self)
sclass.__init__()
self._setitem = sclass.__setitem__
self._delitem = sclass.__delitem__
self._get = sclass.__getitem__
def _parse_slice(self, obj):
start = obj.start or 0
stop = obj.stop or len(self) or start + 1
step = obj.step or 1
return range(start, stop, step)
def __delitem__(self, i):
if isinstance(i, slice):
for i in self._parse_slice(i):
del self[i]
elif i in self:
self._delitem(i)
def __missing__(self, i):
self._setitem(i, -1)
return self[i]
def __getitem__(self, i):
if isinstance(i, slice):
return [self._get(j) for j in self._parse_slice(i)]
return self._get(i)
class TextCache(dict):
def __missing__(self, key): # generate a blank cache
text = bpy.data.texts.get(key, self.ce.wrap_text)
self.purge_unused()
hashes = defaultdict(lambda: None)
def defaultlist(text=text):
return [[] for _ in repeat(None, len(text.lines))]
data = defaultdict(defaultlist)
indents = DefaultInt()
cache = self[key] = (hashes, # body hashes
data, # syntax data
[], # ????
indents) # indents data
return cache
def purge_unused(self):
for k in [k for k in self if k != 'ce' and k not in ce_manager]:
if k not in bpy.data.texts:
del self[k]
class WrapText:
__slots__ = ('ce', 'name', 'lines', 'cmax', 'hashes')
class WrapTextLine:
__slots__ = ('body', 'is_sub', 'oidx')
def __init__(self, body, oidx, is_sub=False):
self.body = body
self.is_sub = is_sub
self.oidx = oidx
def __init__(self, text, ce):
self.ce = ce
self.name = text.name
self.lines = []
self.cmax = ce.cmax
self.rebuild_lines()
def check_hash(self):
otext = bpy.data.texts.get(self.ce.text_name)
if not otext: # original text has been renamed or removed
return
hashes = self.hashes
lenl, lenh = len(otext.lines), len(hashes)
if lenl > lenh:
hashes.extend((0,) * (lenl - lenh))
elif lenh > lenl:
del hashes[lenl:]
elif self.ce.cmax != self.cmax:
self.cmax = self.ce.cmax
*self.hashes, = (0,) * lenl
# TODO should use a more elaborate check so
# TODO we don't have to rebuild every line after
for idx, (line, hash_val) in enumerate(zip(otext.lines, hashes)):
if hash(line.body) != hash_val:
return self.rebuild_lines(from_line=idx)
def rebuild_lines(self, from_line=0):
otext = bpy.data.texts.get(self.ce.text_name)
olines = otext.lines
self.hashes = [hash(l.body) for l in otext.lines]
wtl = self.WrapTextLine
cmax = self.ce.cmax
if cmax < 8:
cmax = 8
if not from_line: # complete wrap rebuild
self.lines = []
else: # partial wrap rebuild (from line)
for idx, line in enumerate(self.lines):
if line.oidx == from_line:
del self.lines[idx:]
break
append = self.lines.append
for idx, line in enumerate(olines[from_line:], from_line):
pos = start = 0
end = cmax
body = line.body
if len(body) < cmax:
append(wtl(body, idx))
continue
for c in body:
if pos - start >= cmax:
append(wtl(body[start:end], idx, is_sub=start > cmax))
start = end
end += cmax
elif c is " " or c is "-":
end = pos + 1
pos += 1
append(wtl(body[start:], idx, is_sub=True))
# maintain (public) caches and give out handles for editors
class CodeEditorManager(dict):
__slots__ = ('__dict__',)
tcache = TextCache()
editors = []
def __init__(self):
super(__class__, self).__init__()
self.__dict__ = self
# cached text is a defaultdict of lists,
# so a new one is created automatically
def get_cached(self, ce):
if ce.word_wrap:
# wrapped texts are unique per space, identify by the editor id
text = ce.wrap_text
name = ce.id
else:
text = bpy.data.texts.get(ce.text_name)
name = text.name
self.tcache.ce = ce
cache = (hsh, data, spec, ind) = self.tcache[name]
lenl = len(text.lines)
lenp = len(data[0])
if lenl > lenp: # if the length has changed, resize
for slot in data.values():
slot.extend([[] for _ in repeat(None, lenl - lenp)])
elif lenp > lenl:
del ind[lenl:]
for data in data.values():
del data[lenl + 1:]
pop = hsh.pop
for i in range(lenl, lenp):
pop(i, None)
return cache
def gcollect(self, context):
wm = context.window_manager
eds = {f"ce_{a.as_pointer()}" for w in wm.windows
for a in w.screen.areas if a.type == 'TEXT_EDITOR'}
for ed in (*self.keys(),):
if ed not in eds:
self.editors.remove(self[ed])
del self[ed]
def nuke(self):
self.tcache.clear()
self.editors.clear()
self.clear()
def get_ce(self, context):
handle_id = f"ce_{context.area.as_pointer()}"
handle = self.get(handle_id)
if not handle:
self.gcollect(context) # remove closed editors
self[handle_id] = handle = CodeEditorMain(context)
self.editors.append(self[handle_id])
return handle
ce_manager = CodeEditorManager()
get_ce = ce_manager.get_ce
def draw_lines_2d(seq, color):
batch = batch_for_shader(sh_2d, 'LINES', {'pos': seq})
sh_2d_bind()
sh_2d_uniform_float("color", [*color])
batch.draw(sh_2d)
def draw_quads_2d(seq, color):
qseq, = [(x1, y1, y2, x1, y2, x2) for (x1, y1, y2, x2) in (seq,)]
batch = batch_for_shader(sh_2d, 'TRIS', {'pos': qseq})
sh_2d_bind()
sh_2d_uniform_float("color", [*color])
batch.draw(sh_2d)
# source/blender/windowmanager/intern/wm_window.c$515
def get_widget_unit(context):
system = context.preferences.system
p = system.pixel_size
pd = p * system.dpi
return int((pd * 20 + 36) / 72 + (2 * (p - pd // 72)))
# find all multi-line string states
def get_ml_states(text):
ml_states = []
ranges = []
append = ml_states.append
pop = ml_states.pop
append2 = ranges.append
dbl, sgl = "\"\"\"", "\'\'\'"
for idx, line in enumerate(text.lines):
body = line.body
if "\"" in body or "\'" in body:
find = body.find
if dbl in body:
find = body.find
i = find(dbl, 0)
while i != -1:
if ml_states and ml_states[-1][2] == dbl:
append2(range(ml_states[0][0], idx))
pop()
else:
append((idx, i, dbl))
i = find(dbl, i + 1)
if sgl in body:
i = find(sgl, 0)
while i != -1:
if ml_states and ml_states[-1][2] == sgl:
append2(range(ml_states[0][0], idx))
pop()
else:
append((idx, i, sgl))
i = find(sgl, i + 1)
return ranges
class MinimapEngine:
__slots__ = ('ce')
numerics = {*'1234567890'}
specials = {'def ', 'class '}
numericsdot = {*'1234567890.'}
some_set = {'TAB', 'STRING', 'BUILTIN', 'SPECIAL'}
whitespace = {'\x0b', '\r', '\x0c', '\t', '\n', ' '}
some_set2 = {'COMMENT', 'PREPRO', 'STRING', 'NUMBER'}
builtins = {'return', 'break', 'continue', 'yield', 'with', 'is '
'while', 'for ', 'import ', 'from ', 'not ', 'elif ',
' else', 'None', 'True', 'False', 'and ', 'in ', 'if '}
def __init__(self, ce):
self.ce = ce
def close_block(self, idx, indent, blankl, spec, dspecial):
remove = spec.remove
val = idx - blankl
for entry in spec:
if entry[0] < idx and entry[1] >= indent:
dspecial[entry[0]].append((entry[1], entry[2], val))
remove(entry)
def highlight(self, tidx):
texts = bpy.data.texts
if not texts: # abort if requested during undo/redo
return
ce = self.ce
if ce.word_wrap:
ml_states = []
text = ce.wrap_text
is_wrap = True
else:
text = texts[tidx]
ml_states = get_ml_states(text)
is_wrap = False
olines = texts[tidx].lines
start, end = ce.mmvisl # visible portion of minimap
# get, or make a proxy version of the text
c_hash, c_data, special_temp, c_indents = ce_manager.get_cached(ce)
dspecial = c_data['special'] # special keywords (class, def)
dplain = c_data['plain'] # plain text
dnumbers = c_data['numbers'] # ints and floats
dstrings = c_data['strings'] # strings
dbuiltin = c_data['builtin'] # builtin
dcomments = c_data['comments'] # comments
dprepro = c_data['prepro'] # pre-processor (decorators)
dtabs = c_data['tabs'] # ?????
indents = c_indents # indentation levels
# syntax element structure
elem = [0, # line id
0, # element start position
0, # element end position
0] # special block end line
# this is used a lot for ending plain text segment
def close_plain(elem, cidx):
"""Ends non-highlighted text segment"""
if elem[1] < cidx:
elem[2] = cidx - 1
dplain[elem[0]].append(elem[1:3])
elem[1] = cidx
# this ends collapsible code block
close_block = self.close_block
# recognized tags definitions, only the most used
numerics = self.numerics
numericsdot = self.numericsdot
some_set = self.some_set
some_set2 = self.some_set2
ws = self.whitespace
blankl = idx = 0
# flags of syntax state machine
state = ""
timer = -1 # timer to skip characters and close segment at t=0
builtin_set = "rbcywfieNTFan"
builtins = self.builtins
specials = self.specials
special_temp.clear()
tab_width = ce.st.tab_width
def is_ml_state(idx):
for r in ml_states:
if idx in r:
return True
def look_back(idx):
prev = idx - 1
lines = text.lines
while prev > 0:
bod = lines[prev].body
blstrip = bod.lstrip()
lenbprev = len(bod)
indprev = (lenbprev - len(blstrip)) // tab_width
if indprev:
bstartsw = blstrip.startswith
if bstartsw("def"):
indprev += 1
elif bstartsw("return"):
indprev -= 1
return indprev
elif blstrip:
return 0
prev -= 1
return 0
for idx, line in enumerate(text.lines[start:end], start):
bod = line.body
hsh = hash(bod)
if hsh == c_hash[idx]: # use cached data instead
continue
c_hash[idx] = hsh
for i in (dspecial, dplain, dnumbers, # TODO wrap into a function
dstrings, dbuiltin, dcomments, dprepro):
i[idx].clear()
# XXX tentative hack
lenbstrip = len(bod.replace("#", " ").lstrip())
lenb = len(bod)
ind = (lenb - lenbstrip) // tab_width
if not lenbstrip: # track hanging indents by look-back
ind = look_back(idx)
indents[idx] = ind
elem[0] = idx # new line new element, carry string flag
elem[1] = 0
is_sub = is_wrap and line.is_sub
is_comment = is_sub and olines[line.oidx].body.startswith("#")
if state != 'STRING' or is_sub and is_comment:
if not is_sub:
state = ""
_is_ml_state = is_ml_state(idx)
if _is_ml_state:
state = "STRING"
else:
state = ""
indent = 0
block_close = has_non_ws = any(c not in ws for c in bod)
enumbod = [*enumerate(bod)]
# process each line and break into syntax blocks
for cidx, c in enumbod:
bodsub = bod[cidx:]
start_tab = " " in bodsub[:4]
if timer > 0:
timer -= 1
elif timer < 0:
if not state:
# tabs
if start_tab:
close_plain(elem, cidx)
state = 'TAB'
timer = 3
indent += 4
# built-in
if not state and c in builtin_set:
bodsub = bod[cidx:]
for b in builtins:
if b in bodsub[:len(b)]:
close_plain(elem, cidx)
state = 'BUILTIN'
timer = len(b) - 1
break
# special (def, class)
if not state and c in "dc":
bodsub = bod[cidx:]
for b in specials:
if b in bodsub[:len(b)]:
close_plain(elem, cidx)
state = 'SPECIAL'
timer = len(b) - 1
break
# numbers
elif c in numerics:
close_plain(elem, cidx)
state = 'NUMBER'
# "" string
elif c in '\"\'' and not is_sub:
if not _is_ml_state:
close_plain(elem, cidx)
state = 'STRING'
# comment
elif c == '#':
close_plain(elem, cidx)
state = 'COMMENT'
# close code blocks
if block_close:
for i, j in enumbod:
if i > 0 and j != " ":
close_block(idx, i // 4 * 4, blankl,
special_temp, dspecial)
break
# preprocessor
elif c == '@':
close_plain(elem, cidx)
state = 'PREPRO'
# close code blocks
if block_close:
close_block(idx, indent, blankl,
special_temp, dspecial)
break
elif state == 'NUMBER' and c not in numericsdot:
elem[2] = cidx
dnumbers[idx].append(elem[1:3])
elem[1] = cidx
state = ""
elif state == 'STRING':
if is_sub and is_comment:
state = ""
else:
if start_tab:
elem[1] = cidx + 4
indent += 4
# close special blocks
if state != 'TAB' and block_close:
block_close = False
close_block(idx, indent, blankl, special_temp, dspecial)
# write element when timer 0
if timer == 0:
elem[2] = cidx
if state in some_set:
if state == 'TAB':
dtabs[idx].append(elem[1:3])
if state == 'STRING':
dstrings[idx].append(elem[1:3])
elif state == 'BUILTIN':
dbuiltin[idx].append(elem[1:3])
elif state == 'SPECIAL':
special_temp.append(elem.copy())
# special_temp.append(elem[:])
elem[1] = cidx + 1
state = ""
timer = -1
# count empty lines
blankl = 0 if has_non_ws else blankl + 1
# handle line ends - aka when a syntax continues over
# multiple lines like multi-line strings etc.
if not state:
elem[2] = lenb
dplain[idx].append(elem[1:3])
elif state in some_set2:
elem[2] = lenb
elems = elem[1:3]
if state == 'COMMENT':
dcomments[idx].append(elems)
elif state == 'PREPRO':
dprepro[idx].append(elems)
elif state == 'STRING':
dstrings[idx].append(elems)
elif state == 'NUMBER':
dnumbers[idx].append(elems)
# close all remaining blocks
val = idx + 1 - blankl
for entry in special_temp:
dspecial[entry[0]].append([entry[1], entry[2], val])
# done
output = ce.segments
output[0]['elements'] = dplain
output[1]['elements'] = dstrings
output[2]['elements'] = dcomments
output[3]['elements'] = dnumbers
output[4]['elements'] = dbuiltin
output[5]['elements'] = dprepro
output[6]['elements'] = dspecial # XXX needs fixing
# output[7]['elements'] = dtabs
ce.indents = indents
ce.tag_redraw()
def get_cw(st):
cw = xoffs = 0
for idx, line in enumerate(st.text.lines):
if line.body:
loc = st.region_location_from_cursor
xoffs = loc(idx, 0)[0]
cw = loc(idx, 1)[0] - xoffs
break
if not cw:
xoffs = get_widget_unit(bpy.context) // 2
cw = round(blf.dimensions(1, "T")[0])
return cw, xoffs
# =====================================================
# OPENGL DRAWCALS
# =====================================================
def draw_callback_px(context):
"""Draws Code Editors Minimap and indentation marks"""
text = context.edit_text
if not text:
return
st = context.space_data
ce = get_ce(context)
word_wrap = ce.word_wrap = st.show_word_wrap
if ce.text_name != text.name: # refer by name to avoid invalid refs
ce.text_name = text.name
wu = get_widget_unit(context) # get the correct ui scale
wu2 = wu * 0.05
rw, rh = ce.region.width, ce.region.height
visl = st.visible_lines
lines = text.lines
lenl = len(lines)
lnrs = st.show_line_numbers and len(repr(lenl)) + 2
cw, xoffs = get_cw(st)
# Main text drawing x offset from area edge
_x = cw
if st.show_line_numbers:
_x += cw * lnrs
mcw = ce.mmcw * round(wu2, 1) # minimap char width
maxw = 120 * wu2
redge = ce.redge = 1 + int(int(rw - (0.2 * wu)) - (0.4 * wu))
# use different cache for wrapped. less performant, but still cached
if word_wrap:
ce.cmax = cmax = (rw - wu - _x) // cw
mmw = min((mcw * 0.8 * (redge // cw), maxw))
text, lines = ce.validate()
lenl = len(lines)
# do a new pass since max char width changed
if cmax != ce.cmax_prev:
ce.cmax_prev = cmax
return draw_callback_px(context)
else:
mmw = min((rw // 7, maxw))
if st.top > lenl: # clamp top to avoid going completely off-screen
st.top = lenl - (visl // 2)
if not ce.autow:
mmw = ce.mmw
ledge = ce.ledge = int(redge - mmw) if ce.show_minimap else redge
ce.prev_state = word_wrap
sttop = st.top
sttopvisl = sttop + visl
texts = bpy.data.texts
lent = len(texts)
lh = int((wu * st.font_size // 20) * 1.3) # line height
mlh = ce.mlh = ce.mlh_base * round(wu * 0.1, 1) # minimap line height
tabsize = ce.large_tabs and int(wu * 1.1) or int(wu * 0.8)
tabw = ce.tabw = ce.show_tabs and lent > 1 and tabsize or 0
lbound = ledge - tabw if ce.show_tabs and texts else ledge
slide = ce.slide = int(max(0, mlh * (lenl + rh / lh) - rh) * sttop / lenl)
mmy1 = rh - mlh * sttop + slide - 1
startrange = round((sttop - (rh - mmy1) // mlh))
endrange = round(startrange + (rh // mlh))
ce.opac = opac = min(max(0, (rw - ce.min_width) / 100.0), 1)
# rebuild minimap visual range
mmvisrange = range(*ce.mmvisl)
if startrange not in mmvisrange or endrange not in mmvisrange:
ce.mmvisl = startrange, endrange
# params are ready, get minimap symbols
ce.update_text()
# draw minimap background rectangle
x = ledge - tabw
color = (*ce.background, (1 - ce.bg_opacity) * opac)
gpu.state.blend_set("ALPHA")
draw_quads_2d(((x, rh), (redge, rh), (redge, 0), (x, 0)), color)
mmap_enabled = all((opac, ce.show_minimap))
# draw minimap shadow
gpu.state.line_width_set(wu2)
if mmap_enabled or tabw:
for idx, intensity in enumerate([.2, .1, .07, .05, .03, .02, .01]):
color = 0.0, 0.0, 0.0, intensity * opac
draw_lines_2d(((x - idx, 0), (x - idx, rh)), color)
# draw minimap/tab divider
if tabw:
color = 0.0, 0.0, 0.0, 0.2 * opac
draw_lines_2d(((ledge, 0), (ledge, rh)), color)
mmtop = int(slide / mlh)
mmbot = int((rh + slide) / mlh)
if mmap_enabled:
# draw minimap slider
alpha = 0.05 if ce.in_minimap else 0.03
color = 1.0, 1.0, 1.0, alpha * opac
color_frame = 1.0, 1.0, 1.0, alpha + 0.1
mmy2 = rh - mlh * sttopvisl + slide
x1, x2 = ledge + 1, redge - 1
y1, y2 = mmy1, mmy2
p1, p2, p3, p4 = (x1, y1), (x2, y1), (x2, y2), (x1, y2)
draw_quads_2d((p1, p2, p3, p4), color)
# draw slider frame
draw_lines_2d((p1, p2), color_frame)
draw_lines_2d((p2, p3), color_frame)
draw_lines_2d((p3, p4), color_frame)
draw_lines_2d((p4, p1), color_frame)
# draw minimap symbols
segments = ce.segments
mmxoffs = ledge + 4 # minimap x offset
gpu.state.line_width_set((mlh ** 1.02) - 2)
for seg in segments:
seq = deque()
seq_extend = seq.extend
color = seg['col'][:3] + (0.4 * opac,)
for idx, elem in enumerate(seg['elements'][mmtop:mmbot]):
if elem:
y = rh - (mlh * (idx + mmtop + 1) - slide)
for start, end, *_ in elem:
x1 = mmxoffs + (mcw * start)
if x1 > redge:
continue
x2 = x1 + (mcw * (end - start))
if x2 > redge:
x2 = redge
seq_extend(((x1, y), (x2, y)))
draw_lines_2d(seq, color)
# draw minimap indent guides
seq1, seq2 = deque(), deque()
seq1_ext, seq2_ext = seq1.extend, seq2.extend
plain_col = ce.segments[0]['col'][:3]
color1 = (*plain_col, 0.1)
color2 = (*plain_col, 0.3 * ce.indent_trans * opac)
tab_width = st.tab_width
indent = cw * tab_width
show_indents = ce.show_indents
for idx, levels in enumerate(ce.indents[mmtop:mmbot], mmtop):
if levels:
for level in range(levels):
if mmap_enabled:
x = ledge + 4 + (mcw * 4 * level)
if x < redge:
ymax = rh + slide - mlh * idx
seq1_ext(((x, ymax - mlh), (x, ymax)))
# draw editor indent guides
if show_indents:
ymax = rh - lh * (1 + idx - sttop) + lh
ymin = ymax - lh
gpu.state.line_width_set(wu2)
if -lh < ymin < rh:
x = xoffs + indent * level
if x >= _x:
seq2_ext(((x, ymin), (x, ymax)))
continue
draw_lines_2d(seq1, color1)
draw_lines_2d(seq2, color2)
# draw tabs
if tabw:
tabh = rh / lent
fsize = int(tabw * 0.75)
blf_size(0, fsize, 72)
blf.enable(0, blf.ROTATION)
blf.rotation(0, 1.5707963267948966)
x = int(ledge - tabw / 4)
yoffs = rh - (tabh / 2)
maxlenn = int(((tabh * 1.2) / (fsize * 0.7)) - 2)
# text names
tnames = [t.name for t in texts]
for idx, name in enumerate(tnames):
lenn = len(name)
tlabel = lenn <= maxlenn and name or name[:maxlenn] + '..'
y = round(yoffs - (tabh * idx) - blf.dimensions(0, tlabel)[0] // 2)
blf.color(0, *plain_col, (name != text.name and .4 or .7) * opac)
blf.position(0, x, y, 0)
blf.draw(0, tlabel)
gpu.state.blend_set("ALPHA")
gpu.state.line_width_set(wu2)
# draw tab hover rects
if opac:
x, y = ledge - tabw, rh
hover_text = ce.hover_text
for name in tnames:
y2 = y - tabh
color2 = 0, 0, 0, .2 * opac
# tab selection
seq = (x, y), (ledge, y), (ledge, y2), (x, y - tabh)
if hover_text == name:
draw_quads_2d(seq, (1, 1, 1, 0.1))
# tab active
elif name == text.name:
ce.active_tab_ymax = y
draw_quads_2d(seq, color1)
y -= tabh
draw_lines_2d(((x, y), (ledge, y)), color2)
# draw whitespace and/or tab characters
if ce.show_whitespace:
st_left = (_x // cw) - (xoffs // cw)
cend = (lbound - _x) // cw
wslines = []
append = wslines.append
join = "".join
for l in lines[sttop:sttopvisl]:
ti = 0
wsbod = []
append2 = wsbod.append
for ci, c in enumerate(l.body):
if ci < st_left:
append2(" ")
continue
if c is "\t":
tb = tab_width - ((ci + ti) % tab_width) - 1
append2(" " * tb + "→")
ti += tb
elif c is " ":
append2("·")
else:
append2(" ")
append(join(wsbod))
y = rh - (lh * 0.8)
blf.color(1, *plain_col, 1 * ce.ws_alpha)
for idx, line in enumerate(wslines):
if line:
blf.position(1, _x, y, 0)
blf.draw(1, line[st_left:cend])
y -= lh
# restore opengl defaults
blf.rotation(0, 0)
blf.disable(0, blf.ROTATION)
class CodeEditorBase:
bl_options = {'INTERNAL'}
@classmethod
def poll(cls, context):
return is_text(context.edit_text)
class CE_OT_scroll(CodeEditorBase, Operator):
bl_idname = 'ce.scroll'
bl_label = "Scroll"
bl_options = {'INTERNAL', 'BLOCKING'}
def modal(self, context, event):
if event.type == 'LEFTMOUSE' and event.value == 'RELEASE':
context.window_manager.event_timer_remove(self.timer)
return {'FINISHED'}
elif event.type == 'TIMER':
return self.scroll_timer(context, event)
return {'RUNNING_MODAL'}
def invoke(self, context, event):
st = context.space_data
self.ce = ce = get_ce(context)
self.lenl = len(ce.word_wrap and ce.wrap_text.lines or st.text.lines)
context.window.cursor_set('HAND')
wm = context.window_manager
wm.modal_handler_add(self)
self.timer = wm.event_timer_add(.0075, window=context.window)
return self.scroll_timer(context, event)
def scroll_timer(self, context, event):
st = context.space_data
top = st.top
vishalf = st.visible_lines // 2
mry = event.mouse_region_y
mlh = self.ce.mlh
lenl = self.lenl
center = context.region.height - mlh * (top + vishalf) # box center
nlines = round(0.3 * (center + self.ce.slide - mry) / mlh)
if nlines > 0 and top + nlines > lenl - vishalf:
val = lenl - vishalf
else:
val = top + round(((30 + (lenl / mlh)) / 60) * nlines)
if val != st.top and not (val < 0 and not st.top):
st.top = val
return {'RUNNING_MODAL'}
# hijack clicks inside tab zones and minimap, otherwise pass through
class CE_OT_cursor_set(CodeEditorBase, Operator):
bl_idname = "ce.cursor_set"
bl_label = "Set Cursor"
options = {'INTERNAL', 'BLOCKING'}
def modal(self, context, event):
if event.value == 'RELEASE':
return {'CANCELLED'}
return {'RUNNING_MODAL'}
def invoke(self, context, event):
ce = get_ce(context)
if ce:
if ce.in_minimap:
return bpy.ops.ce.scroll('INVOKE_DEFAULT')
elif ce.hover_text and ce.hover_text in bpy.data.texts:
context.space_data.text = bpy.data.texts.get(ce.hover_text)
context.window_manager.modal_handler_add(self)
return {'RUNNING_MODAL'}
return {'PASS_THROUGH'}
# handle mouse events in text editor to support hover and scroll
class CE_OT_mouse_move(CodeEditorBase, Operator):
bl_options = {'INTERNAL'}
bl_idname = "ce.mouse_move"
bl_label = "Mouse Move"
def invoke(self, context, event):
if is_text(context.edit_text):
get_ce(context).update(context, event.mouse_x, event.mouse_y)
return {'PASS_THROUGH'}
# main class for storing runtime draw props
class CodeEditorMain:
__slots__ = ('__dict__',)
def __init__(self, context):
self.id = f"ce_{context.area.as_pointer()}"
index = f"{context.screen.areas[:].index(context.area)}"
if index not in context.screen.code_editors:
context.screen.code_editors.add().name = index
self.props = context.screen.code_editors[index]
p = context.preferences
self.ap = ap = p.addons[__name__].preferences
self.text = text = context.edit_text
self.bg_opacity = ap.opacity
self.mmw = ap.minimap_width
self.min_width = ap.window_min_width
self.mmcw = ap.character_width
self.mlh_base = self.mlh = ap.line_height
self.indent_trans = ap.indent_trans
self.ws_alpha = ap.ws_alpha
self.large_tabs = ap.large_tabs
self.tabs_right = ap.tabs_right
self.show_whitespace = self.props.show_whitespace
self.show_minimap = self.props.show_minimap
self.show_indents = self.props.show_indents
self.show_tabs = self.props.show_tabs
self.region = context.area.regions[-1]
self.window = context.window