-
Notifications
You must be signed in to change notification settings - Fork 3
/
jove.py
1729 lines (1485 loc) · 60.3 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
# IMPLEMENT
# - C-x C-o
#
# - implement a build command which lets me specify the make command I want to run
# - implement forward/backward "defun" via scope selectors
# - implement forward/backward class definition via scope selectors
# - make fill paragraph smart about bulleted (i.e., ones that start with "-" or "*")
# - add support for "set mark automatically" commands
# - move_to brackets but not necessarily other move_to's
# - maybe get rid of your own move to eof and bof if you can get this working
# - goto symbol stuff will be harder...
# - add an up-arrow (or meta-P meta-N) history mechanism for incremental search
# FIX
#
# fix comments so you can comment in the right column if no region is selected
import re, sys
import functools as fu
import sublime, sublime_plugin
from copy import copy
from .kill_ring import KillRing
from .mark_ring import MarkRing
JOVE_STATUS = "jove"
ISEARCH_ESCAPE_CMDS = ('move_to', 'jove_center_view', 'move', 'jove_universal_argument',
'jove_move_word', 'jove_move_to', 'scroll_lines')
default_jove_sexpr_separators = "./\\()\"'-:,.;<>~!@#$%^&*|+=[]{}`~?";
default_jove_word_separators = "./\\()\"'-_:,.;<>~!@#$%^&*|+=[]{}`~?";
# kill ring shared across all buffers
kill_ring = KillRing()
# 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'])
#
# We store state about each view.
#
class ViewState():
# per view state
view_state_dict = dict()
# currently active view
current = None
# current in-progress i-search instance
isearch_info = 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):
CmdHelper(view).toggle_active_mark_mode(False)
def on_deactivated(self, view):
info = ViewState.isearch_info
if info and info.input_view == view:
# deactivate immediately or else overlays will malfunction (we'll eat their keys)
# we cannot dismiss the input panel because an overlay (if present) will lose focus
info.deactivate()
def on_activated_async(self, view):
info = ViewState.isearch_info
if info and not view.settings().get("is_widget"):
# now we can dismiss the input panel
info.done()
def on_query_context(self, view, key, operator, operand, match_all):
if key == "i_search_active":
return ViewState.isearch_info and ViewState.isearch_info.is_active
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 on_anything(self, view):
view.erase_status(JOVE_STATUS)
#
# Override some commands to execute them N times if the numberic argument is supplied.
#
def on_text_command(self, view, cmd, args):
if view.settings().get('is_widget') and ViewState.isearch_info:
if cmd in ISEARCH_ESCAPE_CMDS:
return ('jove_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 "jove_" it's handled
# elsewhere)
if not cmd.startswith("jove_"):
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':
if ViewState.isearch_info:
ViewState.isearch_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
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 ("jove_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 = CmdHelper(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 "jove_" this is handled elsewhere)
if not cmd.startswith("jove_"):
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 = CmdHelper(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)
#
# A helper class which provides a bunch of useful functionality on a view
#
class CmdHelper:
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 = b = self.get_point()
selection = self.view.sel()
selection.clear()
selection.add(sublime.Region(a, b))
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()
selection.add_all(view.get_regions(key))
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 commands. This sets up state, creates a helper, processes the universal
# argument, and then calls the run_cmd method, which subclasses should override.
#
class JoveTextCommand(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 != 'jove_universal_argument' or self.unregistered):
vs.this_cmd = cmd
vs.entered += 1
jove = CmdHelper(self.view, state=vs, edit=edit)
try:
self.run_cmd(jove, **kwargs)
finally:
vs.entered -= 1
if vs.entered == 0 and (cmd != 'jove_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:
jove.reset_target_column()
#
# Calls run command a specified number of times.
#
class JoveDoTimesCommand(JoveTextCommand):
def run_cmd(self, jove, cmd, _times, **args):
view = self.view
visible = view.visible_region()
for i in range(_times):
view.run_command(cmd, args)
point = jove.get_point()
if not visible.contains(point):
jove.ensure_visible(point, True)
class JoveShowScopeCommand(JoveTextCommand):
def run_cmd(self, jove, direction=1):
point = jove.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)
class JoveMoveWordCommand(JoveTextCommand):
should_reset_target_column = True
is_ensure_visible_cmd = True
def run_cmd(self, jove, direction=1):
view = self.view
settings = view.settings()
separators = settings.get("jove_word_separators", default_jove_word_separators)
# determine the direction
count = jove.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 jove.is_word_char(point, True, separators):
point = view.find_by_class(point, True, sublime.CLASS_WORD_START, separators)
point = view.find_by_class(point, True, sublime.CLASS_WORD_END, separators)
else:
if not first or not jove.is_word_char(point, False, separators):
point = view.find_by_class(point, False, sublime.CLASS_WORD_END, separators)
point = view.find_by_class(point, False, sublime.CLASS_WORD_START, separators)
cursor.a = cursor.b = point
return cursor
for c in range(count):
jove.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 JoveToWordCommand(JoveTextCommand):
should_reset_target_column = True
def run_cmd(self, jove, direction=1):
view = self.view
settings = view.settings()
separators = settings.get("jove_word_separators", default_jove_word_separators)
forward = direction > 0
def to_word(cursor):
point = cursor.b
if forward:
if not jove.is_word_char(point, True, separators):
point = view.find_by_class(point, True, sublime.CLASS_WORD_START, separators)
else:
if not jove.is_word_char(point, False, separators):
point = view.find_by_class(point, False, sublime.CLASS_WORD_END, separators)
cursor.a = cursor.b = point
return cursor
jove.for_each_cursor(to_word)
class JoveCaseWordCommand(JoveTextCommand):
should_reset_target_column = True
def run_cmd(self, jove, mode, direction=1):
count = jove.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 = jove.save_region("tmp")
for i in range(count):
jove.run_command("jove_move_word", args)
args['direction'] = -args['direction']
for i in range(count):
# go to beginning of word (or stay where we are)
jove.run_command('jove_to_word', args)
cursor.a = jove.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
jove.run_command('jove_move_word', args)
cursor.b = jove.get_point()
if direction < 0 and cursor.b > orig_point:
cursor.b = orig_point
# now convert the text in the selection
old_text = text = jove.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:
jove.view.erase(jove.edit, cursor)
jove.view.insert(jove.edit, cursor.a, text)
if direction < 0:
cursor.a = cursor.b = orig_point
else:
cursor.a = cursor.b = jove.get_point()
return cursor
jove.for_each_cursor(case_word)
class JoveMoveSexprCommand(JoveTextCommand):
is_ensure_visible_cmd = True
should_reset_target_column = True
def run_cmd(self, jove, direction=1):
view = self.view
settings = view.settings()
separators = settings.get("jove_sexpr_separators", default_jove_sexpr_separators)
# determine the direction
count = jove.get_count() * direction
forward = count > 0
count = abs(count)
def advance(cursor, first=False, **kwargs):
point = cursor.b
if forward:
limit = view.size()
while point < limit:
if jove.is_word_char(point, True, separators):
point = view.find_by_class(point, True, sublime.CLASS_WORD_END, separators)
break
else:
ch = view.substr(point)
if ch in "({['\"":
next_point = jove.to_other_end(point, direction)
if next_point is not None:
point = next_point
break
point += 1
else:
while point > 0:
if jove.is_word_char(point, False, separators):
point = view.find_by_class(point, False, sublime.CLASS_WORD_START, separators)
break
else:
ch = view.substr(point - 1)
if ch in ")}]'\"":
next_point = jove.to_other_end(point, direction)
if next_point is not None:
point = next_point
break
point -= 1
cursor.a = cursor.b = point
return cursor
for c in range(count):
jove.for_each_cursor(advance, first=(c == 0))
#
# This command remembers all the current cursor positions, executes a command on all the cursors,
# and then deletes all the data between the two.
#
# If there's only one selection, the deleted data is added to the kill ring appropriately.
#
class JoveMoveThenDeleteCommand(JoveTextCommand):
is_ensure_visible_cmd = True
is_kill_cmd = True
def run_cmd(self, jove, move_cmd, **kwargs):
view = self.view
selection = view.sel()
# peek at the count
count = jove.get_count(True)
if 'direction' in kwargs:
count *= kwargs['direction']
# remember the current cursor positions
orig_cursors = [s for s in selection]
view.run_command(move_cmd, kwargs)
# extend each cursor so we can delete the bytes, and only if there is only one region will
# we add the data to the kill ring
new_cursors = [s for s in selection]
selection.clear()
for old,new in zip(orig_cursors, new_cursors):
if old < new:
selection.add(sublime.Region(old.begin(), new.end()))
else:
selection.add(sublime.Region(new.begin(), old.end()))
# only append to kill ring if there's one selection
if len(selection) == 1:
kill_ring.add(view.substr(selection[0]), forward=count > 0, join=jove.state.last_was_kill_cmd())
for region in selection:
view.erase(jove.edit, region)
class JoveGotoLineCommand(JoveTextCommand):
def run_cmd(self, jove):
if jove.has_prefix_arg():
jove.goto_line(jove.get_count())
else:
self.run_window_command("show_overlay", {"overlay": "goto", "text": ":"})
class JoveDeleteWhiteSpaceCommand(JoveTextCommand):
def run_cmd(self, jove):
jove.for_each_cursor(self.delete_white_space, jove)
def delete_white_space(self, cursor, jove, **kwargs):
view = self.view
line = view.line(cursor.a)
data = view.substr(line)
row,col = view.rowcol(cursor.a)
start = col
while start - 1 >= 0 and data[start-1: start] in (" \t"):
start -= 1
end = col
limit = len(data)
while end + 1 < limit and data[end:end+1] in (" \t"):
end += 1
view.erase(jove.edit, sublime.Region(line.begin() + start, line.begin() + end))
return None
class JoveUniversalArgumentCommand(JoveTextCommand):
def run_cmd(self, jove, value):
state = jove.state
if not state.argument_supplied:
state.argument_supplied = True
if value == 'by_four':
state.argument_value = 4
elif value == 'negative':
state.argument_negative = True
else:
state.argument_value = value
elif value == 'by_four':
state.argument_value *= 4
elif isinstance(value, int):
state.argument_value *= 10
state.argument_value += value
elif value == 'negative':
state.argument_value = -state.argument_value
class JoveShiftRegionCommand(JoveTextCommand):
"""Shifts the emacs region left or right."""
def run_cmd(self, jove, direction):
view = self.view
state = jove.state
r = jove.save_region("shift")
if r:
jove.toggle_active_mark_mode(False)
selection = self.view.sel()
selection.clear()
# figure out how far we're moving
if state.argument_supplied:
cols = direction * jove.get_count()
else:
cols = direction * self.view.settings().get("tab_size")
# now we know which way and how far we're shifting, create a cursor for each line we
# want to shift
amount = abs(cols)
count = 0
shifted = 0
for line in jove.for_each_line(r):
count += 1
if cols < 0 and (line.size() < amount or not jove.is_blank(line.a, line.a + amount)):
continue
selection.add(sublime.Region(line.a, line.a))
shifted += 1
# shift the region
if cols > 0:
# shift right
self.view.run_command("insert", {"characters": " " * cols})
else:
for i in range(amount):
self.view.run_command("right_delete")
# restore the region
jove.restore_region("shift")
sublime.set_timeout(lambda: jove.set_status("Shifted %d of %d lines in the region" % (shifted, count)), 100)
class JoveCenterViewCommand(JoveTextCommand):
def run_cmd(self, jove):
view = self.view
point = jove.get_point()
if jove.has_prefix_arg():
lines = jove.get_count()
line_height = view.line_height()
ignore, point_offy = view.text_to_layout(point)
offx, ignore = view.viewport_position()
view.set_viewport_position((offx, point_offy - line_height * lines))
else:
view.show_at_center(point)
class JoveSetMarkCommand(JoveTextCommand):
def run_cmd(self, jove):
state = jove.state
if state.argument_supplied:
pos = state.mark_ring.pop()
if pos:
jove.goto_position(pos)
else:
jove.set_status("No mark to pop!")
state.this_cmd = "jove_pop_mark"
elif state.this_cmd == state.last_cmd:
# at least two set mark commands in a row: turn ON the highlight
jove.toggle_active_mark_mode()
else:
# set the mark
state.active_mark = False
jove.set_mark()
class JoveSwapPointAndMarkCommand(JoveTextCommand):
def run_cmd(self, jove):
if jove.state.argument_supplied:
jove.toggle_active_mark_mode()
else:
jove.swap_point_and_mark()
class JoveMoveToCommand(JoveTextCommand):
is_ensure_visible_cmd = True
def run_cmd(self, jove, to):
if to == 'bof':
jove.goto_position(0, set_mark=True)
elif to == 'eof':
jove.goto_position(self.view.size(), set_mark=True)
elif to in ('eow', 'bow'):
visible = self.view.visible_region()
jove.goto_position(visible.a if to == 'bow' else visible.b)
class JoveOpenLineCommand(JoveTextCommand):
def run_cmd(self, jove):
view = self.view
for point in view.sel():
view.insert(jove.edit, point.b, "\n")
view.run_command("move", {"by": "characters", "forward": False})
class JoveKillRegionCommand(JoveTextCommand):
is_kill_cmd = True
def run_cmd(self, jove, is_copy=False):
view = self.view
region = jove.get_region()
if region:
bytes = region.size()
kill_ring.add(view.substr(region), True, False)
if not is_copy:
view.erase(jove.edit, region)
else:
jove.set_status("Copied %d bytes" % (bytes,))
jove.toggle_active_mark_mode(False)
class JovePaneCmdCommand(JoveTextCommand):
def run_cmd(self, jove, cmd, **kwargs):
view = self.view
window = view.window()
if cmd == 'split':
self.split(window, jove, **kwargs)
elif cmd == 'grow':
self.grow(window, jove, **kwargs)
elif cmd == 'destroy':
self.destroy(window, jove, **kwargs)
elif cmd == 'move':
self.move(window, jove, **kwargs)
else:
print("Unknown command")
#
# Grow the current selected window group (pane). Amount is usually 1 or -1 for grow and shrink.
#
def grow(self, window, jove, amount):
def rows_to_sizes(rows):
sizes = []
for i in range(len(rows) - 1):
sizes.append(rows[i + 1] - rows[i])