forked from guillermooo/Vintageous
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ex_commands.py
executable file
·1774 lines (1334 loc) · 56.3 KB
/
ex_commands.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 os
import re
import stat
import subprocess
import sublime
import sublime_plugin
from Vintageous.ex import ex_error
from Vintageous.ex import shell
from Vintageous.ex.ex_error import Display
from Vintageous.ex.ex_error import ERR_CANT_FIND_DIR_IN_CDPATH
from Vintageous.ex.ex_error import ERR_CANT_MOVE_LINES_ONTO_THEMSELVES
from Vintageous.ex.ex_error import ERR_CANT_WRITE_FILE
from Vintageous.ex.ex_error import ERR_EMPTY_BUFFER
from Vintageous.ex.ex_error import ERR_FILE_EXISTS
from Vintageous.ex.ex_error import ERR_INVALID_ADDRESS
from Vintageous.ex.ex_error import ERR_NO_FILE_NAME
from Vintageous.ex.ex_error import ERR_OTHER_BUFFER_HAS_CHANGES
from Vintageous.ex.ex_error import ERR_READONLY_FILE
from Vintageous.ex.ex_error import ERR_UNSAVED_CHANGES
from Vintageous.ex.ex_error import show_error
from Vintageous.ex.ex_error import show_message
from Vintageous.ex.ex_error import show_status
from Vintageous.ex.ex_error import show_not_implemented
from Vintageous.ex.ex_error import VimError
from Vintageous.ex.parser.parser import parse_command_line
from Vintageous.ex.plat.windows import get_oem_cp
from Vintageous.ex.plat.windows import get_startup_info
from Vintageous.state import State
from Vintageous.vi import abbrev
from Vintageous.vi import utils
from Vintageous.vi.constants import MODE_NORMAL
from Vintageous.vi.constants import MODE_VISUAL
from Vintageous.vi.constants import MODE_VISUAL_LINE
from Vintageous.vi.core import ViWindowCommandBase
from Vintageous.vi.mappings import Mappings
from Vintageous.vi.search import find_all_in_range
from Vintageous.vi.settings import set_global
from Vintageous.vi.settings import set_local
from Vintageous.vi.sublime import has_dirty_buffers
from Vintageous.vi.utils import adding_regions
from Vintageous.vi.utils import first_sel
from Vintageous.vi.utils import modes
from Vintageous.vi.utils import R
from Vintageous.vi.utils import resolve_insertion_point_at_b
from Vintageous.vi.utils import row_at
GLOBAL_RANGES = []
CURRENT_LINE_RANGE = {'left_ref': '.', 'left_offset': 0,
'left_search_offsets': [], 'right_ref': None,
'right_offset': 0, 'right_search_offsets': []}
def changing_cd(f, *args, **kwargs):
def inner(*args, **kwargs):
try:
state = State(args[0].view)
except AttributeError:
state = State(args[0].window.active_view())
old = os.getcwd()
try:
# FIXME: Under some circumstances, like when switching projects to
# a file whose _cmdline_cd has not been set, _cmdline_cd might
# return 'None'. In such cases, change to the actual current
# directory as a last measure. (We should probably fix this anyway).
os.chdir(state.settings.vi['_cmdline_cd'] or old)
f(*args, **kwargs)
finally:
os.chdir(old)
return inner
def get_view_info(v):
"""gathers data to be displayed by :ls or :buffers
"""
path = v.file_name()
if path:
parent, leaf = os.path.split(path)
parent = os.path.basename(parent)
path = os.path.join(parent, leaf)
else:
path = v.name() or str(v.buffer_id())
leaf = v.name() or 'untitled'
status = []
if not v.file_name():
status.append("t")
if v.is_dirty():
status.append("*")
if v.is_read_only():
status.append("r")
if status:
leaf += ' (%s)' % ', '.join(status)
return [leaf, path]
class ExTextCommandBase(sublime_plugin.TextCommand):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def serialize_sel(self):
sels = [(r.a, r.b) for r in list(self.view.sel())]
self.view.settings().set('ex_data', {'prev_sel': sels})
def deserialize_sel(self, name='next_sel'):
return self.view.settings().get('ex_data')[name] or []
def set_sel(self):
sel = self.deserialize_sel()
self.view.sel().clear()
self.view.sel().add_all([sublime.Region(b) for (a, b) in sel])
def set_next_sel(self, data):
self.view.settings().set('ex_data', {'next_sel': data})
def set_mode(self):
state = State(self.view)
state.enter_normal_mode()
self.view.run_command('vi_enter_normal_mode')
def run(self, edit, *args, **kwargs):
self.serialize_sel()
self.run_ex_command(edit, *args, **kwargs)
self.set_sel()
self.set_mode()
class ExGoto(ViWindowCommandBase):
def run(self, command_line):
if not command_line:
# No-op: user issues ':'.
return
parsed = parse_command_line(command_line)
r = parsed.line_range.resolve(self._view)
line_nr = row_at(self._view, r.a) + 1
# TODO: .enter_normal_mode has access to self.state.mode
self.enter_normal_mode(mode=self.state.mode)
self.state.enter_normal_mode()
self.window.run_command('_vi_add_to_jump_list')
self.window.run_command('_vi_go_to_line', {'line': line_nr, 'mode': self.state.mode})
self.window.run_command('_vi_add_to_jump_list')
self._view.show(self._view.sel()[0])
class ExShellOut(sublime_plugin.TextCommand):
"""
Command: :!{cmd}
:!!
http://vimdoc.sourceforge.net/htmldoc/various.html#:!
"""
_last_command = None
@changing_cd
def run(self, edit, command_line=''):
assert command_line, 'expected non-empty command line'
parsed = parse_command_line(command_line)
shell_cmd = parsed.command.command
if shell_cmd == '!':
if not _last_command:
return
shell_cmd = ExShellOut._last_command
# TODO: store only successful commands.
ExShellOut._last_command = shell_cmd
try:
if not parsed.line_range.is_empty:
shell.filter_thru_shell(
view=self.view,
edit=edit,
regions=[parsed.line_range.resolve(self.view)],
cmd=shell_cmd)
else:
# TODO: Read output into output panel.
# shell.run_and_wait(self.view, shell_cmd)
out = shell.run_and_read(self.view, shell_cmd)
output_view = self.view.window().create_output_panel('vi_out')
output_view.settings().set("line_numbers", False)
output_view.settings().set("gutter", False)
output_view.settings().set("scroll_past_end", False)
output_view = self.view.window().create_output_panel('vi_out')
output_view.run_command('append', {'characters': out,
'force': True,
'scroll_to_end': True})
self.view.window().run_command("show_panel", {"panel": "output.vi_out"})
except NotImplementedError:
show_not_implemented()
class ExShell(ViWindowCommandBase):
"""Ex command(s): :shell
Opens a shell at the current view's directory. Sublime Text keeps a virtual
current directory that most of the time will be out of sync with the actual
current directory. The virtual current directory is always set to the
current view's directory, but it isn't accessible through the API.
"""
def open_shell(self, command):
return subprocess.Popen(command, cwd=os.getcwd())
@changing_cd
def run(self, command_line=''):
assert command_line, 'expected non-empty command line'
if sublime.platform() == 'linux':
term = self.view.settings().get('VintageousEx_linux_terminal')
term = term or os.environ.get('COLORTERM') or os.environ.get("TERM")
if not term:
sublime.status_message("Vintageous: Not terminal name found.")
return
try:
self.open_shell([term, '-e', 'bash']).wait()
except Exception as e:
print(e)
sublime.status_message("Vintageous: Error while executing command through shell.")
return
elif sublime.platform() == 'osx':
term = self.view.settings().get('VintageousEx_osx_terminal')
term = term or os.environ.get('COLORTERM') or os.environ.get("TERM")
if not term:
sublime.status_message("Vintageous: Not terminal name found.")
return
try:
self.open_shell([term, '-e', 'bash']).wait()
except Exception as e:
print(e)
sublime.status_message("Vintageous: Error while executing command through shell.")
return
elif sublime.platform() == 'windows':
self.open_shell(['cmd.exe', '/k']).wait()
else:
# XXX OSX (make check explicit)
show_not_implemented()
class ExReadShellOut(sublime_plugin.TextCommand):
'''
Command: :r[ead] [++opt] [name]
:{range}r[ead] [++opt] [name]
:[range]r[ead] !{cmd}
http://vimdoc.sourceforge.net/htmldoc/insert.html#:r
'''
@changing_cd
def run(self, edit, command_line=''):
assert command_line, 'expected non-empty command line'
parsed = parse_command_line(command_line)
r = parsed.line_range.resolve(self.view)
target_point = min(r.end(), self.view.size())
if parsed.command.command:
if sublime.platform() == 'linux':
# TODO: make shell command configurable.
the_shell = self.view.settings().get('linux_shell')
the_shell = the_shell or os.path.expandvars("$SHELL")
if not the_shell:
sublime.status_message("Vintageous: No shell name found.")
return
try:
p = subprocess.Popen([the_shell, '-c', parsed.command.command],
stdout=subprocess.PIPE)
except Exception as e:
print(e)
sublime.status_message("Vintageous: Error while executing command through shell.")
return
self.view.insert(edit, target_point, p.communicate()[0][:-1].decode('utf-8').strip() + '\n')
elif sublime.platform() == 'windows':
p = subprocess.Popen(['cmd.exe', '/C', parsed.command.command],
stdout=subprocess.PIPE,
startupinfo=get_startup_info()
)
cp = 'cp' + get_oem_cp()
rv = p.communicate()[0].decode(cp)[:-2].strip()
self.view.insert(edit, target_point, rv.strip() + '\n')
else:
show_not_implemented()
# Read a file into the current view.
else:
# According to Vim's help, :r should read the current file's content
# if no file name is given, but Vim doesn't do that.
# TODO: implement reading a file into the buffer.
show_not_implemented()
return
class ExPromptSelectOpenFile(ViWindowCommandBase):
'''
Command: :ls[!]
:buffers[!]
:files[!]
http://vimdoc.sourceforge.net/htmldoc/windows.html#:ls
'''
def run(self, command_line=''):
self.file_names = [get_view_info(view) for view in self.window.views()]
self.view_ids = [view.id() for view in self.window.views()]
self.window.show_quick_panel(self.file_names, self.on_done)
def on_done(self, index):
if index == -1:
return
sought_id = self.view_ids[index]
for view in self.window.views():
# TODO: Start looking in current group.
if view.id() == sought_id:
self.window.focus_view(view)
class ExMap(ViWindowCommandBase):
"""
Command: :map {lhs} {rhs}
http://vimdoc.sourceforge.net/htmldoc/map.html#:map
"""
def run(self, command_line=''):
# def run(self, edit, mode=None, count=None, cmd=''):
assert command_line, 'expected non-empty command line'
parsed = parse_command_line(command_line)
if not (parsed.command.keys and parsed.command.command):
show_not_implemented('Showing mappings now implemented')
return
mappings = Mappings(self.state)
mappings.add(modes.NORMAL, parsed.command.keys, parsed.command.command)
mappings.add(modes.OPERATOR_PENDING, parsed.command.keys, parsed.command.command)
mappings.add(modes.VISUAL, parsed.command.keys, parsed.command.command)
class ExUnmap(ViWindowCommandBase):
'''
Command: :unm[ap] {lhs}
http://vimdoc.sourceforge.net/htmldoc/map.html#:unmap
'''
def run(self, command_line=''):
assert command_line, 'expected non-empty command line'
unmap = parse_command_line(command_line)
mappings = Mappings(self.state)
try:
mappings.remove(modes.NORMAL, unmap.command.keys)
mappings.remove(modes.OPERATOR_PENDING, unmap.command.keys)
mappings.remove(modes.VISUAL, unmap.command.keys)
except KeyError:
sublime.status_message('Vintageous: Mapping not found.')
class ExNmap(ViWindowCommandBase):
"""
Command: :nm[ap] {lhs} {rhs}
http://vimdoc.sourceforge.net/htmldoc/map.html#:nmap
"""
def run(self, command_line=''):
assert command_line, 'expected non-empty command line'
nmap_command = parse_command_line(command_line)
keys, command = (nmap_command.command.keys,
nmap_command.command.command)
mappings = Mappings(self.state)
mappings.add(modes.NORMAL, keys, command)
class ExNunmap(ViWindowCommandBase):
"""
Command: :nun[map] {lhs}
http://vimdoc.sourceforge.net/htmldoc/map.html#:nunmap
"""
def run(self, command_line=''):
assert command_line, 'expected non-empty command line'
nunmap_command = parse_command_line(command_line)
mappings = Mappings(self.state)
try:
mappings.remove(modes.NORMAL, nunmap_command.command.keys)
except KeyError:
sublime.status_message('Vintageous: Mapping not found.')
class ExOmap(ViWindowCommandBase):
"""
Command: :om[ap] {lhs} {rhs}
http://vimdoc.sourceforge.net/htmldoc/map.html#:omap
"""
def run(self, command_line=''):
assert command_line, 'expected non-empty command line'
omap_command = parse_command_line(command_line)
keys, command = (omap_command.command.keys,
omap_command.command.command)
mappings = Mappings(self.state)
mappings.add(modes.OPERATOR_PENDING, keys, command)
class ExOunmap(ViWindowCommandBase):
"""
Command: :ou[nmap] {lhs}
http://vimdoc.sourceforge.net/htmldoc/map.html#:ounmap
"""
def run(self, command_line=''):
assert command_line, 'expected non-empty command line'
ounmap_command = parse_command_line(command_line)
mappings = Mappings(self.state)
try:
mappings.remove(modes.OPERATOR_PENDING, ounmap_command.command.keys)
except KeyError:
sublime.status_message('Vintageous: Mapping not found.')
class ExVmap(ViWindowCommandBase):
"""
Command: :vm[ap] {lhs} {rhs}
http://vimdoc.sourceforge.net/htmldoc/map.html#:vmap
"""
def run(self, command_line=''):
assert command_line, 'expected non-empty command line'
vmap_command = parse_command_line(command_line)
keys, command = (vmap_command.command.keys,
vmap_command.command.command)
mappings = Mappings(self.state)
mappings.add(modes.VISUAL, keys, command)
mappings.add(modes.VISUAL_LINE, keys, command)
mappings.add(modes.VISUAL_BLOCK, keys, command)
class ExVunmap(ViWindowCommandBase):
"""
Command: :vu[nmap] {lhs}
http://vimdoc.sourceforge.net/htmldoc/map.html#:vunmap
"""
def run(self, command_line=''):
assert command_line, 'expected non-empty command line'
vunmap_command = parse_command_line(command_line)
mappings = Mappings(self.state)
try:
mappings.remove(modes.VISUAL, vunmap_command.command.keys)
mappings.remove(modes.VISUAL_LINE, vunmap_command.command.keys)
mappings.remove(modes.VISUAL_BLOCK, vunmap_command.command.keys)
except KeyError:
sublime.status_message('Vintageous: Mapping not found.')
class ExAbbreviate(ViWindowCommandBase):
'''
Command: :ab[breviate]
http://vimdoc.sourceforge.net/htmldoc/map.html#:abbreviate
'''
def run(self, command_line=''):
if not command_line:
self.show_abbreviations()
return
parsed = parse_command_line(command_line)
if not (parsed.command.short and parsed.command.full):
show_not_implemented(':abbreviate not fully implemented')
return
abbrev.Store().set(parsed.command.short, parsed.command.full)
def show_abbreviations(self):
abbrevs = ['{0} --> {1}'.format(item['trigger'], item['contents'])
for item in
abbrev.Store().get_all()]
self.window.show_quick_panel(abbrevs,
None, # Simply show the list.
flags=sublime.MONOSPACE_FONT)
class ExUnabbreviate(ViWindowCommandBase):
'''
Command: :una[bbreviate] {lhs}
http://vimdoc.sourceforge.net/htmldoc/map.html#:unabbreviate
'''
def run(self, command_line=''):
assert command_line, 'expected non-empty command line'
parsed = parse_command_line(command_line)
if not parsed.command.short:
return
abbrev.Store().erase(parsed.command.short)
class ExPrintWorkingDir(ViWindowCommandBase):
'''
Command: :pw[d]
http://vimdoc.sourceforge.net/htmldoc/editing.html#:pwd
'''
@changing_cd
def run(self, command_line=''):
assert command_line, 'expected non-empty command line'
show_status(os.getcwd())
class ExWriteFile(ViWindowCommandBase):
'''
Command :w[rite] [++opt]
:w[rite]! [++opt]
:[range]w[rite][!] [++opt]
:[range]w[rite] [++opt] {file}
:[range]w[rite]! [++opt] {file}
:[range]w[rite][!] [++opt] >>
:[range]w[rite][!] [++opt] >> {file}
:[range]w[rite] [++opt] {!cmd}
http://vimdoc.sourceforge.net/htmldoc/editing.html#:write
'''
def check_is_readonly(self, fname):
'''
Returns `True` if @fname is read-only on the filesystem.
@fname
Path to a file.
'''
if not fname:
return
try:
mode = os.stat(fname)
read_only = (stat.S_IMODE(mode.st_mode) & stat.S_IWUSR != stat.S_IWUSR)
except FileNotFoundError:
return
return read_only
@changing_cd
def run(self, command_line=''):
if not command_line:
raise ValueError('empty command line; that seems to be an error')
parsed = parse_command_line(command_line)
if parsed.command.options:
show_not_implemented("++opt isn't implemented for :write")
return
if parsed.command.command:
show_not_implemented('!cmd not implememted for :write')
return
if not self._view:
return
if parsed.command.appends:
self.do_append(parsed)
return
if parsed.command.command:
show_not_implemented("!cmd isn't implemented for :write")
return
if parsed.command.target_file:
self.do_write(parsed)
return
if not self._view.file_name():
show_error(VimError(ERR_NO_FILE_NAME))
return
read_only = (self.check_is_readonly(self._view.file_name())
or self._view.is_read_only())
if read_only and not parsed.command.forced:
utils.blink()
show_error(VimError(ERR_READONLY_FILE))
return
self.window.run_command('save')
def do_append(self, parsed_command):
if parsed_command.command.target_file:
self.do_append_to_file(parsed_command)
return
r = None
if parsed_command.line_range.is_empty:
# If the user didn't provide any range data, Vim appends whe whole buffer.
r = R(0, self._view.size())
else:
r = parsed_command.line_range.resolve(self._view)
text = self._view.substr(r)
text = text if text.startswith('\n') else '\n' + text
location = resolve_insertion_point_at_b(first_sel(self._view))
self._view.run_command('append', {'characters': text})
utils.replace_sel(self._view, R(self._view.line(location).a))
self.enter_normal_mode(mode=self.state.mode)
self.state.enter_normal_mode()
def do_append_to_file(self, parsed_command):
r = None
if parsed_command.line_range.is_empty:
# If the user didn't provide any range data, Vim writes whe whole buffer.
r = R(0, self._view.size())
else:
r = parsed_command.line_range.resolve(self._view)
fname = parsed_command.command.target_file
if not parsed_command.command.forced and not os.path.exists(fname):
show_error(VimError(ERR_CANT_WRITE_FILE))
return
try:
with open(fname, 'at') as f:
text = self._view.substr(r)
f.write(text)
# TODO: make this `show_info` instead.
show_status('Appended to ' + os.path.abspath(fname))
return
except IOError as e:
print('Vintageous: could not write file')
print('Vintageous ============')
print(e)
print('=======================')
return
def do_write(self, ex_command):
fname = ex_command.command.target_file
if not ex_command.command.forced:
if os.path.exists(fname):
utils.blink()
show_error(VimError(ERR_FILE_EXISTS))
return
if self.check_is_readonly(fname):
utils.blink()
show_error(VimError(ERR_READONLY_FILE))
return
region = None
if ex_command.line_range.is_empty:
# If the user didn't provide any range data, Vim writes whe whole buffer.
region = R(0, self._view.size())
else:
region = ex_command.line_range.resolve(self._view)
assert region is not None, "range cannot be None"
try:
expanded_path = os.path.expandvars(os.path.expanduser(fname))
expanded_path = os.path.abspath(expanded_path)
with open(expanded_path, 'wt') as f:
text = self._view.substr(region)
f.write(text)
# FIXME: Does this do what we think it does?
self._view.retarget(expanded_path)
self.window.run_command('save')
except IOError as e:
# TODO: Add logging.
show_error(VimError(ERR_CANT_WRITE_FILE))
print('Vintageous ==============================================')
print (e)
print('=========================================================')
class ExWriteAll(ViWindowCommandBase):
'''
Commmand: :wa[ll][!]
http://vimdoc.sourceforge.net/htmldoc/editing.html#:wa
'''
@changing_cd
def run(self, command_line=''):
assert command_line, 'expected non-empty command line'
parsed = parse_command_line(command_line)
forced = parsed.command.forced
# TODO: read-only views don't get properly saved.
for v in (v for v in self.window.views() if v.file_name()):
if v.is_read_only() and not forced:
continue
v.run_command('save')
class ExFile(ViWindowCommandBase):
'''
Command: :f[file][!]
http://vimdoc.sourceforge.net/htmldoc/editing.html#:file
'''
def run(self, command_line=''):
# XXX figure out what the right params are. vim's help seems to be
# wrong
if self._view.file_name():
fname = self._view.file_name()
else:
fname = 'untitled'
attrs = ''
if self._view.is_read_only():
attrs = 'readonly'
if self._view.is_dirty():
attrs = 'modified'
lines = 'no lines in the buffer'
if self._view.rowcol(self._view.size())[0]:
lines = self._view.rowcol(self._view.size())[0] + 1
# fixme: doesn't calculate the buffer's % correctly
if not isinstance(lines, str):
vr = self._view.visible_region()
start_row, end_row = self._view.rowcol(vr.begin())[0], \
self._view.rowcol(vr.end())[0]
mid = (start_row + end_row + 2) / 2
percent = float(mid) / lines * 100.0
msg = fname
if attrs:
msg += " [%s]" % attrs
if isinstance(lines, str):
msg += " -- %s --" % lines
else:
msg += " %d line(s) --%d%%--" % (lines, int(percent))
sublime.status_message('Vintageous: %s' % msg)
class ExMove(ExTextCommandBase):
'''
Command: :[range]m[ove] {address}
http://vimdoc.sourceforge.net/htmldoc/change.html#:move
'''
def run_ex_command(self, edit, command_line=''):
assert command_line, 'expected non-empty command line'
move_command = parse_command_line(command_line)
if move_command.command.address is None:
show_error(VimError(ERR_INVALID_ADDRESS))
return
source = move_command.line_range.resolve(self.view)
if any(s.contains(source) for s in self.view.sel()):
show_error(VimError(ERR_CANT_MOVE_LINES_ONTO_THEMSELVES))
return
destination = move_command.command.address.resolve(self.view)
if destination == source:
return
text = self.view.substr(source)
if destination.end() >= self.view.size():
text = '\n' + text.rstrip()
if destination == R(-1):
destination = R(0)
if destination.end() < source.begin():
self.view.erase(edit, source)
self.view.insert(edit, destination.end(), text)
self.set_next_sel([[destination.a, destination.b]])
return
self.view.insert(edit, destination.end(), text)
self.view.erase(edit, source)
self.set_next_sel([[destination.a, destination.a]])
class ExCopy(ExTextCommandBase):
'''
Command: :[range]co[py] {address}
http://vimdoc.sourceforge.net/htmldoc/change.html#:copy
'''
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def run_ex_command(self, edit, command_line=''):
assert command_line, 'expected non-empty command line'
parsed = parse_command_line(command_line)
unresolved = parsed.command.calculate_address()
if unresolved is None:
show_error(VimError(ERR_INVALID_ADDRESS))
return
# TODO: how do we signal row 0?
target_region = unresolved.resolve(self.view)
address = None
if target_region == R(-1, -1):
address = 0
else:
row = utils.row_at(self.view, target_region.begin()) + 1
address = self.view.text_point(row, 0)
source = parsed.line_range.resolve(self.view)
text = self.view.substr(source)
if address >= self.view.size():
address = self.view.size()
text = '\n' + text[:-1]
self.view.insert(edit, address, text)
cursor_dest = self.view.line(address + len(text) - 1).begin()
self.set_next_sel([(cursor_dest, cursor_dest)])
class ExOnly(ViWindowCommandBase):
"""
Command: :on[ly][!]
http://vimdoc.sourceforge.net/htmldoc/windows.html#:only
"""
def run(self, command_line=''):
if not command_line:
raise ValueError('empty command line; that seems wrong')
parsed = parse_command_line(command_line)
if not parsed.command.forced and has_dirty_buffers(self.window):
show_error(VimError(ERR_OTHER_BUFFER_HAS_CHANGES))
return
current_id = self._view.id()
for view in self.window.views():
if view.id() == current_id:
continue
if view.is_dirty():
view.set_scratch(True)
view.close()
class ExDoubleAmpersand(ViWindowCommandBase):
'''
Command: :[range]&[&][flags] [count]
http://vimdoc.sourceforge.net/htmldoc/change.html#:&
'''
def run(self, command_line=''):
assert command_line, 'expected non-empty command line'
parsed = parse_command_line(command_line)
new_command_line = '{0}substitute///{1} {2}'.format(
str(parsed.line_range),
''.join(parsed.command.params['flags']),
parsed.command.params['count'],
)
self.window.run_command('ex_substitute', {
'command_line': new_command_line.strip()
})
class ExSubstitute(sublime_plugin.TextCommand):
'''
Command :s[ubstitute]
http://vimdoc.sourceforge.net/htmldoc/change.html#:substitute
'''
last_pattern = None
last_flags = []
last_replacement = ''
def run(self, edit, command_line=''):
if not command_line:
raise ValueError('no command line passed; that seems wrong')
# ST commands only accept Json-encoded parameters.
# We parse the command line again because the alternative is to
# serialize the parsed command line before calling this command.
# Parsing twice seems simpler.
parsed = parse_command_line(command_line)
pattern = parsed.command.pattern
replacement = parsed.command.replacement
count = parsed.command.count
flags = parsed.command.flags
# :s
if not pattern:
pattern = ExSubstitute.last_pattern
replacement = ExSubstitute.last_replacement
# TODO: Don't we have to reuse the previous flags?
flags = []
count = 0
if not pattern:
sublime.status_message("Vintageous: no previous pattern available")
print("Vintageous: no previous pattern available")
return
ExSubstitute.last_pattern = pattern
ExSubstitute.last_replacement = replacement
ExSubstitute.last_flags = flags
computed_flags = 0
computed_flags |= re.IGNORECASE if ('i' in flags) else 0
try:
compiled_rx = re.compile(pattern, flags=computed_flags)
except Exception as e:
sublime.status_message(
"Vintageous: bad pattern '%s'" % (e.message, pattern))
print("Vintageous [regex error]: %s ... in pattern '%s'"
% (e.message, pattern))
return
# TODO: Implement 'count'
replace_count = 0 if (flags and 'g' in flags) else 1
target_region = parsed.line_range.resolve(self.view)
if 'c' in flags:
self.replace_confirming(edit, pattern, compiled_rx, replacement, replace_count, target_region)
return
line_text = self.view.substr(target_region)
new_text = re.sub(compiled_rx, replacement, line_text, count=replace_count)
self.view.replace(edit, target_region, new_text)
def replace_confirming(self, edit, pattern, compiled_rx, replacement,
replace_count, target_region):
last_row = row_at(self.view, target_region.b - 1)
start = target_region.begin()
while True:
match = self.view.find(pattern, start)
# no match or match out of range -- stop
if (match == R(-1)) or (row_at(self.view, match.a) > last_row):
self.view.show(first_sel(self.view).begin())
return
size_before = self.view.size()
with adding_regions(self.view, 's_confirm', [match], 'comment'):
self.view.show(match.a, True)
if sublime.ok_cancel_dialog("Confirm replacement?"):
text = self.view.substr(match)
substituted = re.sub(compiled_rx, replacement, text, count=replace_count)
self.view.replace(edit, match, substituted)
start = match.b + (self.view.size() - size_before)
class ExDelete(ExTextCommandBase):
'''
Command: :[range]d[elete] [x]
:[range]d[elete] [x] {count}
http://vimdoc.sourceforge.net/htmldoc/change.html#:delete
'''