-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathvimode.py
executable file
·2247 lines (1970 loc) · 81.8 KB
/
vimode.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
# -*- coding: utf-8 -*-
#
# Copyright (C) 2013-2014 Germain Z. <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#
# Add vi/vim-like modes to WeeChat.
#
from abc import ABCMeta, abstractproperty
from contextlib import contextmanager
import csv
import enum
import functools
import json
import os
import re
import subprocess
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
import sys
import time
import weechat
# Script info.
# ============
SCRIPT_NAME = "vimode"
SCRIPT_AUTHOR = "GermainZ <[email protected]>"
SCRIPT_VERSION = "0.8"
SCRIPT_LICENSE = "GPL3"
SCRIPT_DESC = ("Add vi/vim-like modes and keybindings to WeeChat.")
# Global variables.
# =================
# General.
# --------
# Halp! Halp! Halp!
GITHUB_BASE = "https://github.com/GermainZ/weechat-vimode/blob/master/"
README_URL = GITHUB_BASE + "README.md"
FAQ_KEYBINDINGS = GITHUB_BASE + "FAQ.md#problematic-key-bindings"
FAQ_ESC = GITHUB_BASE + "FAQ.md#esc-key-not-being-detected-instantly"
# Holds the text of the tab-completions for the command-line mode.
cmd_compl_text = ""
# Holds the original text of the command-line mode, used for completion.
cmd_text_orig = None
# Index of current suggestion, used for completion.
cmd_compl_pos = 0
# Used for command-line mode history.
cmd_history = []
cmd_history_index = 0
# Used to store the content of the input line when going into COMMAND mode.
input_line_backup = {}
# Mode we're in. One of INSERT, NORMAL, REPLACE, COMMAND or SEARCH.
# SEARCH is only used if search_vim is enabled.
mode = "INSERT"
# Holds normal commands (e.g. "dd").
vi_buffer = ""
# See `cb_key_combo_default()`.
esc_pressed = 0
# See `cb_key_pressed()`.
last_signal_time = 0
# See `start_catching_keys()` for more info.
catching_keys_data = {'amount': 0}
# Used for ; and , to store the last f/F/t/T motion.
last_search_motion = {'motion': None, 'data': None}
# Used for undo history.
undo_history = {}
undo_history_index = {}
# Holds mode colors (loaded from vimode_settings).
mode_colors = {}
# Script options.
vimode_settings = {
'no_warn': ("off", ("don't warn about problematic keybindings and "
"tmux/screen")),
'copy_clipboard_cmd': ("xclip -selection c",
("command used to copy to clipboard; must read "
"input from stdin")),
'paste_clipboard_cmd': ("xclip -selection c -o",
("command used to paste clipboard; must output "
"content to stdout")),
'imap_esc': ("", ("use alternate mapping to enter Normal mode while in "
"Insert mode; having it set to 'jk' is similar to "
"`:imap jk <Esc>` in vim")),
'user_command_mapping': (":", ("user alternate mapping to enter Command mode while in "
"Normal mode")),
'imap_esc_timeout': ("1000", ("time in ms to wait for the imap_esc "
"sequence to complete")),
'search_vim': ("off", ("allow n/N usage after searching (requires an extra"
" <Enter> to return to normal mode)")),
'user_mappings': ("", ("see the `:nmap` command in the README for more "
"info; please do not modify this field manually "
"unless you know what you're doing")),
'user_mappings_noremap': ("", ("see the `:nnoremap` command in the README "
"for more info; please do not modify this field "
"manually unless you know what you're doing")),
'mode_indicator_prefix': ("", "prefix for the bar item mode_indicator"),
'mode_indicator_suffix': ("", "suffix for the bar item mode_indicator"),
'mode_indicator_normal_color': ("white",
"color for mode indicator in Normal mode"),
'mode_indicator_normal_color_bg': ("gray",
("background color for mode indicator "
"in Normal mode")),
'mode_indicator_insert_color': ("white",
"color for mode indicator in Insert mode"),
'mode_indicator_insert_color_bg': ("blue",
("background color for mode indicator "
"in Insert mode")),
'mode_indicator_replace_color': ("white",
("color for mode indicator in Replace "
"mode")),
'mode_indicator_replace_color_bg': ("red",
("background color for mode indicator "
"in Replace mode")),
'mode_indicator_cmd_color': ("white",
"color for mode indicator in Command mode"),
'mode_indicator_cmd_color_bg': ("cyan",
("background color for mode indicator in "
"Command mode")),
'mode_indicator_search_color': ("white",
"color for mode indicator in Search mode"),
'mode_indicator_search_color_bg': ("magenta",
("background color for mode indicator "
"in Search mode")),
'line_number_prefix': ("", "prefix for line numbers"),
'line_number_suffix': (" ", "suffix for line numbers"),
'is_keyword': ("a-zA-Z0-9_À-ÿ", "characters recognized as part of a word")
}
# Regex patterns.
# ---------------
WHITESPACE = re.compile(r"\s")
REGEX_MOTION_UPPERCASE_W = re.compile(r"(?<=\s)\S")
REGEX_MOTION_UPPERCASE_E = re.compile(r"\S(?!\S)")
REGEX_MOTION_UPPERCASE_B = REGEX_MOTION_UPPERCASE_E
REGEX_MOTION_G_UPPERCASE_E = REGEX_MOTION_UPPERCASE_W
REGEX_MOTION_CARRET = re.compile(r"\S")
REGEX_INT = r"[0-9]"
keyword_regexes = {} # Loaded on runtime (uses the is_keyword config option).
REGEX_MAP_KEYS_1 = {
re.compile("<([^>]*-)Left>", re.IGNORECASE): '<\\1\x01[[D>',
re.compile("<([^>]*-)Right>", re.IGNORECASE): '<\\1\x01[[C>',
re.compile("<([^>]*-)Up>", re.IGNORECASE): '<\\1\x01[[A>',
re.compile("<([^>]*-)Down>", re.IGNORECASE): '<\\1\x01[[B>',
re.compile("<Left>", re.IGNORECASE): '\x01[[D',
re.compile("<Right>", re.IGNORECASE): '\x01[[C',
re.compile("<Up>", re.IGNORECASE): '\x01[[A',
re.compile("<Down>", re.IGNORECASE): '\x01[[B'
}
REGEX_MAP_KEYS_2 = {
# Python's regex doesn't support \U1, but we're using a simple hack when
# replacing to fix this.
re.compile(r"<C-([^>]*)>", re.IGNORECASE): '\x01\\U1',
re.compile(r"<M-([^>]*)>", re.IGNORECASE): '\x01[\\1'
}
# Regex used to detect problematic keybindings.
# For example: meta-wmeta-s is bound by default to ``/window swap``.
# If the user pressed Esc-w, WeeChat will detect it as meta-w and will not
# send any signal to `cb_key_combo_default()` just yet, since it's the
# beginning of a known key combo.
# Instead, `cb_key_combo_default()` will receive the Esc-ws signal, which
# becomes "ws" after removing the Esc part, and won't know how to handle it.
REGEX_PROBLEMATIC_KEYBINDINGS = re.compile(r"meta-\w(meta|ctrl)")
class Mapping(enum.Enum):
RECURSIVE = "user_mappings"
NON_RECURSIVE = "user_mappings_noremap"
# Vi commands.
# ------------
def add_mapping(args, which):
"""Add a user-defined key mapping.
`which` is a Mapping type, either Mapping.RECURSIVE for `:nmap` or
Mapping.NON_RECURSIVE for `:nnoremap`).
Some (but not all) vim-like key codes are supported to simplify things for
the user: <Up>, <Down>, <Left>, <Right>, <C-...> and <M-...>.
See Also:
`cmd_unmap()`.
"""
args = args.lstrip()
if not args:
mappings = vimode_settings[which.value]
if mappings:
cmd = ':nnoremap' if which == Mapping.NON_RECURSIVE else ':nmap'
title = "----- Vimode User Mappings ({}) -----".format(cmd)
bar = '-' * len(title)
weechat.prnt("", bar)
weechat.prnt("", title)
weechat.prnt("", bar)
for keys, mapping in sorted(mappings.items(),
key=lambda x: x[0].lower()):
pretty_keys = keys
for pttrn, repl in [(r'\u0001([A-Z])', r'<C-\1>'),
(r'\u0001\[([A-Z])', r'<M-\1>'),
(r'\u0001\[\[A', r'<Up>'),
(r'\u0001\[\[B', r'<Down>'),
(r'\u0001\[\[C', r'<Right>'),
(r'\u0001\[\[D', r'<Left>'),
('"', '\\"')]:
pretty_keys = re.sub(pttrn, repl, pretty_keys)
pretty_mapping = mapping
for pttrn, repl in [('"', '\\"')]:
pretty_mapping = re.sub(pttrn, repl, pretty_mapping)
msg_fmt = '("{}", "{}")'
weechat.prnt("", msg_fmt.format(pretty_keys, pretty_mapping))
else:
weechat.prnt("", "nmap: no mapping found.")
elif " " not in args:
weechat.prnt("", "nmap syntax -> :nmap {lhs} {rhs}")
else:
key, mapping = args.split(" ", 1)
# First pass of replacements. We perform two passes as a simple way to
# avoid incorrect replacements due to dictionaries not being
# insertion-ordered prior to Python 3.7.
for regex, repl in REGEX_MAP_KEYS_1.items():
key = regex.sub(repl, key)
mapping = regex.sub(repl, mapping)
# Second pass of replacements.
for regex, repl in REGEX_MAP_KEYS_2.items():
if '\\U' in repl: # Hack, but works well for our simple case.
repl = repl.replace('\\U', '\\')
key = regex.sub(lambda pat: pat.expand(repl).lower(), key)
else:
key = regex.sub(repl, key)
mapping = regex.sub(repl, mapping)
vimode_settings[which.value][key] = mapping
weechat.config_set_plugin(which.value, json.dumps(vimode_settings[which.value]))
def cmd_nmap(args):
"""Add a user-defined key mapping."""
add_mapping(args, Mapping.RECURSIVE)
def cmd_nnoremap(args):
"""Add a user-defined key mapping, without following user mappings."""
add_mapping(args, Mapping.NON_RECURSIVE)
def cmd_nunmap(args):
"""Remove a user-defined key mapping.
See Also:
`cmd_map()`.
"""
args = args.strip()
if not args:
weechat.prnt("", "nunmap syntax -> :unmap {lhs}")
else:
key = args
for regex, repl in REGEX_MAP_KEYS_1.items():
key = regex.sub(repl, key)
for regex, repl in REGEX_MAP_KEYS_2.items():
if '\\U' in repl: # Hack, but works well for our simple case.
repl = repl.replace('\\U', '\\')
key = regex.sub(lambda pat: pat.expand(repl).upper(), key)
else:
key = regex.sub(repl, key)
found = False
for setting in ['user_mappings', 'user_mappings_noremap']:
mappings = vimode_settings[setting]
if key in mappings:
found = True
del mappings[key]
del VI_KEYS[key]
# restore default keys
if key in VI_DEFAULT_KEYS:
VI_KEYS[key] = VI_DEFAULT_KEYS[key]
weechat.config_set_plugin(setting, json.dumps(mappings))
vimode_settings[setting] = mappings
if not found:
weechat.prnt("", "nunmap: No such mapping")
# See Also: `cb_exec_cmd()`.
VI_COMMAND_GROUPS = {('h', 'help'): "/help",
('qa', 'qall', 'quita', 'quitall'): "/exit",
('q', 'quit'): "/close",
('w', 'write'): "/save",
('bN', 'bNext', 'bp', 'bprevious'): "/buffer -1",
('bn', 'bnext'): "/buffer +1",
('bd', 'bdel', 'bdelete'): "/close",
('b#',): "/input jump_last_buffer_displayed",
('b', 'bu', 'buf', 'buffer'): "/buffer",
('sp', 'split'): "/window splith",
('vs', 'vsplit'): "/window splitv",
('nm', 'nmap'): cmd_nmap,
('nn', 'nnoremap'): cmd_nnoremap,
('nun', 'nunmap'): cmd_nunmap}
VI_COMMANDS = dict()
for T, v in VI_COMMAND_GROUPS.items():
VI_COMMANDS.update(dict.fromkeys(T, v))
# Vi operators.
# -------------
# Each operator must have a corresponding function, called "operator_X" where
# X is the operator. For example: `operator_c()`.
VI_OPERATORS = ["c", "d", "y"]
# Vi motions.
# -----------
# Vi motions. Each motion must have a corresponding function, called
# "motion_X" where X is the motion (e.g. `motion_w()`).
# See Also: `SPECIAL_CHARS`.
VI_MOTIONS = ["w", "e", "b", "^", "$", "h", "l", "W", "E", "B", "f", "F", "t",
"T", "ge", "gE", "0", "iw"]
# Special characters for motions. The corresponding function's name is
# converted before calling. For example, "^" will call `motion_carret` instead
# of `motion_^` (which isn't allowed because of illegal characters).
SPECIAL_CHARS = {'^': "carret",
'$': "dollar"}
# Methods for vi operators, motions and key bindings.
# ===================================================
# Documented base examples:
# -------------------------
def operator_base(buf, input_line, pos1, pos2, overwrite):
"""Operator method example.
Args:
buf (str): pointer to the current WeeChat buffer.
input_line (str): the content of the input line.
pos1 (int): the starting position of the motion.
pos2 (int): the ending position of the motion.
overwrite (bool, optional): whether the character at the cursor's new
position should be overwritten or not (for inclusive motions).
Defaults to False.
Notes:
Should be called "operator_X", where X is the operator, and defined in
`VI_OPERATORS`.
Must perform actions (e.g. modifying the input line) on its own,
using the WeeChat API.
See Also:
For additional examples, see `operator_d()` and
`operator_y()`.
"""
# Get start and end positions.
start = min(pos1, pos2)
end = max(pos1, pos2)
# Print the text the operator should go over.
weechat.prnt("", "Selection: %s" % input_line[start:end])
def motion_base(input_line, cur, count):
"""Motion method example.
Args:
input_line (str): the content of the input line.
cur (int): the position of the cursor.
count (int): the amount of times to multiply or iterate the action.
Returns:
A tuple containing four values:
int: the starting position of the selection. Usually the cursor's
position.
int: the ending position of the motion.
bool: True if the motion is inclusive, False otherwise.
bool: True if the motion is catching, False otherwise.
See `start_catching_keys()` for more info on catching motions.
Notes:
Should be called "motion_X", where X is the motion, and defined in
`VI_MOTIONS`.
Must not modify the input line directly.
See Also:
For additional examples, see `motion_w()` (normal motion) and
`motion_f()` (catching motion).
"""
# Find (relative to cur) position of next number.
pos = get_pos(input_line, REGEX_INT, cur, True, count)
# Return the new (absolute) cursor position.
# This motion is exclusive, so overwrite is False.
return cur, cur + pos, False, False
def key_base(buf, input_line, cur, count):
"""Key method example.
Args:
buf (str): pointer to the current WeeChat buffer.
input_line (str): the content of the input line.
cur (int): the position of the cursor.
count (int): the amount of times to multiply or iterate the action.
Notes:
Should be called `key_X`, where X represents the key(s), and defined
in `VI_KEYS`.
Must perform actions on its own (using the WeeChat API).
See Also:
For additional examples, see `key_a()` (normal key) and
`key_r()` (catching key).
"""
# Key was pressed. Go to Insert mode (similar to "i").
set_mode("INSERT")
# Operators:
# ----------
def operator_d(buf, input_line, pos1, pos2, overwrite=False):
"""Delete text from `pos1` to `pos2` from the input line.
If `overwrite` is set to True, the character at the cursor's new position
is removed as well (the motion is inclusive).
See Also:
`operator_base()`.
"""
start = min(pos1, pos2)
end = max(pos1, pos2)
if overwrite:
end += 1
input_line = list(input_line)
del input_line[start:end]
input_line = "".join(input_line)
weechat.buffer_set(buf, "input", input_line)
set_cur(buf, input_line, pos2)
def operator_c(buf, input_line, pos1, pos2, overwrite=False):
"""Delete text from `pos1` to `pos2` from the input and enter Insert mode.
If `overwrite` is set to True, the character at the cursor's new position
is removed as well (the motion is inclusive.)
See Also:
`operator_base()`.
"""
operator_d(buf, input_line, pos1, pos2, overwrite)
set_mode("INSERT")
set_cur(buf, input_line, pos1)
def operator_y(buf, input_line, pos1, pos2, _):
"""Yank text from `pos1` to `pos2` from the input line.
See Also:
`operator_base()`.
"""
start = min(pos1, pos2)
end = max(pos1, pos2)
cmd = vimode_settings['copy_clipboard_cmd']
proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE)
if sys.version_info > (3,):
proc.communicate(input=input_line[start:end].encode())
else:
proc.communicate(input=input_line[start:end])
# Motions:
# --------
def motion_0(input_line, cur, count):
"""Go to the first character of the line.
See Also;
`motion_base()`.
"""
return cur, 0, False, False
def motion_w(input_line, cur, count):
"""Go `count` words forward and return position.
See Also:
`motion_base()`.
"""
pos = get_pos(input_line, keyword_regexes['w'], cur, True, count)
if pos == -1:
return cur, len(input_line), False, False
return cur, cur + pos, False, False
def motion_W(input_line, cur, count):
"""Go `count` WORDS forward and return position.
See Also:
`motion_base()`.
"""
pos = get_pos(input_line, REGEX_MOTION_UPPERCASE_W, cur, True, count)
if pos == -1:
return cur, len(input_line), False, False
return cur, cur + pos, False, False
def motion_e(input_line, cur, count):
"""Go to the end of `count` words and return position.
See Also:
`motion_base()`.
"""
pos = get_pos(input_line, keyword_regexes['e'], cur, True, count)
if pos == -1:
return cur, len(input_line), True, False
return cur, cur + pos, True, False
def motion_E(input_line, cur, count):
"""Go to the end of `count` WORDS and return cusor position.
See Also:
`motion_base()`.
"""
pos = get_pos(input_line, REGEX_MOTION_UPPERCASE_E, cur, True, count)
if pos == -1:
return cur, len(input_line), False, False
return cur, cur + pos, True, False
def motion_b(input_line, cur, count):
"""Go `count` words backwards and return position.
See Also:
`motion_base()`.
"""
# "b" is just "e" on inverted data (e.g. "olleH" instead of "Hello").
pos_inv = motion_e(input_line[::-1], len(input_line) - cur - 1, count)[1]
pos = len(input_line) - pos_inv - 1
return cur, max(0, pos), True, False
def motion_B(input_line, cur, count):
"""Go `count` WORDS backwards and return position.
See Also:
`motion_base()`.
"""
new_cur = len(input_line) - cur
pos = get_pos(input_line[::-1], REGEX_MOTION_UPPERCASE_B, new_cur,
count=count)
if pos == -1:
return cur, 0, False, False
pos = len(input_line) - (pos + new_cur + 1)
return cur, pos, True, False
def motion_ge(input_line, cur, count):
"""Go to end of `count` words backwards and return position.
See Also:
`motion_base()`.
"""
# "ge is just "w" on inverted data (e.g. "olleH" instead of "Hello").
pos_inv = motion_w(input_line[::-1], len(input_line) - cur - 1, count)[1]
pos = len(input_line) - pos_inv - 1
return cur, pos, True, False
def motion_gE(input_line, cur, count):
"""Go to end of `count` WORDS backwards and return position.
See Also:
`motion_base()`.
"""
new_cur = len(input_line) - cur - 1
pos = get_pos(input_line[::-1], REGEX_MOTION_G_UPPERCASE_E, new_cur,
True, count)
if pos == -1:
return cur, 0, False, False
pos = len(input_line) - (pos + new_cur + 1)
return cur, pos, True, False
def motion_h(input_line, cur, count):
"""Go `count` characters to the left and return position.
See Also:
`motion_base()`.
"""
return cur, max(0, cur - max(count, 1)), False, False
def motion_l(input_line, cur, count):
"""Go `count` characters to the right and return position.
See Also:
`motion_base()`.
"""
return cur, cur + max(count, 1), False, False
def motion_carret(input_line, cur, count):
"""Go to first non-blank character of line and return position.
See Also:
`motion_base()`.
"""
pos = get_pos(input_line, REGEX_MOTION_CARRET, 0)
return cur, pos, False, False
def motion_dollar(input_line, cur, count):
"""Go to end of line and return position.
See Also:
`motion_base()`.
"""
pos = len(input_line)
return cur, pos, False, False
def motion_iw(input_line, cur, count):
"""Select `count` inner words, returning starting/ending positions.
See Also:
`motion_base()`.
"""
pos_inv = get_pos(input_line[::-1], keyword_regexes['iw'],
len(input_line) - cur - 1, False, 1)
start_pos = cur - pos_inv
end_pos = start_pos + get_pos(input_line, keyword_regexes['iw'],
start_pos, False, count)
return start_pos, end_pos, True, False
def motion_f(input_line, cur, count):
"""Go to `count`'th occurence of character and return position.
See Also:
`motion_base()`.
"""
return start_catching_keys(1, "cb_motion_f", input_line, cur, count)
def cb_motion_f(update_last=True):
"""Callback for `motion_f()`.
Args:
update_last (bool, optional): should `last_search_motion` be updated?
Set to False when calling from `key_semicolon()` or `key_comma()`
so that the last search motion isn't overwritten.
Defaults to True.
See Also:
`start_catching_keys()`.
"""
global last_search_motion
pattern = catching_keys_data['keys']
pos = get_pos(catching_keys_data['input_line'], re.escape(pattern),
catching_keys_data['cur'], True,
catching_keys_data['count'])
catching_keys_data['new_cur'] = max(0, pos) + catching_keys_data['cur']
if update_last:
last_search_motion = {'motion': "f", 'data': pattern}
cb_key_combo_default(None, None, "")
def motion_F(input_line, cur, count):
"""Go to `count`'th occurence of char to the right and return position.
See Also:
`motion_base()`.
"""
return start_catching_keys(1, "cb_motion_F", input_line, cur, count)
def cb_motion_F(update_last=True):
"""Callback for `motion_F()`.
Args:
update_last (bool, optional): should `last_search_motion` be updated?
Set to False when calling from `key_semicolon()` or `key_comma()`
so that the last search motion isn't overwritten.
Defaults to True.
See Also:
`start_catching_keys()`.
"""
global last_search_motion
pattern = catching_keys_data['keys']
cur = len(catching_keys_data['input_line']) - catching_keys_data['cur']
pos = get_pos(catching_keys_data['input_line'][::-1],
re.escape(pattern),
cur,
False,
catching_keys_data['count'])
catching_keys_data['new_cur'] = catching_keys_data['cur'] - max(0, pos + 1)
if update_last:
last_search_motion = {'motion': "F", 'data': pattern}
cb_key_combo_default(None, None, "")
def motion_t(input_line, cur, count):
"""Go to `count`'th occurence of char and return position.
The position returned is the position of the character to the left of char.
See Also:
`motion_base()`.
"""
return start_catching_keys(1, "cb_motion_t", input_line, cur, count)
def cb_motion_t(update_last=True):
"""Callback for `motion_t()`.
Args:
update_last (bool, optional): should `last_search_motion` be updated?
Set to False when calling from `key_semicolon()` or `key_comma()`
so that the last search motion isn't overwritten.
Defaults to True.
See Also:
`start_catching_keys()`.
"""
global last_search_motion
pattern = catching_keys_data['keys']
pos = get_pos(catching_keys_data['input_line'], re.escape(pattern),
catching_keys_data['cur'] + 1,
True, catching_keys_data['count'])
pos += 1
if pos > 0:
catching_keys_data['new_cur'] = pos + catching_keys_data['cur'] - 1
else:
catching_keys_data['new_cur'] = catching_keys_data['cur']
if update_last:
last_search_motion = {'motion': "t", 'data': pattern}
cb_key_combo_default(None, None, "")
def motion_T(input_line, cur, count):
"""Go to `count`'th occurence of char to the left and return position.
The position returned is the position of the character to the right of
char.
See Also:
`motion_base()`.
"""
return start_catching_keys(1, "cb_motion_T", input_line, cur, count)
def cb_motion_T(update_last=True):
"""Callback for `motion_T()`.
Args:
update_last (bool, optional): should `last_search_motion` be updated?
Set to False when calling from `key_semicolon()` or `key_comma()`
so that the last search motion isn't overwritten.
Defaults to True.
See Also:
`start_catching_keys()`.
"""
global last_search_motion
pattern = catching_keys_data['keys']
pos = get_pos(catching_keys_data['input_line'][::-1], re.escape(pattern),
(len(catching_keys_data['input_line']) -
(catching_keys_data['cur'] + 1)) + 1,
True, catching_keys_data['count'])
pos += 1
if pos > 0:
catching_keys_data['new_cur'] = catching_keys_data['cur'] - pos + 1
else:
catching_keys_data['new_cur'] = catching_keys_data['cur']
if update_last:
last_search_motion = {'motion': "T", 'data': pattern}
cb_key_combo_default(None, None, "")
# Keys:
# -----
def key_cc(buf, input_line, cur, count):
"""Delete line and start Insert mode.
See Also:
`key_base()`.
"""
weechat.command("", "/input delete_line")
set_mode("INSERT")
def key_C(buf, input_line, cur, count):
"""Delete from cursor to end of line and start Insert mode.
See Also:
`key_base()`.
"""
weechat.command("", "/input delete_end_of_line")
set_mode("INSERT")
def key_yy(buf, input_line, cur, count):
"""Yank line.
See Also:
`key_base()`.
"""
cmd = vimode_settings['copy_clipboard_cmd']
proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE)
if sys.version_info > (3,):
proc.communicate(input=input_line.encode())
else:
proc.communicate(input=input_line)
def key_p(buf, input_line, cur, count):
"""Paste text.
See Also:
`key_base()`.
"""
cmd = vimode_settings['paste_clipboard_cmd']
weechat.hook_process(cmd, 10 * 1000, "cb_key_p", weechat.current_buffer())
def cb_key_p(data, command, return_code, output, err):
"""Callback for fetching clipboard text and pasting it."""
buf = ""
this_buffer = data
if output != "":
buf += output.strip()
if return_code == 0:
my_input = weechat.buffer_get_string(this_buffer, "input")
pos = weechat.buffer_get_integer(this_buffer, "input_pos") + 1
my_input = my_input[:pos] + buf + my_input[pos:]
pos += len(buf)
weechat.buffer_set(this_buffer, "input", my_input)
weechat.buffer_set(this_buffer, "input_pos", str(pos))
return weechat.WEECHAT_RC_OK
def key_i(buf, input_line, cur, count):
"""Start Insert mode.
See Also:
`key_base()`.
"""
set_mode("INSERT")
def key_a(buf, input_line, cur, count):
"""Move cursor one character to the right and start Insert mode.
See Also:
`key_base()`.
"""
set_cur(buf, input_line, cur + 1, False)
set_mode("INSERT")
def key_A(buf, input_line, cur, count):
"""Move cursor to end of line and start Insert mode.
See Also:
`key_base()`.
"""
set_cur(buf, input_line, len(input_line), False)
set_mode("INSERT")
def key_I(buf, input_line, cur, count):
"""Move cursor to first non-blank character and start Insert mode.
See Also:
`key_base()`.
"""
_, pos, _, _ = motion_carret(input_line, cur, 0)
set_cur(buf, input_line, pos)
set_mode("INSERT")
def key_G(buf, input_line, cur, count):
"""Scroll to specified line or bottom of buffer.
See Also:
`key_base()`.
"""
if count > 0:
# This is necessary to prevent weird scroll jumps.
weechat.command("", "/window scroll_top")
weechat.command("", "/window scroll %s" % (count - 1))
else:
weechat.command("", "/window scroll_bottom")
def key_r(buf, input_line, cur, count):
"""Replace `count` characters under the cursor.
See Also:
`key_base()`.
"""
start_catching_keys(1, "cb_key_r", input_line, cur, count, buf)
def cb_key_r():
"""Callback for `key_r()`.
See Also:
`start_catching_keys()`.
"""
global catching_keys_data
input_line = list(catching_keys_data['input_line'])
count = max(catching_keys_data['count'], 1)
cur = catching_keys_data['cur']
if cur + count <= len(input_line):
for _ in range(count):
input_line[cur] = catching_keys_data['keys']
cur += 1
input_line = "".join(input_line)
weechat.buffer_set(catching_keys_data['buf'], "input", input_line)
set_cur(catching_keys_data['buf'], input_line, cur - 1)
catching_keys_data = {'amount': 0}
def key_R(buf, input_line, cur, count):
"""Start Replace mode.
See Also:
`key_base()`.
"""
set_mode("REPLACE")
def key_tilda(buf, input_line, cur, count):
"""Switch the case of `count` characters under the cursor.
See Also:
`key_base()`.
"""
input_line = list(input_line)
count = max(1, count)
while count and cur < len(input_line):
input_line[cur] = input_line[cur].swapcase()
count -= 1
cur += 1
input_line = "".join(input_line)
weechat.buffer_set(buf, "input", input_line)
set_cur(buf, input_line, cur)
def key_alt_j(buf, input_line, cur, count):
"""Go to WeeChat buffer.
Called to preserve WeeChat's alt-j buffer switching.
This is only called when alt-j<num> is pressed after pressing Esc, because
\x01\x01j is received in key_combo_default which becomes \x01j after
removing the detected Esc key.
If Esc isn't the last pressed key, \x01j<num> is directly received in
key_combo_default.
"""
start_catching_keys(2, "cb_key_alt_j", input_line, cur, count)
def cb_key_alt_j():
"""Callback for `key_alt_j()`.
See Also:
`start_catching_keys()`.
"""
global catching_keys_data
weechat.command("", "/buffer " + catching_keys_data['keys'])
catching_keys_data = {'amount': 0}
def key_semicolon(buf, input_line, cur, count, swap=False):
"""Repeat last f, t, F, T `count` times.
Args:
swap (bool, optional): if True, the last motion will be repeated in the
opposite direction (e.g. "f" instead of "F"). Defaults to False.
See Also:
`key_base()`.
"""
global catching_keys_data, vi_buffer
catching_keys_data = ({'amount': 0,
'input_line': input_line,
'cur': cur,
'keys': last_search_motion['data'],
'count': count,
'new_cur': 0,
'buf': buf})
if not last_search_motion['motion']:
return
# Swap the motion's case if called from key_comma.
if swap:
motion = last_search_motion['motion'].swapcase()
else:
motion = last_search_motion['motion']
func = "cb_motion_%s" % motion
vi_buffer = motion
globals()[func](False)
def key_comma(buf, input_line, cur, count):
"""Repeat last f, t, F, T in opposite direction `count` times.
See Also:
`key_base()`.
"""
key_semicolon(buf, input_line, cur, count, True)
def key_u(buf, input_line, cur, count):
"""Undo change `count` times.