forked from sublime-emacs/sublemacspro
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjove.py
2112 lines (1787 loc) · 71.6 KB
/
jove.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
import re, sys
import functools as fu
import sublime, sublime_plugin
from copy import copy
# Handling the different imports in Sublime
if sublime.version() < '3000':
# we are on ST2 and Python 2.X
_ST3 = False
import paragraph
import sbp_layout as ll
else:
_ST3 = True
import Default.paragraph as paragraph
from . import sbp_layout as ll
JOVE_STATUS = "jove"
default_sbp_sexpr_separators = "./\\()\"'-:,.;<>~!@#$%^&*|+=[]{}`~?";
default_sbp_word_separators = "./\\()\"'-_:,.;<>~!@#$%^&*|+=[]{}`~?";
# ensure_visible commands
ensure_visible_cmds = set(['move', 'move_to'])
# initialized at the end of this file after all commands are defined
kill_cmds = set()
# repeatable commands
repeatable_cmds = set(['move', 'left_delete', 'right_delete'])
#
# Classic emacs kill ring.
#
class KillRing:
KILL_RING_SIZE = 64
def __init__(self):
self.buffers = [None] * self.KILL_RING_SIZE
self.index = 0
#
# Add some text to the kill ring. 'forward' indicates whether the editing command that produced
# this data was in the forward or reverse direction. It only matters if 'join' is true, because
# it tells us how to add this data to the most recent kill ring entry rather than creating a new
# entry.
#
def add(self, text, forward, join):
if len(text) == 0:
return
buffers = self.buffers
index = self.index
if not join:
index += 1
if index >= len(buffers):
index = 0
self.index = index
buffers[index] = text
else:
if buffers[index] is None:
buffers[index] = text
elif forward:
buffers[index] = buffers[index] + text
else:
buffers[index] = text + buffers[index]
sublime.set_clipboard(buffers[index])
#
# Returns the current entry in the kill ring. If pop is non-zero, we move backwards or forwards
# once in the kill ring and return that data instead.
#
def get_current(self, pop):
buffers = self.buffers
index = self.index
if pop == 0:
clipboard = sublime.get_clipboard()
val = buffers[index]
if val != clipboard and clipboard:
# we switched to another app and cut or copied something there, so add that to our
# kill ring
self.add(clipboard, True, False)
val = clipboard
else:
incr = self.KILL_RING_SIZE - 1 if pop == 1 else 1
index = (index + incr) % self.KILL_RING_SIZE
while buffers[index] is None and index != self.index:
index = (incr + index) % self.KILL_RING_SIZE
self.index = index
val = buffers[index]
sublime.set_clipboard(val)
return val
# kill ring shared across all buffers
kill_ring = KillRing()
#
# Classic emacs mark ring. Each entry in the ring is implemented with a named view region.
#
class MarkRing:
MARK_RING_SIZE = 16
def __init__(self, view):
self.view = view
self.index = 0
# in case any left over from before
self.view.erase_regions("jove_mark")
for i in range(self.MARK_RING_SIZE):
self.view.erase_regions(self.get_key(i))
def get_key(self, index):
return "jove_mark:" + str(index)
#
# Get the current mark.
#
def get(self):
key = self.get_key(self.index)
r = self.view.get_regions(key)
if r:
return r[0].a
def clear(self):
self.view.erase_regions("jove_mark")
def has_visible_mark(self):
return self.view.get_regions("jove_mark") != None and len(self.view.get_regions("jove_mark")) > 0
#
# Update the display to show the current mark.
#
def display(self):
# display the mark's dot
mark = self.get()
if mark is not None:
mark = sublime.Region(mark, mark)
self.view.add_regions("jove_mark", [mark], "mark", "dot", sublime.HIDDEN)
#
# Set the mark to pos. If index is supplied we overwrite that mark, otherwise we push to the
# next location.
#
def set(self, pos, same_index=False):
if self.get() == pos:
# don't set another mark in the same place
return
if not same_index:
self.index = (self.index + 1) % self.MARK_RING_SIZE
self.view.add_regions(self.get_key(self.index), [sublime.Region(pos, pos)], "mark", "", sublime.HIDDEN)
self.display()
#
# Exchange the current mark with the specified pos, and return the current mark.
#
def exchange(self, pos):
val = self.get()
if val is not None:
self.set(pos, False)
return val
#
# Pops the current mark from the ring and returns it. The caller sets point to that value. The
# new mark is the previous mark on the ring.
#
def pop(self):
val = self.get()
# find a non-None mark in the ring
start = self.index
while True:
self.index -= 1
if self.index < 0:
self.index = self.MARK_RING_SIZE - 1
if self.get() is not None or self.index == start:
break
self.display()
return val
isearch_info = dict()
def isearch_info_for(view):
if isinstance(view, sublime.Window):
window = view
else:
window = view.window()
if window:
return isearch_info.get(window.id(), None)
return None
def set_isearch_info_for(view, info):
window = view.window()
isearch_info[window.id()] = info
return info
def clear_isearch_info_for(view):
window = view.window()
del(isearch_info[window.id()])
#
# We store state about each view.
#
class ViewState():
# per view state
view_state_dict = dict()
# currently active view
current = None
def __init__(self, view):
self.view = view
self.active_mark = False
# a mark ring per view (should be per buffer)
self.mark_ring = MarkRing(view)
self.reset()
@classmethod
def on_view_closed(cls, view):
if view.id() in cls.view_state_dict:
del(cls.view_state_dict[view.id()])
@classmethod
def get(cls, view):
# make sure current is set to this view
if ViewState.current is None or ViewState.current.view != view:
state = cls.view_state_dict.get(view.id(), None)
if state is None:
state = ViewState(view)
cls.view_state_dict[view.id()] = state
state.view = view
ViewState.current = state
return ViewState.current
def reset(self):
self.this_cmd = None
self.last_cmd = None
self.argument_supplied = False
self.argument_value = 0
self.argument_negative = False
self.drag_count = 0
self.entered = 0
#
# Get the argument count and reset it for the next command (unless peek is True).
#
def get_count(self, peek=False):
if self.argument_supplied:
count = self.argument_value
if self.argument_negative:
if count == 0:
count = -1
else:
count = -count
if not peek:
self.argument_negative = False
if not peek:
self.argument_supplied = False
else:
count = 1
return count
def last_was_kill_cmd(self):
return self.last_cmd in kill_cmds
class ViewWatcher(sublime_plugin.EventListener):
def __init__(self, *args, **kwargs):
super(ViewWatcher, self).__init__(*args, **kwargs)
self.pending_dedups = 0
def on_close(self, view):
ViewState.on_view_closed(view)
def on_modified(self, view):
CmdUtil(view).toggle_active_mark_mode(False)
def on_activated_async(self, view):
info = isearch_info_for(view)
if info and not view.settings().get("is_widget"):
# stop the search if we activated a new view in this window
info.done()
def on_query_context(self, view, key, operator, operand, match_all):
if key == "i_search_active":
return isearch_info_for(view) is not None
if key == "sbp_has_visible_mark":
return CmdUtil(view).state.mark_ring.has_visible_mark() == operand
def on_post_save(self, view):
# Schedule a dedup, but do not do it NOW because it seems to cause a crash if, say, we're
# saving all the buffers right now. So we schedule it for the future.
self.pending_dedups += 1
def doit():
self.pending_dedups -= 1
if self.pending_dedups == 0:
dedup_views(sublime.active_window())
sublime.set_timeout(doit, 50)
class CmdWatcher(sublime_plugin.EventListener):
def __init__(self, *args, **kwargs):
super(CmdWatcher, self).__init__(*args, **kwargs)
def on_anything(self, view):
view.erase_status(JOVE_STATUS)
def on_window_command(self, window, cmd, args):
# Some window commands take us to new view. Here's where we abort the isearch if that happens.
info = isearch_info_for(window)
def check():
if info is not None and window.active_view() != info.view:
info.done()
if info is not None:
sublime.set_timeout(check, 0)
#
# Override some commands to execute them N times if the numberic argument is supplied.
#
def on_text_command(self, view, cmd, args):
if isearch_info_for(view) is not None:
if cmd not in ('sbp_inc_search', 'sbp_inc_search_escape'):
return ('sbp_inc_search_escape', {'next_cmd': cmd, 'next_args': args})
return
vs = ViewState.get(view)
self.on_anything(view)
if args is None:
args = {}
# first keep track of this_cmd and last_cmd (if command starts with "sbp_" it's handled
# elsewhere)
if not cmd.startswith("sbp_"):
vs.this_cmd = cmd
#
# Process events that create a selection. The hard part is making it work with the emacs region.
#
if cmd == 'drag_select':
info = isearch_info_for(view)
if info:
info.done()
# Set drag_count to 0 when drag_select command occurs. BUT, if the 'by' parameter is
# present, that means a double or triple click occurred. When that happens we have a
# selection we want to start using, so we set drag_count to 2. 2 is the number of
# drag_counts we need in the normal course of events before we turn on the active mark
# mode.
vs.drag_count = 2 if 'by' in args else 0
if cmd in ('move', 'move_to') and vs.active_mark and not args.get('extend', False):
args['extend'] = True
return (cmd, args)
# now check for numeric argument and rewrite some commands as necessary
if not vs.argument_supplied:
return None
if cmd in repeatable_cmds:
count = vs.get_count()
args.update({
'cmd': cmd,
'_times': abs(count),
})
if count < 0 and 'forward' in args:
args['forward'] = not args['forward']
return ("sbp_do_times", args)
elif cmd == 'scroll_lines':
args['amount'] *= vs.get_count()
return (cmd, args)
#
# Post command processing: deal with active mark and resetting the numeric argument.
#
def on_post_text_command(self, view, cmd, args):
vs = ViewState.get(view)
cm = CmdUtil(view)
if vs.active_mark and vs.this_cmd != 'drag_select' and vs.last_cmd == 'drag_select':
# if we just finished a mouse drag, make sure active mark mode is off
cm.toggle_active_mark_mode(False)
# reset numeric argument (if command starts with "sbp_" this is handled elsewhere)
if not cmd.startswith("sbp_"):
vs.argument_value = 0
vs.argument_supplied = False
vs.last_cmd = cmd
if vs.active_mark:
if len(view.sel()) > 1:
# allow the awesomeness of multiple cursors to be used: the selection will disappear
# after the next command
vs.active_mark = False
else:
cm.set_selection(cm.get_mark(), cm.get_point())
if cmd in ensure_visible_cmds and cm.just_one_point():
cm.ensure_visible(cm.get_point())
#
# Process the selection if it was created from a drag_select (mouse dragging) command.
#
def on_selection_modified(self, view):
vs = ViewState.get(view)
selection = view.sel()
if len(selection) == 1 and vs.this_cmd == 'drag_select':
cm = CmdUtil(view, vs);
if vs.drag_count == 2:
# second event - enable active mark
region = view.sel()[0]
mark = region.a
cm.set_mark(mark, and_selection=False)
cm.toggle_active_mark_mode(True)
elif vs.drag_count == 0:
cm.toggle_active_mark_mode(False)
vs.drag_count += 1
#
# At a minimum this is called when bytes are inserted into the buffer.
#
def on_modified(self, view):
ViewState.get(view).this_cmd = None
self.on_anything(view)
class WindowCmdWatcher(sublime_plugin.EventListener):
def __init__(self, *args, **kwargs):
super(WindowCmdWatcher, self).__init__(*args, **kwargs)
def on_window_command(self, window, cmd, args):
# REMIND - JP: Why is this code here? Can't this be done in the SbpPaneCmd class?
# Check the move state of the Panes and make sure we stop recursion
if cmd == "sbp_pane_cmd" and args and args['cmd'] == 'move' and 'next_pane' not in args:
lm = ll.LayoutManager(window.layout())
if args["direction"] == 'next':
pos = lm.next(window.active_group())
else:
pos = lm.next(window.active_group(), -1)
args["next_pane"] = pos
return cmd, args
#
# A helper class which provides a bunch of useful functionality on a view
#
class CmdUtil:
def __init__(self, view, state=None, edit=None):
self.view = view
if state is None:
state = ViewState.get(self.view)
self.state = state
self.edit = edit
#
# Sets the status text on the bottom of the window.
#
def set_status(self, msg):
self.view.set_status(JOVE_STATUS, msg)
#
# Returns point. Point is where the cursor is in the possibly extended region. If there are multiple cursors it
# uses the first one in the list.
#
def get_point(self):
sel = self.view.sel()
if len(sel) > 0:
return sel[0].b
return -1
#
# This no-op ensures the next/prev line target column is reset to the new locations.
#
def reset_target_column(self):
selection = self.view.sel()
if len(selection) == 1 and selection[0].empty() and selection[0].b < self.view.size():
self.run_command("move", {"by": "characters", "forward": True})
self.run_command("move", {"by": "characters", "forward": False})
#
# Returns the mark position.
#
def get_mark(self):
mark = self.view.get_regions("jove_mark")
if mark:
mark = mark[0]
return mark.a
#
# Get the region between mark and point.
#
def get_region(self):
selection = self.view.sel()
if len(selection) != 1:
# Oops - this error message does not belong here!
self.set_status("Operation not supported with multiple cursors")
return
selection = selection[0]
if selection.size() > 0:
return selection
mark = self.get_mark()
if mark is not None:
point = self.get_point()
return sublime.Region(mark, self.get_point())
#
# Save a copy of the current region in the named mark. This mark will be robust in the face of
# changes to the buffer.
#
def save_region(self, name):
r = self.get_region()
if r:
self.view.add_regions(name, [r], "mark", "", sublime.HIDDEN)
return r
#
# Restore the current region to the named saved mark.
#
def restore_region(self, name):
r = self.view.get_regions(name)
if r:
r = r[0]
self.set_mark(r.a, False, False)
self.set_selection(r.b, r.b)
self.view.erase_regions(name)
return r
#
# Iterator on all the lines in the specified sublime Region.
#
def for_each_line(self, region):
view = self.view
pos = region.begin()
limit = region.end()
while pos < limit:
line = view.line(pos)
yield line
pos = line.end() + 1
#
# Returns true if all the text between a and b is blank.
#
def is_blank(self, a, b):
text = self.view.substr(sublime.Region(a, b))
return re.match(r'[ \t]*$', text) is not None
#
# Returns the current indent of the line containing the specified POS and the column of POS.
#
def get_line_indent(self, pos):
data,col,region = self.get_line_info(pos)
m = re.match(r'[ \t]*', data)
return (len(m.group(0)), col)
#
# Sets the buffers mark to the specified pos (or the current position in the view).
#
def set_mark(self, pos=None, update_status=True, and_selection=True):
view = self.view
mark_ring = self.state.mark_ring
if pos is None:
pos = self.get_point()
# update the mark ring
mark_ring.set(pos)
if and_selection:
self.set_selection(pos, pos)
if update_status:
self.set_status("Mark Saved")
#
# Enabling active mark means highlight the current emacs region.
#
def toggle_active_mark_mode(self, value=None):
if value is not None and self.state.active_mark == value:
return
self.state.active_mark = value if value is not None else (not self.state.active_mark)
point = self.get_point()
if self.state.active_mark:
mark = self.get_mark()
self.set_selection(mark, point)
self.state.active_mark = True
else:
self.set_selection(point, point)
def swap_point_and_mark(self):
view = self.view
mark_ring = self.state.mark_ring
mark = mark_ring.exchange(self.get_point())
if mark is not None:
self.goto_position(mark)
else:
self.set_status("No mark in this buffer")
def set_selection(self, a=None, b=None):
if a is None:
a = self.get_point()
if b is None:
b = a
selection = self.view.sel()
selection.clear()
r = sublime.Region(a, b)
selection.add(r)
def get_line_info(self, point):
view = self.view
region = view.line(point)
data = view.substr(region)
row,col = view.rowcol(point)
return (data, col, region)
def run_window_command(self, cmd, args):
self.view.window().run_command(cmd, args)
def has_prefix_arg(self):
return self.state.argument_supplied
def just_one_point(self):
return len(self.view.sel()) == 1
def get_count(self, peek=False):
return self.state.get_count(peek)
#
# This provides a way to run a function on all the cursors, one after another. This maintains
# all the cursors and then calls the function with one cursor at a time, with the view's
# selection state set to just that one cursor. So any calls to run_command within the function
# will operate on only that one cursor.
#
# The called function is supposed to return a new cursor position or None, in which case value
# is taken from the view itself.
#
# REMIND: This isn't how it currently works!
#
# After the function is run on all the cursors, the view's multi-cursor state is restored with
# new values for the cursor.
#
def for_each_cursor(self, function, *args, **kwargs):
view = self.view
selection = view.sel()
# copy cursors into proper regions which sublime will manage while we potentially edit the
# buffer and cause things to move around
key = "tmp_cursors"
cursors = [c for c in selection]
view.add_regions(key, cursors, "tmp", "", sublime.HIDDEN)
# run the command passing in each cursor and collecting the returned cursor
for i in range(len(cursors)):
selection.clear()
regions = view.get_regions(key)
if i >= len(regions):
# we've deleted some cursors along the way - we're done
break
cursor = regions[i]
selection.add(cursor)
cursor = function(cursor, *args, **kwargs)
if cursor is not None:
# update the cursor in its slot
regions[i] = cursor
view.add_regions(key, regions, "tmp", "", sublime.HIDDEN)
# restore the cursors
selection.clear()
for r in view.get_regions(key):
selection.add(r)
view.erase_regions(key)
def goto_line(self, line):
if line >= 0:
view = self.view
point = view.text_point(line - 1, 0)
self.goto_position(point, set_mark=True)
def goto_position(self, pos, set_mark=False):
if set_mark and self.get_point() != pos:
self.set_mark()
self.view.sel().clear()
self.view.sel().add(sublime.Region(pos, pos))
self.ensure_visible(pos)
def is_visible(self, pos):
visible = self.view.visible_region()
return visible.contains(pos)
def ensure_visible(self, point, force=False):
if force or not self.is_visible(point):
self.view.show_at_center(point)
def is_word_char(self, pos, forward, separators):
if not forward:
if pos == 0:
return False
pos -= 1
char = self.view.substr(pos)
return not (char in " \t\r\n" or char in separators)
#
# Goes to the other end of the scope at the specified position. The specified position should be
# around brackets or quotes.
#
def to_other_end(self, point, direction):
brac = "([{"
kets = ")]}"
view = self.view
scope_name = view.scope_name(point)
if scope_name.find("comment") >= 0:
return None
ch = view.substr(point)
if direction > 0 and view.substr(point) in brac:
return self.run_command("move_to", {"to": "brackets"}, point=point)
elif direction < 0 and view.substr(point - 1) in kets:
# this can be tricky due to inconsistencies with sublime bracket matching
# we need to handle "))" and "()[0]" when between the ) and [
if point < view.size() and view.substr(point) in brac:
# go inside the bracket (point - 1), then to the inside of the match, then back one more
return self.run_command("move_to", {"to": "brackets"}, point=point - 1) - 1
else:
return self.run_command("move_to", {"to": "brackets"}, point=point)
# otherwise it's a string
start = point + direction
self.run_command("expand_selection", {"to": "scope"}, point=start)
r = view.sel()[0]
return r.end() if direction > 0 else r.begin()
#
# Run the specified command and args in the current view. If point is specified set point in the
# view before running the command. Returns the resulting point.
#
def run_command(self, cmd, args, point=None):
view = self.view
if point is not None:
view.sel().clear()
view.sel().add(sublime.Region(point, point))
view.run_command(cmd, args)
return self.get_point()
#
# The baseclass for JOVE/SBP commands. This sets up state, creates a helper, processes the universal
# argument, and then calls the run_cmd method, which subclasses should override.
#
class SbpTextCommand(sublime_plugin.TextCommand):
should_reset_target_column = False
is_kill_cmd = False
is_ensure_visible_cmd = False
unregistered = False
def run(self, edit, **kwargs):
# get our view state
vs = ViewState.get(self.view)
# first keep track of this_cmd and last_cmd but only if we're not called recursively
cmd = self.jove_cmd_name
if vs.entered == 0 and (cmd != 'sbp_universal_argument' or self.unregistered):
vs.this_cmd = cmd
vs.entered += 1
util = CmdUtil(self.view, state=vs, edit=edit)
try:
self.run_cmd(util, **kwargs)
finally:
vs.entered -= 1
if vs.entered == 0 and (cmd != 'sbp_universal_argument' or self.unregistered):
vs.last_cmd = vs.this_cmd
vs.argument_value = 0
vs.argument_supplied = False
# this no-op ensures the next/prev line target column is reset to the new locations
if self.should_reset_target_column:
util.reset_target_column()
class SbpWindowCommand(sublime_plugin.WindowCommand):
def run(self, **kwargs):
self.util = CmdUtil(self.window.active_view(), state=ViewState.get(self.window.active_view()))
self.run_cmd(self.util, **kwargs)
#
# Calls run command a specified number of times.
#
class SbpDoTimesCommand(SbpTextCommand):
def run_cmd(self, util, cmd, _times, **args):
view = self.view
visible = view.visible_region()
for i in range(_times):
view.run_command(cmd, args)
point = util.get_point()
if not visible.contains(point):
util.ensure_visible(point, True)
class SbpShowScopeCommand(SbpTextCommand):
def run_cmd(self, util, direction=1):
point = util.get_point()
name = self.view.scope_name(point)
region = self.view.extract_scope(point)
status = "%d bytes: %s" % (region.size(), name)
print(status)
self.view.set_status(JOVE_STATUS, status)
#
# Advance to the beginning (or end if going backward) word unless already positioned at a word
# character. This can be used as setup for commands like upper/lower/capitalize words. This ignores
# the argument count.
#
class SbpMoveWordCommand(SbpTextCommand):
should_reset_target_column = True
is_ensure_visible_cmd = True
def find_by_class_fallback(self, view, point, forward, classes, seperators):
if forward:
delta = 1
end_position = self.view.size()
if point > end_position:
point = end_position
else:
delta = -1
end_position = 0
if point < end_position:
point = end_position
while point != end_position:
if view.classify(point) & classes != 0:
return point
point += delta
return point
def find_by_class_native(self, view, point, forward, classes, separators):
return view.find_by_class(point, forward, classes, separators)
def call_find_by_class(self, view, point, forward, classes, separators):
'''
This is a small wrapper that maps to the right find_by_class call
depending on the version of ST installed
'''
if _ST3:
return self.find_by_class_native(view, point, forward, classes, separators)
else:
return self.find_by_class_fallback(view, point, forward, classes, separators)
def run_cmd(self, util, direction=1):
view = self.view
settings = view.settings()
separators = settings.get("sbp_word_separators", default_sbp_word_separators)
# determine the direction
count = util.get_count() * direction
forward = count > 0
count = abs(count)
def move_word0(cursor, first=False, **kwargs):
point = cursor.b
if forward:
if not first or not util.is_word_char(point, True, separators):
point = self.call_find_by_class(view, point, True, sublime.CLASS_WORD_START, separators)
point = self.call_find_by_class(view, point, True, sublime.CLASS_WORD_END, separators)
else:
if not first or not util.is_word_char(point, False, separators):
point = self.call_find_by_class(view, point, False, sublime.CLASS_WORD_END, separators)
point = self.call_find_by_class(view, point, False, sublime.CLASS_WORD_START, separators)
return sublime.Region(point, point)
for c in range(count):
util.for_each_cursor(move_word0, first=(c == 0))
#
# Advance to the beginning (or end if going backward) word unless already positioned at a word
# character. This can be used as setup for commands like upper/lower/capitalize words. This ignores
# the argument count.
#
class SbpToWordCommand(SbpTextCommand):
should_reset_target_column = True
def run_cmd(self, util, direction=1):
view = self.view
settings = view.settings()
separators = settings.get("sbp_word_separators", default_sbp_word_separators)
forward = direction > 0
def to_word(cursor):
point = cursor.b
if forward:
if not util.is_word_char(point, True, separators):
point = view.find_by_class(point, True, sublime.CLASS_WORD_START, separators)
else:
if not util.is_word_char(point, False, separators):
point = view.find_by_class(point, False, sublime.CLASS_WORD_END, separators)
return sublime.Region(point, point)
util.for_each_cursor(to_word)
class SbpCaseRegion(SbpTextCommand):
def run_cmd(self, util, mode):
region = util.get_region()
text = util.view.substr(region)
if mode == "upper":
text = text.upper()
elif mode == "lower":
text = text.lower()
else:
util.set_status("Unknown Mode")
return
util.view.replace(util.edit, region, text)
class SbpCaseWordCommand(SbpTextCommand):
should_reset_target_column = True
def run_cmd(self, util, mode, direction=1):
count = util.get_count() * direction
direction = -1 if count < 0 else 1
count = abs(count)
args = {"direction": direction}
def case_word(cursor):
if direction < 0:
# modify the N words before point by going back N words first
orig_point = cursor.a
saved = util.save_region("tmp")
for i in range(count):
util.run_command("sbp_move_word", args)
args['direction'] = -args['direction']
for i in range(count):
# go to beginning of word (or stay where we are)
util.run_command('sbp_to_word', args)
cursor.a = util.get_point()
# stretch the selection to the end of the word, making sure we don't zip past our
# start if we were going backwards
util.run_command('sbp_move_word', args)
cursor.b = util.get_point()
if direction < 0 and cursor.b > orig_point:
cursor.b = orig_point
# now convert the text in the selection
old_text = text = util.view.substr(cursor)
if mode == "title":
text = text.title()
elif mode == 'lower':
text = text.lower()
elif mode == 'upper':
text= text.upper()
else:
print("Unknown mode", mode)
if old_text != text:
util.view.replace(util.edit, cursor, text)
if direction < 0:
cursor.a = cursor.b = orig_point
else:
cursor.a = cursor.b = util.get_point()
return cursor
util.for_each_cursor(case_word)
class SbpMoveSexprCommand(SbpTextCommand):
is_ensure_visible_cmd = True
should_reset_target_column = True
def run_cmd(self, util, direction=1):
view = self.view
settings = view.settings()
separators = settings.get("sbp_sexpr_separators", default_sbp_sexpr_separators)
# determine the direction
count = util.get_count() * direction
forward = count > 0
count = abs(count)
def advance(cursor, first):
point = cursor.b
if forward:
limit = view.size()
while point < limit:
if util.is_word_char(point, True, separators):
point = view.find_by_class(point, True, sublime.CLASS_WORD_END, separators)
break