forked from guillermooo/Vintageous
-
Notifications
You must be signed in to change notification settings - Fork 0
/
xactions.py
2305 lines (1800 loc) · 80.9 KB
/
xactions.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
# TODO: weird name to avoid init issues with state.py::State.
import sublime
import sublime_plugin
import re
import logging
from Vintageous import local_logger
from Vintageous.state import _init_vintageous
from Vintageous.state import State
from Vintageous.vi import inputs
from Vintageous.vi import motions
from Vintageous.vi import utils
from Vintageous.vi.cmd_defs import cmd_types
from Vintageous.vi.cmd_defs import cmds
from Vintageous.vi.constants import regions_transformer_reversed
from Vintageous.vi.core import ViTextCommandBase
from Vintageous.vi.core import ViWindowCommandBase
from Vintageous.vi.keys import mappings
from Vintageous.vi.keys import KeySequenceTokenizer
from Vintageous.vi.keys import EOF
from Vintageous.vi.keys import to_bare_command_name
from Vintageous.vi.keys import key_names
from Vintageous.vi.mappings import Mappings
from Vintageous.vi.utils import gluing_undo_groups
from Vintageous.vi.utils import IrreversibleTextCommand
from Vintageous.vi.utils import is_view
from Vintageous.vi.utils import modes
from Vintageous.vi.utils import regions_transformer
_logger = local_logger(__name__)
class _vi_g_big_u(ViTextCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None, count=1, motion=None):
def f(view, s):
view.replace(edit, s, view.substr(s).upper())
# reverse the resulting region so that _enter_normal_mode collapses the
# selection as we want it.
return sublime.Region(s.b, s.a)
if mode != modes.INTERNAL_NORMAL:
raise ValueError('bad mode: ' + mode)
if motion is None:
raise ValueError('motion data required')
self.save_sel()
self.view.run_command(motion['motion'], motion['motion_args'])
if self.has_sel_changed():
regions_transformer(self.view, f)
else:
utils.blink()
self.enter_normal_mode(mode)
class _vi_gu(ViTextCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None, count=1, motion=None):
def f(view, s):
view.replace(edit, s, view.substr(s).lower())
# reverse the resulting region so that _enter_normal_mode collapses the
# selection as we want it.
return sublime.Region(s.b, s.a)
if mode != modes.INTERNAL_NORMAL:
raise ValueError('bad mode: ' + mode)
if motion is None:
raise ValueError('motion data required')
self.save_sel()
self.view.run_command(motion['motion'], motion['motion_args'])
if self.has_sel_changed():
regions_transformer(self.view, f)
else:
utils.blink()
self.enter_normal_mode(mode)
class _vi_gq(ViTextCommandBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run(self, edit, mode=None, count=1, motion=None):
def f(view, s):
return sublime.Region(s.begin(), s.end())
# reverse the resulting region so that _enter_normal_mode foo bar foo
# collapses the selection as we want it.
if mode != modes.INTERNAL_NORMAL:
raise ValueError('bad mode: ' + mode)
if motion is None:
raise ValueError('motion data required')
self.save_sel()
self.view.run_command(motion['motion'], motion['motion_args'])
if self.has_sel_changed():
self.save_sel()
self.view.run_command('wrap_lines')
self.view.sel().clear()
self.view.sel().add_all(self.old_sel)
else:
utils.blink()
self.enter_normal_mode(mode)
class _vi_u(IrreversibleTextCommand):
def run(self, count=1):
for i in range(count):
self.view.run_command('undo')
if self.view.has_non_empty_selection_region():
def reverse(view, s):
return sublime.Region(s.end(), s.begin())
# TODO: xpos is misaligned after this.
regions_transformer(self.view, reverse)
self.view.window().run_command('_enter_normal_mode', {'mode': modes.VISUAL})
class _vi_ctrl_r(IrreversibleTextCommand):
def run(self, count=1, mode=None):
for i in range(count):
self.view.run_command('redo')
class _vi_a(sublime_plugin.TextCommand):
def run(self, edit, count=1, mode=None):
def f(view, s):
if mode == modes.INTERNAL_NORMAL:
return sublime.Region(s.b + 1)
if mode == modes.VISUAL:
return sublime.Region(s.b)
return s
if mode is None:
raise ValueError('mode required')
regions_transformer(self.view, f)
self.view.window().run_command('_enter_insert_mode')
class _vi_c(ViTextCommandBase):
def run(self, edit, count=1, mode=None, motion=None):
if mode is None:
raise ValueError('mode required')
if mode == modes.INTERNAL_NORMAL and motion is None:
raise ValueError('motion required')
if mode == modes.INTERNAL_NORMAL and motion['motion'] == '_vi_w':
motion['motion'] = '_vi_e'
self.save_sel()
if motion:
self.view.run_command(motion['motion'], motion['motion_args'])
if not self.has_sel_changed():
self.enter_insert_mode(mode)
return
self.view.run_command('right_delete')
self.enter_insert_mode(mode)
class _enter_normal_mode(ViTextCommandBase):
"""
The equivalent of pressing the Esc key in Vim.
@mode
The mode we're coming from, which should still be the current mode.
@from_init
Whether _enter_normal_mode has been called from _init_vintageous. This
is important to know in order to not hide output panels when the user
is only navigating files or clicking around, not pressing Esc.
"""
def run(self, edit, mode=None, from_init=False):
state = self.state
self.view.window().run_command('hide_auto_complete')
self.view.window().run_command('hide_overlay')
if ((not from_init and (mode == modes.NORMAL) and not state.sequence) or
not is_view(self.view)):
# When _enter_normal_mode is requested from _init_vintageous, we
# should not hide output panels; hide them only if the user
# pressed Esc and we're not cancelling partial state data, or if a
# panel has the focus.
# XXX: We are assuming that state.sequence will always be empty
# when we do the check above. Is that so?
# XXX: The 'not is_view(self.view)' check above seems to be
# redundant, since those views should be ignored by
# Vintageous altogether.
self.view.window().run_command('hide_panel', {'cancel': True})
self.view.settings().set('command_mode', True)
self.view.settings().set('inverse_caret_state', True)
# Exit replace mode.
self.view.set_overwrite_status(False)
state.enter_normal_mode()
# XXX: st bug? if we don't do this, selections won't be redrawn
self.view.run_command('_enter_normal_mode_impl', {'mode': mode})
if state.glue_until_normal_mode and not state.gluing_sequence:
if self.view.is_dirty():
self.view.window().run_command('glue_marked_undo_groups')
# We're exiting from insert mode or replace mode. Capture
# the last native command as repeat data.
state.repeat_data = ('native', self.view.command_history(0)[:2], mode, None)
else:
self.view.window().run_command('unmark_undo_groups_for_gluing')
state.glue_until_normal_mode = False
if mode == modes.INSERT and int(state.normal_insert_count) > 1:
# TODO: Calculate size the view has grown by and place the caret
# after the newly inserted text.
sels = list(self.view.sel())
times = int(state.normal_insert_count) - 1
state.normal_insert_count = '1'
self.view.window().run_command('_vi_dot', {
'count': times,
'mode': mode,
'repeat_data': state.repeat_data,
})
self.view.sel().clear()
self.view.sel().add_all(sels)
state.xpos = self.view.rowcol(self.view.sel()[0].b)[1]
sublime.status_message('')
class _enter_normal_mode_impl(sublime_plugin.TextCommand):
def run(self, edit, mode=None):
def f(view, s):
_logger().info('[_enter_normal_mode_impl] entering normal mode from {0}'.format(mode))
if mode == modes.INSERT:
if view.line(s.b).a != s.b:
return sublime.Region(s.b - 1)
return sublime.Region(s.b)
if mode == modes.INTERNAL_NORMAL:
return sublime.Region(s.b)
if mode == modes.VISUAL:
# save selections for gv
# But only if there are non-empty sels. We might be in visual mode and not have
# non-empty sels because we've just existed from an action.
if self.view.has_non_empty_selection_region():
self.view.add_regions('visual_sel', list(self.view.sel()))
if s.a < s.b:
r = sublime.Region(s.b - 1)
if view.substr(r.b) == '\n':
r.b -= 1
return sublime.Region(r.b)
return sublime.Region(s.b)
if mode in (modes.VISUAL_LINE, modes.VISUAL_BLOCK):
# save selections for gv
# But only if there are non-empty sels. We might be in visual mode and not have
# non-empty sels because we've just existed from an action.
if self.view.has_non_empty_selection_region():
self.view.add_regions('visual_sel', list(self.view.sel()))
if s.a < s.b:
pt = s.b - 1
if (view.substr(pt) == '\n') and not view.line(pt).empty():
pt -= 1
return sublime.Region(pt)
else:
return sublime.Region(s.b)
if mode == modes.SELECT:
return sublime.Region(s.begin())
return sublime.Region(s.b)
if mode == modes.UNKNOWN:
return
if len(self.view.sel()) > 1 and mode == modes.NORMAL:
sel = self.view.sel()[0]
self.view.sel().clear()
self.view.sel().add(sel)
regions_transformer(self.view, f)
self.view.erase_regions('vi_search')
self.view.run_command('_vi_adjust_carets', {'mode': mode})
class _enter_select_mode(ViWindowCommandBase):
def run(self, mode=None, count=1):
self.state.enter_select_mode()
view = self.window.active_view()
# If there are no visual selections, do some work work for the user.
if not view.has_non_empty_selection_region():
self.window.run_command('find_under_expand')
state = State(view)
state.display_status()
class _enter_insert_mode(ViTextCommandBase):
def run(self, edit, mode=None, count=1):
self.view.settings().set('inverse_caret_state', False)
self.view.settings().set('command_mode', False)
self.state.enter_insert_mode()
self.state.normal_insert_count = str(count)
self.state.display_status()
class _enter_visual_mode(ViTextCommandBase):
def run(self, edit, mode=None):
state = self.state
if state.mode == modes.VISUAL:
self.view.run_command('_enter_normal_mode', {'mode': mode})
return
self.view.run_command('_enter_visual_mode_impl', {'mode': mode})
state.enter_visual_mode()
state.display_status()
class _enter_visual_mode_impl(sublime_plugin.TextCommand):
"""
Transforms the view's selections. We don't do this inside the EnterVisualMode
window command because ST seems to neglect to repaint the selections. (bug?)
"""
def run(self, edit, mode=None):
def f(view, s):
if mode == modes.VISUAL_LINE:
return sublime.Region(s.a, s.b)
else:
return sublime.Region(s.b, s.b + 1)
regions_transformer(self.view, f)
class _enter_visual_line_mode(ViTextCommandBase):
def run(self, edit, mode=None):
state = self.state
if state.mode == modes.VISUAL_LINE:
self.view.run_command('_enter_normal_mode', {'mode': mode})
return
self.view.run_command('_enter_visual_line_mode_impl', {'mode': mode})
state.enter_visual_line_mode()
state.display_status()
class _enter_visual_line_mode_impl(sublime_plugin.TextCommand):
"""
Transforms the view's selections.
"""
def run(self, edit, mode=None):
def f(view, s):
if mode == modes.VISUAL:
if s.a < s.b:
if view.substr(s.b - 1) != '\n':
return sublime.Region(view.line(s.a).a,
view.full_line(s.b - 1).b)
else:
return sublime.Region(view.line(s.a).a, s.b)
else:
if view.substr(s.a - 1 ) != '\n':
return sublime.Region(view.full_line(s.a - 1).b,
view.line(s.b).a)
else:
return sublime.Region(s.a, view.line(s.b).a)
else:
return view.full_line(s.b)
regions_transformer(self.view, f)
class _enter_replace_mode(ViTextCommandBase):
def run(self, edit):
def f(view, s):
return sublime.Region(s.b)
state = self.state
state.settings.view['command_mode'] = False
state.settings.view['inverse_caret_state'] = False
state.view.set_overwrite_status(True)
state.enter_replace_mode()
regions_transformer(self.view, f)
state.display_status()
state.reset()
# TODO: Remove this command once we don't need it any longer.
class ToggleMode(ViWindowCommandBase):
def run(self):
value = self.window.active_view().settings().get('command_mode')
self.window.active_view().settings().set('command_mode', not value)
self.window.active_view().settings().set('inverse_caret_state', not value)
print("command_mode status:", not value)
state = self.state
if not self.window.active_view().settings().get('command_mode'):
state.mode = modes.INSERT
sublime.status_message('command mode status: %s' % (not value))
class PressKeys(ViWindowCommandBase):
"""
Runs sequences of keys representing Vim commands.
For example: fngU5l
@keys
Key sequence to be run.
@repeat_count
Count to be applied when repeating through the '.' command.
@check_user_mappings
Whether user mappings should be consulted to expand key sequences.
"""
def run(self, keys, repeat_count=None, check_user_mappings=True):
state = self.state
_logger().info("[PressKeys] seq received: {0} mode: {1}"
.format(keys, state.mode))
initial_mode = state.mode
# Disable interactive prompts. For example, to supress interactive
# input collection in /foo<CR>.
state.non_interactive = True
# First, run any motions coming before the first action. We don't keep
# these in the undo stack, but they will still be repeated via '.'.
# This ensures that undoing will leave the caret where the first
# editing action started. For example, 'lldl' would skip 'll' in the
# undo history, but store the full sequence for '.' to use.
leading_motions = ''
for key in KeySequenceTokenizer(keys).iter_tokenize():
self.window.run_command('press_key', {
'key': key,
'do_eval': False,
'repeat_count': repeat_count,
'check_user_mappings': check_user_mappings
})
if state.action:
# The last key press has caused an action to be primed. That
# means there are no more leading motions. Break out of here.
_logger().info('[PressKeys] first action found in {0}'
.format(state.sequence))
state.reset_command_data()
if state.mode == modes.OPERATOR_PENDING:
state.mode = modes.NORMAL
break
elif state.runnable():
# Run any primed motion.
leading_motions += state.sequence
state.eval()
state.reset_command_data()
elif state.input_parsers:
# XXX: Unreachable?
pass
else:
# XXX: When do we reach here?
state.eval()
if state.input_parsers:
# State is requesting more input, so this is the last command in
# the sequence and it needs more input.
self.collect_input()
return
# Strip the already run commands.
if leading_motions:
if ((len(leading_motions) == len(keys)) and
(not state.input_parsers)):
return
_logger().info('[PressKeys] original seq/leading motions: {0}/{1}'
.format(keys, leading_motions))
keys = keys[len(leading_motions):]
_logger().info('[PressKeys] seq stripped to {0}'.format(keys))
if not (state.motion and not state.action):
with gluing_undo_groups(self.window.active_view(), state):
try:
for key in KeySequenceTokenizer(keys).iter_tokenize():
if key.lower() == key_names.ESC:
# XXX: We should pass a mode here?
self.window.run_command('_enter_normal_mode')
continue
elif state.mode not in (modes.INSERT, modes.REPLACE):
self.window.run_command('press_key', {
'key': key,
'repeat_count': repeat_count,
'check_user_mappings': check_user_mappings
})
else:
# TODO: remove active_view; window will route the
# cmd.
self.window.active_view().run_command('insert', {
'characters': key})
if not state.input_parsers:
return
finally:
state.non_interactive = False
# Ensure we set the full command for '.' to use, but don't
# store '.' alone.
if (leading_motions + keys) not in ('.', 'u', '<C-r>'):
state.repeat_data = (
'vi', (leading_motions + keys),
initial_mode, None)
# We'll reach this point if we have a command that requests input
# whose input parser isn't satistied. For example, `/foo`. Note that
# `/foo<CR>`, on the contrary, would have satisfied the parser.
_logger().info('[PressKeys] unsatisfied parser: {0} {1}'
.format(state.action, state.motion))
if (state.action and state.motion):
# We have a parser an a motion that can collect data. Collect data
# interactively.
motion_func = getattr(motions, state.motion['name'], None)
if motion_func is None:
utils.blink()
state.reset_command_data()
return
motion_data = motion_func(state)
motion_data['motion_args']['default'] = state.user_input
self.window.run_command(motion_data['motion'],
motion_data['motion_args'])
return
self.collect_input()
def collect_input(self):
try:
parser_def = inputs.get(self.state, self.state.input_parsers[-1])
_logger().info('[PressKeys] last attemp to collect input: {0}'
.format(parser_def.command))
if parser_def.interactive_command:
self.window.run_command(parser_def.interactive_command,
{'default': self.state.user_input})
except IndexError:
_logger().info('[Vintageous] could not find a command to collect'
'more user input')
utils.blink()
finally:
self.state.non_interactive = False
class PressKey(ViWindowCommandBase):
"""
Core command. It interacts with the global state each time a key is
pressed.
@key
Key pressed.
@repeat_count
count to be used when repeating through the '.' command.
@do_eval
whether to evaluate the global state when it's in a runnable
state. Most of the time, the default value of `True` should be
used. Set to `False` when you want to manually control
the global state's evaluation. For example, this is what the
PressKeys command does.
"""
def run(self, key, repeat_count=None, do_eval=True, check_user_mappings=True):
_logger().info("[PressKey] pressed: {0}".format(key))
state = self.state
# If the user has made selections with the mouse, we may be in an
# inconsistent state. Try to remedy that.
if (state.view.has_non_empty_selection_region() and
state.mode not in (modes.VISUAL,
modes.VISUAL_LINE,
modes.VISUAL_BLOCK,
modes.SELECT)):
_init_vintageous(state.view)
if key.lower() == '<esc>':
self.window.run_command('_enter_normal_mode', {'mode': state.mode})
state.reset_command_data()
return
state.sequence += key
if not state.recording_macro:
state.display_status()
# sublime.status_message(state.sequence)
else:
sublime.status_message('[Vintageous] Recording')
if state.capture_register:
state.register = key
state.partial_sequence = ''
return
# if capturing input, we shall not pass this point
if state.input_parsers:
if state.process_user_input(key):
if state.runnable():
_logger().info('[PressKey] state holds complete command: {0} motion: {1} user input: {2}'.format(state.action,
state.motion,
state.user_input))
if do_eval:
_logger().info('[PressKey] evaluating complete command')
state.eval()
state.reset_command_data()
return
if repeat_count:
state.action_count = str(repeat_count)
if self.handle_counts(key, repeat_count):
return
state.partial_sequence += key
_logger().info("[PressKey] sequence {0}".format(state.sequence))
_logger().info("[PressKey] partial sequence {0}".format(state.partial_sequence))
# key_mappings = KeyMappings(self.window.active_view())
key_mappings = Mappings(state)
if check_user_mappings and key_mappings.incomplete_user_mapping():
_logger().info("[PressKey] incomplete user mapping: {0}".format(state.partial_sequence))
# for example, we may have typed 'aa' and there's an 'aaa' mapping.
# we need to keep collecting input.
return
_logger().info('[PressKey] getting cmd for seq/partial seq in (mode): {0}/{1} ({2})'.format(state.sequence,
state.partial_sequence,
state.mode))
command = key_mappings.get_current(check_user_mappings=check_user_mappings)
if command['name'] == cmds.OPEN_REGISTERS:
_logger().info('[PressKey] requesting register name')
state.capture_register = True
return
# XXX: This doesn't seem to be correct. If we are in OPERATOR_PENDING mode, we should
# most probably not have to wipe the state.
if command['type'] == cmd_types.USER:
if do_eval:
new_keys = command['name']
if state.mode == modes.OPERATOR_PENDING:
command_name = command['name']
new_keys = state.sequence[:-len(state.partial_sequence)] + command['name']
state.reset_command_data()
state.mode = modes.NORMAL
_logger().info('[PressKey] running user mapping {0} via press_keys starting in mode {1}'.format(new_keys, state.mode))
self.window.run_command('press_keys', {'keys': new_keys, 'check_user_mappings': False})
return
if command['name'] == cmds.OPEN_NAME_SPACE:
# Keep collecing input to complete the sequence. For example, we
# may have typed 'g'.
_logger().info("[PressKey] opening namespace: {0}".format(state.partial_sequence))
return
elif command['name'] == cmds.MISSING:
bare_seq = to_bare_command_name(state.sequence)
if state.mode == modes.OPERATOR_PENDING:
# We might be looking at a command like 'dd'. The first 'd' is
# mapped for normal mode, but the second is missing in
# operator pending mode, so we get a missing command. Try to
# build the full command now.
#
# Exclude user mappings, since they've already been given a
# chance to evaluate.
command = key_mappings.get_current(sequence=bare_seq,
mode=modes.NORMAL,
check_user_mappings=False)
else:
command = key_mappings.get_current(sequence=bare_seq)
if command['name'] == cmds.MISSING:
_logger().info('[PressKey] unmapped sequence: {0}'.format(state.sequence))
utils.blink()
state.mode = modes.NORMAL
state.reset_command_data()
return
if (state.mode == modes.OPERATOR_PENDING and
command['type'] == cmd_types.ACTION):
# TODO: This may be unreachable code by now. ???
# we're expecting a motion, but we could still get an action.
# For example, dd, g~g~ or g~~
# remove counts
action_seq = to_bare_command_name(state.sequence)
_logger().info('[PressKey] action seq: {0}'.format(action_seq))
command = key_mappings.get_current(sequence=action_seq, mode=modes.NORMAL)
if command['name'] == cmds.MISSING:
_logger().info("[PressKey] unmapped sequence: {0}".format(state.sequence))
state.reset_command_data()
return
if not command['motion_required']:
state.mode = modes.NORMAL
state.set_command(command)
_logger().info("[PressKey] '{0}'' mapped to '{1}'".format(state.partial_sequence, command))
if state.mode == modes.OPERATOR_PENDING:
state.reset_partial_sequence()
if do_eval:
state.eval()
def handle_counts(self, key, repeat_count):
"""
Returns `True` if the processing of the current key needs to stop.
"""
state = State(self.window.active_view())
if not state.action and key.isdigit():
if not repeat_count and (key != '0' or state.action_count) :
_logger().info('[PressKey] action count digit: {0}'.format(key))
state.action_count += key
return True
if (state.action and (state.mode == modes.OPERATOR_PENDING) and
key.isdigit()):
if not repeat_count and (key != '0' or state.motion_count):
_logger().info('[PressKey] motion count digit: {0}'.format(key))
state.motion_count += key
return True
class _vi_dot(ViWindowCommandBase):
def run(self, mode=None, count=None, repeat_data=None):
state = self.state
state.reset_command_data()
if state.mode == modes.INTERNAL_NORMAL:
state.mode = modes.NORMAL
if repeat_data is None:
_logger().info('[_vi_dot] nothing to repeat')
return
# TODO: Find out if the user actually meant '1'.
if count and count == 1:
count = None
type_, seq_or_cmd, old_mode, visual_data = repeat_data
_logger().info('[_vi_dot] type: {0} seq or cmd: {1} old mode: {2}'.format(type_, seq_or_cmd, old_mode))
if visual_data and (mode != modes.VISUAL):
s0 = state.view.sel()[0]
if (visual_data[0] > 0):
end = state.view.text_point(
state.view.rowcol(s0.b)[0] + visual_data[0],
visual_data[1])
else:
end = s0.b + visual_data[1]
state.view.sel().add(sublime.Region(s0.b, end))
state.mode = modes.VISUAL
elif not visual_data and (mode == modes.VISUAL):
# Can't repeat normal mode commands in visual mode.
utils.blink()
return
elif mode not in (modes.VISUAL, modes.VISUAL_LINE, modes.NORMAL,
modes.INTERNAL_NORMAL, modes.INSERT):
utils.blink()
return
if type_ == 'vi':
self.window.run_command('press_keys', {'keys': seq_or_cmd,
'repeat_count': count})
elif type_ == 'native':
sels = list(self.window.active_view().sel())
# FIXME: We're not repeating as we should. It's the motion that
# should receive this count.
for i in range(count or 1):
self.window.run_command(*seq_or_cmd)
# FIXME: What happens in visual mode?
self.window.active_view().sel().clear()
self.window.active_view().sel().add_all(sels)
else:
raise ValueError('bad repeat data')
self.window.run_command('_enter_normal_mode', {'mode': mode})
state.repeat_data = repeat_data
class _vi_dd_action(ViTextCommandBase):
_can_yank = True
_synthetize_new_line_at_eof = True
_yanks_linewise = False
_populates_small_delete_register = False
def run(self, edit, mode=None, count=1):
def f(view, s):
# We've made a selection with _vi_cc_motion just before this.
if mode == modes.INTERNAL_NORMAL:
view.erase(edit, s)
if utils.row_at(self.view, s.a) != utils.row_at(self.view, self.view.size()):
pt = utils.next_non_white_space_char(view, s.a, white_space=' \t')
else:
pt = utils.next_non_white_space_char(view,
self.view.line(s.a).a,
white_space=' \t')
return sublime.Region(pt, pt)
return s
self.view.run_command('_vi_dd_motion', {'mode': mode, 'count': count})
state = self.state
state.registers.yank(self)
row = [self.view.rowcol(s.begin())[0] for s in self.view.sel()][0]
regions_transformer_reversed(self.view, f)
self.view.sel().clear()
self.view.sel().add(sublime.Region(self.view.text_point(row, 0)))
class _vi_dd_motion(sublime_plugin.TextCommand):
def run(self, edit, mode=None, count=1):
def f(view, s):
if mode == modes.INTERNAL_NORMAL:
end = view.text_point(utils.row_at(self.view, s.b) + (count - 1), 0)
begin = view.line(s.b).a
if ((utils.row_at(self.view, end) == utils.row_at(self.view, view.size())) and
(view.substr(begin - 1) == '\n')):
begin -= 1
return sublime.Region(begin, view.full_line(end).b)
return s
regions_transformer(self.view, f)
class _vi_cc_motion(ViTextCommandBase):
def run(self, edit, mode=None, count=1):
def f(view, s):
if mode == modes.INTERNAL_NORMAL:
end = view.text_point(utils.row_at(self.view, s.b) + (count - 1), 0)
begin = view.line(s.b).a
begin = utils.next_non_white_space_char(view, begin, white_space=' \t')
return sublime.Region(begin, view.line(end).b)
return s
regions_transformer(self.view, f)
class _vi_cc_action(ViTextCommandBase):
_can_yank = True
_synthetize_new_line_at_eof = True
_yanks_linewise = False
_populates_small_delete_register = False
def run(self, edit, mode=None, count=1):
self.view.run_command('_vi_cc_motion', {'mode': mode, 'count': count})
state = self.state
state.registers.yank(self)
self.view.run_command('right_delete')
self.enter_insert_mode(mode)
self.set_xpos(state)
class _vi_visual_o(sublime_plugin.TextCommand):
def run(self, edit, mode=None, count=1):
def f(view, s):
# FIXME: In Vim, o doesn't work in modes.VISUAL_LINE, but ST can't move the caret while
# in modes.VISUAL_LINE, so we enable this for convenience. Change when/if ST can move
# the caret while in modes.VISUAL_LINE.
if mode in (modes.VISUAL, modes.VISUAL_LINE):
return sublime.Region(s.b, s.a)
return s
regions_transformer(self.view, f)
self.view.show(self.view.sel()[0].b, False)
class _vi_yy(ViTextCommandBase):
_can_yank = True
_synthetize_new_line_at_eof = True
def run(self, edit, mode=None, count=1, register=None):
def select(view, s):
if count > 1:
row, col = self.view.rowcol(s.b)
end = view.text_point(row + count - 1, 0)
return sublime.Region(view.line(s.a).a, view.full_line(end).b)
return view.full_line(s.b)
def restore():
self.view.sel().clear()
self.view.sel().add_all(list(self.old_sel))
if mode != modes.INTERNAL_NORMAL:
utils.blink()
raise ValueError('wrong mode')
self.save_sel()
regions_transformer(self.view, select)
state = self.state
self.outline_target()
state.registers.yank(self, register)
restore()
self.enter_normal_mode(mode)
class _vi_y(ViTextCommandBase):
_can_yank = True
_populates_small_delete_register = True
def run(self, edit, mode=None, count=1, motion=None, register=None):
def f(view, s):
return sublime.Region(s.end(), s.begin())
if mode == modes.INTERNAL_NORMAL:
if motion is None:
raise ValueError('bad args')
self.view.run_command(motion['motion'], motion['motion_args'])
self.outline_target()
elif mode not in (modes.VISUAL, modes.VISUAL_LINE, modes.VISUAL_BLOCK):
return
state = self.state
state.registers.yank(self, register)
regions_transformer(self.view, f)
self.enter_normal_mode(mode)
class _vi_d(ViTextCommandBase):
_can_yank = True
_populates_small_delete_register = True
def run(self, edit, mode=None, count=1, motion=None, register=None):
def reverse(view, s):
return sublime.Region(s.end(), s.begin())
if mode not in (modes.INTERNAL_NORMAL, modes.VISUAL,
modes.VISUAL_LINE):
raise ValueError('wrong mode')
if mode == modes.INTERNAL_NORMAL and not motion:
raise ValueError('missing motion')
if motion:
self.save_sel()
self.view.run_command(motion['motion'], motion['motion_args'])
# The motion has failed, so abort.
if not self.has_sel_changed():
utils.blink()
self.enter_normal_mode(mode)
return
state = self.state
state.registers.yank(self, register)
self.view.run_command('left_delete')
self.view.run_command('_vi_adjust_carets')
self.enter_normal_mode(mode)
class _vi_big_a(ViTextCommandBase):
def run(self, edit, mode=None, count=1):
def f(view, s):
if mode == modes.VISUAL_BLOCK:
if self.view.substr(s.b - 1) == '\n':
return sublime.Region(s.end() - 1)
return sublime.Region(s.end())