-
Notifications
You must be signed in to change notification settings - Fork 6
/
copytk.py
1401 lines (1235 loc) · 45.6 KB
/
copytk.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
# Tmux Copy Toolkit
# (C) Chris Breneman 2021
import os
import os.path
import sys
import re
import argparse
import traceback
import curses
import itertools
import math
import subprocess
import shutil
from datetime import datetime
import time
import platform
#logdir = '/tmp/copytklog'
logdir = None
python_command = 'python3'
# Find full path to tmux command so it can be invoked without a shell
def find_command_path(c):
cmd = 'command -V ' + c
f = os.popen(cmd)
result = f.read()
estatus = f.close()
if estatus:
raise Exception('Error finding tmux: ' + cmd)
r = ' '.join(result.split('\n')[0].split(' ')[2:])
if r[0] != '/':
raise Exception('Got unexpected result from tmux path finding: ' + cmd)
return r
tmux_command = find_command_path('tmux')
# strings that can be used to map to regexes in the quickcopy matches
match_expr_presets = {
# matches common types of urls and things that look like urls
'urls': r'(?:^|[][\s:=,#"{}()'+"'"+r'])([a-zA-Z][a-zA-Z0-9]{1,5}://(?:[a-zA-Z0-9_]+(?::[a-zA-Z0-9_-]+)?@)?(?:(?:[a-zA-Z0-9][\w-]*\.)*[a-zA-Z][\w-]*|(?:[0-2]?[0-9]{1,2}\.){3}[0-2]?[0-9]{1,2})(?::[0-9]{1,5})?(?:/(?:[\w.~%/&-]+|(?:[\w.~%/&-]*\([\w.~%/&-]*\)[\w.~%/&-]*)+)?/?)?(?:\?(?:(?:[\w.~%/&-]+|(?:[\w.~%/&-]*\([\w.~%/&-]*\)[\w.~%/&-]*)+)+(?:=(?:[\w.~%/&-]+|(?:[\w.~%/&-]*\([\w.~%/&-]*\)[\w.~%/&-]*)+)?)?&)*(?:(?:[\w.~%/&-]+|(?:[\w.~%/&-]*\([\w.~%/&-]*\)[\w.~%/&-]*)+)+(?:=(?:[\w.~%/&-]+|(?:[\w.~%/&-]*\([\w.~%/&-]*\)[\w.~%/&-]*)+)?)?)?)?(?:#(?:(?:[\w.~%/&-]+|(?:[\w.~%/&-]*\([\w.~%/&-]*\)[\w.~%/&-]*)+)+(?:=(?:[\w.~%/&-]+|(?:[\w.~%/&-]*\([\w.~%/&-]*\)[\w.~%/&-]*)+)?)?&)*(?:(?:[\w.~%/&-]+|(?:[\w.~%/&-]*\([\w.~%/&-]*\)[\w.~%/&-]*)+)+(?:=(?:[\w.~%/&-]+|(?:[\w.~%/&-]*\([\w.~%/&-]*\)[\w.~%/&-]*)+)?)?)?)?)(?:$|[][\s:=,#"{}()'+"'"+r'])',
# Unix and window style absolute paths
'abspaths': r'(?:^|[][\s:=,#$"{}<>()`'+"'"+r'])((?:/|~/|[A-Z]:[\\/])(?:(?:(?:[a-zA-Z0-9_-]{1,80}|\.|\.\.)|[a-zA-Z0-9_-]{1,60}\\? [a-zA-Z0-9_-]{1,60})[\\/])*(?:(?:(?:[a-zA-Z0-9_-]{1,80}|\.|\.\.)|[a-zA-Z0-9_-]{1,60}\\? [a-zA-Z0-9_-]{1,60})\.[a-zA-Z0-9]{1,6}|(?:[a-zA-Z0-9_-]{1,80}|\.|\.\.)[\\/]?))(?:$|[][\s:=,#$"{}<>()`'+"'"+r'])',
# Absolute or relative paths
'paths': r'(?:^|[][\s:=,#$"{}<>()`'+"'"+r'])((?:(?:/|~/|[A-Z]:[\\/])(?:(?:(?:[a-zA-Z0-9_-]{1,80}|\.|\.\.)|[a-zA-Z0-9_-]{1,60}\\? [a-zA-Z0-9_-]{1,60})[\\/])*(?:(?:(?:[a-zA-Z0-9_-]{1,80}|\.|\.\.)|[a-zA-Z0-9_-]{1,60}\\? [a-zA-Z0-9_-]{1,60})\.[a-zA-Z0-9]{1,6}|(?:[a-zA-Z0-9_-]{1,80}|\.|\.\.)[\\/]?)|(?:[a-zA-Z0-9_-]{1,80}|\.|\.\.)[\\/](?:(?:[a-zA-Z0-9_-]{1,80}|\.|\.\.)[\\/]?|(?:(?:[a-zA-Z0-9_-]{1,80}|\.|\.\.)|[a-zA-Z0-9_-]{1,60}\\? [a-zA-Z0-9_-]{1,60})\.[a-zA-Z0-9]{1,6})|(?:[a-zA-Z0-9_-]{1,80}|\.|\.\.)[\\/](?:(?:(?:[a-zA-Z0-9_-]{1,80}|\.|\.\.)|[a-zA-Z0-9_-]{1,60}\\? [a-zA-Z0-9_-]{1,60})[\\/])+(?:(?:[a-zA-Z0-9_-]{1,80}|\.|\.\.)[\\/]?|(?:(?:[a-zA-Z0-9_-]{1,80}|\.|\.\.)|[a-zA-Z0-9_-]{1,60}\\? [a-zA-Z0-9_-]{1,60})\.[a-zA-Z0-9]{1,6})))(?:$|[][\s:=,#$"{}<>()`'+"'"+r'])',
# Isolated filenames without paths
'filenames': r'(?:^|[][\s:=,#$"{}<>()`/'+"'"+r'])([a-zA-Z0-9_-]{1,80}\.[a-zA-Z][a-zA-Z0-9]{0,5})(?:$|[][\s:=,#$"{}<>()`'+"'"+r'])',
}
def log_clear():
if not logdir: return
shutil.rmtree(logdir, ignore_errors=True)
os.makedirs(logdir)
def log(message, fn=None, time=False):
if not logdir: return
if fn == None: fn = 'main.log'
if time:
message = str(datetime.now()) + ': ' + message
with open(os.path.join(logdir, fn), 'a') as f:
f.write(message + '\n')
# We need to replace the current pane with a pane running the plugin script.
# Ideally this would be done without messing with any application currently running within the pane.
# So, create a new window and pane for that application. If the created window/pane
# is larger than the current pane, divide it into sections and set the pane to the proper size.
def runcmd(command, one=False, lines=False, noblanklines=False):
# runs command in shell via popen
f = os.popen(command)
data = f.read()
estatus = f.close()
if estatus:
raise Exception(f'Command "{command}" exited with status {estatus}')
if one or lines: # return list of lines
dlines = data.split('\n')
if not one and noblanklines:
dlines = [ l for l in dlines if len(l) > 0 ]
if one: # single-line
return dlines[0] if len(dlines) > 0 else ''
return dlines if lines else data
def runtmux(args, one=False, lines=False, noblanklines=False, sendstdin=None):
args = [ str(a) for a in args ]
log('run tmux: ' + ' '.join(args), time=True)
with subprocess.Popen(
[ tmux_command ] + args,
shell=False,
stdin=subprocess.PIPE if sendstdin != None else subprocess.DEVNULL,
stdout=subprocess.PIPE
) as proc:
if sendstdin != None and isinstance(sendstdin, str):
sendstdin = bytearray(sendstdin, 'utf8')
recvstdout, _ = proc.communicate(input=sendstdin)
if proc.returncode != 0:
raise Exception(f'tmux {" ".join(args)} exited with status {proc.returncode}')
log('tmux returned', time=True)
data = recvstdout.decode('utf8')
if one or lines: # return list of lines
dlines = data.split('\n')
if not one and noblanklines:
dlines = [ l for l in dlines if len(l) > 0 ]
if one: # single-line
return dlines[0] if len(dlines) > 0 else ''
return dlines if lines else data
def runshellcommand(command, sendstdin=None, raisenonzero=True):
log('run shell command: ' + command, time=True)
with subprocess.Popen(
command,
shell=True,
executable='/bin/bash',
stdin=subprocess.PIPE if sendstdin != None else subprocess.DEVNULL,
stdout=subprocess.DEVNULL
) as proc:
if sendstdin != None and isinstance(sendstdin, str):
sendstdin = bytearray(sendstdin, 'utf8')
proc.communicate(input=sendstdin)
if proc.returncode != 0 and raisenonzero:
raise Exception(f'Command {command} returned exit code {proc.returncode}')
def runtmuxmulti(argsets):
if len(argsets) < 1: return
allargs = []
for argset in argsets:
if len(allargs) > 0:
allargs.append(';')
allargs.extend(argset)
runtmux(allargs)
tmux_options_cache = {}
def fetch_tmux_options(optmode='g'):
if optmode in tmux_options_cache:
return tmux_options_cache[optmode]
tmuxargs = [ 'show-options' ]
if optmode:
tmuxargs += [ '-' + optmode ]
rows = runtmux(tmuxargs, lines=True, noblanklines=True)
opts = {}
for row in rows:
i = row.find(' ')
if i == -1:
opts[row] = 'on'
continue
name = row[:i]
val = row[i+1:]
# need to process val for quoting and backslash-escapes
if len(val) > 1 and val[0] == '"':
assert(val[-1] == '"')
val = val[1:-1]
elif len(val) > 1 and val[0] == "'":
assert(val[-1] == "'")
val = val[1:-1]
if val.find('\\') != -1:
rval = ''
esc = False
for c in val:
if esc:
rval += c
esc = False
elif c == '\\':
esc = True
else:
rval += c
val = rval
opts[name] = val
tmux_options_cache[optmode] = opts
return opts
def get_tmux_option(name, default=None, optmode='g', aslist=False, userlist=False):
opts = fetch_tmux_options(optmode)
if aslist:
ret = []
if name in opts:
ret.append(opts[name])
i = 0
while True:
if userlist:
lname = name + '-' + str(i)
else:
lname = name + '[' + str(i) + ']'
if lname not in opts: break
ret.append(opts[lname])
i += 1
if len(ret) == 0 and default != None:
if isinstance(default, list):
return default
else:
return [ default ]
return ret
else:
return opts.get(name, default)
def str2bool(s):
return str(s).lower() not in ( '', 'off', 'no', 'false', '0' )
def get_tmux_option_key_curses(name, default=None, optmode='g', aslist=False):
remap = {
'Escape': '\x1b',
'Enter': '\n',
'Space': ' '
}
v = get_tmux_option(name, default=default, optmode=optmode, aslist=aslist)
if aslist:
# also allow space-separated list
return [ remap.get(s, s) for k in v for s in k.split(' ') ]
else:
return remap.get(v, v)
def get_tmux_option_color_pair_curses(name, default_fg=-1, default_bg=-1):
strmap = {
'none': -1,
'black': curses.COLOR_BLACK,
'red': curses.COLOR_RED,
'green': curses.COLOR_GREEN,
'yellow': curses.COLOR_YELLOW,
'blue': curses.COLOR_BLUE,
'magenta': curses.COLOR_MAGENTA,
'cyan': curses.COLOR_CYAN,
'white': curses.COLOR_WHITE
}
v = get_tmux_option(name)
if v == None:
return (default_fg, default_bg)
parts = v.lower().split(':')
if parts[0] not in strmap:
raise Exception(f'Invalid color {parts[0]}')
fg = strmap[parts[0]]
if len(parts) > 1:
if parts[1] not in strmap:
raise Exception(f'Invalid color {parts[1]}')
bg = strmap[parts[1]]
else:
bg = default_bg
return (fg, bg)
def capture_pane_contents(target=None, opts=None):
args = [ 'capture-pane', '-p' ]
if opts:
args += opts
if target != None:
args += [ '-t', target ]
return runtmux(args)[:-1]
def get_pane_info(target=None, capture=False, capturej=False):
args = [ 'display-message', '-p' ]
if target != None:
args += [ '-t', target ]
args += [ '#{session_id} #{window_id} #{pane_id} #{pane_width} #{pane_height} #{window_zoomed_flag} #{cursor_x} #{cursor_y} #{copy_cursor_x} #{copy_cursor_y} #{pane_mode} #{scroll_position}' ]
r = runtmux(args, one=True).split(' ')
try:
cursorpos = (int(r[6]), int(r[7]))
except:
cursorpos = (0, 0)
try:
copycursorpos = (int(r[8]), int(r[9]))
except:
copycursorpos = (0, 0)
mode = r[10]
rdict = {
'session_id': r[0],
'window_id': r[1],
'window_id_full': r[0] + ':' + r[1],
'pane_id': r[2],
'pane_id_full': r[0] + ':' + r[1] + '.' + r[2],
'pane_size': (int(r[3]), int(r[4])), # (width, height)
'zoomed': bool(int(r[5])),
'cursor': copycursorpos if mode == 'copy-mode' else cursorpos,
'scroll_position': int(r[11]) if r[11] != '' else None,
'mode': mode
}
capture_opts = []
if mode == 'copy-mode' and rdict['scroll_position'] != None and rdict['scroll_position'] > 0:
capture_opts += [ '-S', str(-rdict['scroll_position']), '-E', str(-rdict['scroll_position'] + rdict['pane_size'][1] - 1) ]
if capture:
# The "normal" pane capture includes "hard" newlines at line wraps and truncates trailing spaces
rdict['contents'] = capture_pane_contents(rdict['pane_id_full'], capture_opts)
if capturej:
# The "-J" pane capture includes trailing spaces and does not have newlines for wrapping
rdict['contentsj'] = capture_pane_contents(rdict['pane_id_full'], [ '-J' ] + capture_opts)
return rdict
def create_window_pane_of_size(size):
# Create a new window in the background
window_id_full = runtmux([ 'new-window', '-dP', '-F', '#{session_id}:#{window_id}', '/bin/cat' ], one=True)
# Get the information about the new pane just created
pane = get_pane_info(window_id_full)
# If the width is greater than the target width, do a vertical split.
# Note that splitting reduces width by at least 2 due to the separator
tmuxcmds = []
resize = False
if pane['pane_size'][0] > size[0] + 1:
tmuxcmds.append([ 'split-window', '-t', pane['pane_id_full'], '-hd', '/bin/cat' ])
resize = True
# If too tall, do a horizontal split
if pane['pane_size'][1] > size[1] + 1:
tmuxcmds.append([ 'split-window', '-t', pane['pane_id_full'], '-vd', '/bin/cat' ])
resize = True
# Resize the pane to desired size
if resize:
tmuxcmds.append([ 'resize-pane', '-t', pane['pane_id_full'], '-x', size[0], '-y', size[1] ])
if len(tmuxcmds) > 0:
runtmuxmulti(tmuxcmds)
# Return info
pane['pane_size'] = size
return pane
swap_count = 0
def swap_hidden_pane(show_hidden=None):
global swap_count
if show_hidden == True and swap_count % 2 == 1:
return
if show_hidden == False and swap_count % 2 == 0:
return
if args.swap_mode == 'pane-swap':
# Swap target pane and hidden pane
t1 = args.t
t2 = args.hidden_t
runtmux([ 'swap-pane', '-s', t2, '-t', t1 ])
else:
# Switch to either the hidden window or the orig window
if swap_count % 2 == 0:
selectwin = args.hidden_window
else:
selectwin = args.orig_window
runtmux([ 'select-window', '-t', selectwin ])
swap_count += 1
def move_tmux_cursor(pos, target, gotocopy=True): # (x, y)
log('move cursor to: ' + str(pos), time=True)
tmuxcmds = []
if gotocopy:
tmuxcmds.append([ 'copy-mode', '-t', target ])
tmuxcmds.append([ 'send-keys', '-X', '-t', target, 'top-line' ])
if pos[1] > 0:
tmuxcmds.append([ 'send-keys', '-X', '-t', target, '-N', str(pos[1]), 'cursor-down' ])
#tmuxcmds.append([ 'send-keys', '-X', '-t', target, 'start-of-line' ]) # Was breaking when on a wrapped line
if pos[0] > 0:
tmuxcmds.append([ 'send-keys', '-X', '-t', target, '-N', str(pos[0]), 'cursor-right' ])
runtmuxmulti(tmuxcmds)
def cleanup_internal_process():
if swap_count % 2 == 1:
swap_hidden_pane()
runtmux([ 'kill-window', '-t', args.hidden_window ])
def gen_em_labels(n, chars=None, min_nchars=1, max_nchars=None):
# Generates easy-motion letter abbreviation sequences
all_chars = chars or 'asdghklqwertyuiopzxcvbnmfj;'
# Determine how many chars per label are needed
need_label_len = max(math.ceil(math.log(n, len(all_chars))), 1)
if min_nchars > need_label_len:
need_label_len = min_nchars
if max_nchars and need_label_len > max_nchars:
need_label_len = max_nchars
# Determine how many letters are actually needed at such a length
at_len_need_chars = math.ceil(n ** (1 / need_label_len))
# If there are free letters, then there are some available lower on the stack. Evenly divide the
# remaininder among the lower tiers.
n_remaining_chars = len(all_chars) - at_len_need_chars
nchars_per_tier = [ at_len_need_chars ]
for i in range(need_label_len - 1):
nc = n_remaining_chars // (need_label_len - 1 - i)
if i+1 < min_nchars:
nc = 0
nchars_per_tier.append(nc)
n_remaining_chars -= nc
nchars_per_tier.reverse()
# Construct the labels
remaining_chars = all_chars
for tier in range(need_label_len):
tierchars = remaining_chars[:nchars_per_tier[tier]]
remaining_chars = remaining_chars[nchars_per_tier[tier]:]
for label in itertools.product(*[tierchars for i in range(tier + 1)]):
yield ''.join(label)
def process_pane_capture_lines(data, nlines=None):
"""Given the string blob of data from `tmux capture-pane`, returns an array of line strings.
Arguments:
data -- String blob of data from `tmux capture-pane`
nlines -- Maximum number of lines to return
Returns:
An array of line strings. Each line string corresponds to a single visible line such that
a wrapped line is returned as multiple visible lines. Nonprintable characters are removed
and tabs are converted to spaces.
"""
# processes pane capture data into an array of lines
# also handles nonprintables
lines = [
''.join([
' ' if c == '\t' else (
c if c.isprintable() else ''
)
for c in line
])
for line in data.split('\n')
]
if nlines != None:
lines = lines[:nlines]
return lines
def process_pane_capture_line(line):
return ''.join([
' ' if c == '\t' else (
c if c.isprintable() else ''
)
for c in line
])
# Aligns display capture data to actual data that doesn't include wraps.
# Returns a dict mapping each (x, y) in disp_data to an index in j_data.
# If alignment fails, returns None.
# size is x, y (column, lineno)
def align_capture_data(disp_data, j_data, size):
# TODO: Add checks for if arguments are 0-length or otherwise invalid
jidx = 0
didx = 0
charmap = [] # map from index in disp_data to index in j_data
jcharmap = [] # map from index in j_data to index in disp_data
while didx < len(disp_data):
if jidx >= len(j_data):
charmap.append(len(j_data) - 1)
didx += 1
continue
jc = j_data[jidx]
dc = disp_data[didx]
if jc == dc: # usual case - characters match
charmap.append(jidx)
jcharmap.append(didx)
didx += 1
jidx += 1
elif dc == '\t' and jc == ' ':
for i in range(8):
if jidx < len(j_data) and j_data[jidx] == ' ':
jcharmap.append(didx)
jidx += 1
else:
break
elif jc == '\t' and dc == ' ':
for i in range(8):
if didx < len(disp_data) and disp_data[didx] == ' ':
charmap.append(jidx)
didx += 1
else:
break
elif dc == '\n' or dc == ' ' or dc == '\t':
charmap.append(max(jidx - 1, 0))
didx += 1
elif jc == ' ' or jc == '\t':
jcharmap.append(didx)
jidx += 1
else:
return None
# Pad maps to full length if necessary
while len(charmap) < len(disp_data):
charmap.append(len(j_data) - 1)
while len(jcharmap) < len(j_data):
jcharmap.append(len(disp_data) - 1)
# Convert character mapping to mapping indexed by disp_data (x, y)
xymap = {
xy : charmap[didx] if didx < len(charmap) and didx < len(disp_data) else len(j_data) - 1
for xy, didx in get_data_xy_idx_map(disp_data, size).items()
}
# Convert j character mapping to a mapping from j char index to display (x, y)
didx_rev_coord_map = get_data_xy_idx_rev_map(disp_data, size)
xymapj = [
didx_rev_coord_map[min(didx, len(disp_data) - 1)]
for didx in jcharmap
]
# Return values are:
# 0. Mapping dict from tuple (x, y) display position to index into j_data
# 1. Mapping list from index into j_data to (x, y) display position
# 2. Mapping list from index into disp_data to index into j_data
# 3. Mapping list from index into j_data to index into disp_data
return xymap, xymapj, charmap, jcharmap
# Returns a mapping array from index in data (the pane capture data) to the (x, y) coordinates on screen
def get_data_xy_idx_rev_map(data, size):
revmap = []
lineno = 0
col = 0
for dchar in data:
if dchar == '\n':
revmap.append((col, lineno))
lineno += 1
col = 0
continue
if col >= size[0]:
lineno += 1
col = 0
revmap.append((col, lineno))
if dchar == '\t':
col = min(col + 8, size[0])
else:
col += 1
return revmap
# Return a map from (x,y) to index into data
def get_data_xy_idx_map(data, size):
xymap = {}
didx = 0
for lineno in range(size[1]):
lineended = False
for col in range(size[0]):
if didx >= len(data):
xymap[(col, lineno)] = max(len(data) - 1, 0)
continue
dc = data[didx]
if lineended or dc == '\n':
lineended = True
xymap[(col, lineno)] = max(didx - 1, 0)
else:
xymap[(col, lineno)] = didx if didx < len(data) else len(data) - 1
didx += 1
if didx < len(data) and data[didx] == '\n':
didx += 1
return xymap
def execute_copy(data):
command = os.path.expanduser(get_tmux_option('@copytk-copy-command', 'tmux load-buffer -'))
runshellcommand(command, sendstdin=data)
log('Copied data.')
#n = 10000
#ls = gen_em_labels(n)
#for i in range(n):
# print(next(ls))
#exit(0)
class ActionCanceled(Exception):
def __init__(self):
super().__init__('Action Canceled')
class PaneJumpAction:
def __init__(self, stdscr):
self.stdscr = stdscr
log('start run easymotion internal', time=True)
# Fetch information about the panes and capture original contents
self.orig_pane = get_pane_info(args.t, capture=True, capturej=True)
self.overlay_pane = get_pane_info(args.hidden_t)
# Fetch options
self.em_label_chars = get_tmux_option('@copytk-label-chars', 'asdghklqwertyuiopzxcvbnmfj;')
self.has_capital_label_chars = bool(re.search(r'[A-Z]', self.em_label_chars))
# Sanitize the J capture data by removing trailing spaces on each line
self.copy_data = '\n'.join(( line.rstrip() for line in self.orig_pane['contentsj'].split('\n') ))
log(self.copy_data, 'copy_data')
# Create a mapping from display coordinates to indexes into the copy data
aligninfo = align_capture_data(self.orig_pane['contents'], self.copy_data, self.orig_pane['pane_size'])
if aligninfo == None:
log('alignment failed')
# raise Exception('alignment failed')
# Fall back to just mapping the display data to itself. Will break wrapped lines.
self.copy_data = self.orig_pane['contents']
self.disp_copy_map = get_data_xy_idx_map(self.copy_data, self.orig_pane['pane_size'])
self.copy_disp_map = get_data_xy_idx_rev_map(self.copy_data, self.orig_pane['pane_size'])
else:
self.disp_copy_map = aligninfo[0]
self.copy_disp_map = aligninfo[1]
# Fetch options
self.cancel_keys = get_tmux_option_key_curses('@copytk-cancel-key', default='Escape Enter ^C', aslist=True)
# Initialize curses stuff
curses.curs_set(False)
curses.start_color()
curses.use_default_colors()
def init_color(index, optname, default_fg, default_bg):
pair = get_tmux_option_color_pair_curses(optname, default_fg, default_bg)
curses.init_pair(index, pair[0], pair[1])
init_color(1, '@copytk-color-labelchar', curses.COLOR_RED, -1) # first label char
init_color(2, '@copytk-color-labelchar2', curses.COLOR_YELLOW, -1) # second+ label char
init_color(3, '@copytk-color-highlight', curses.COLOR_GREEN, curses.COLOR_YELLOW) # highlight
init_color(4, '@copytk-color-message', curses.COLOR_RED, -1) # status message
self.stdscr.clear()
# Track the size as known by curses
self.curses_size = stdscr.getmaxyx() # note: in (y,x) not (x,y)
# Set the contents to display
self.display_content_lines = process_pane_capture_lines(self.orig_pane['contents'], self.orig_pane['pane_size'][1])
self.reset()
def reset(self, keep_highlight=False):
# Initialize properties for later
self.cur_label_pos = 0 # how many label chars have been keyed in
self.match_locations = None # the currently valid search results [ (x, y, label) ]
self.status_msg = None # Message in bottom-right of screen
# Highlighted location
if not keep_highlight:
self.highlight_ranges = None # range is inclusive
# display current contents
log('\n'.join(self.display_content_lines), 'display_content_lines')
self.redraw()
def flash_highlight_range(self, hlrange, noredraw=False, preflash=False):
if not self.highlight_ranges:
self.highlight_ranges = []
if preflash:
delayt = float(get_tmux_option('@copytk-preflash-time', '0.05'))
self.redraw()
time.sleep(delayt)
if isinstance(hlrange, list):
self.highlight_ranges.extend(hlrange)
else:
self.highlight_ranges.append(hlrange)
self._redraw_highlight_ranges()
self.stdscr.refresh()
delayt = float(get_tmux_option('@copytk-flash-time', '0.5'))
time.sleep(delayt)
if isinstance(hlrange, list):
self.highlight_ranges = self.highlight_ranges[:-len(hlrange)]
else:
self.highlight_ranges.pop()
if not noredraw:
self._redraw_contents()
self.stdscr.refresh()
def addstr(self, y, x, s, a=None):
if len(s) == 0: return
try:
if a == None:
self.stdscr.addstr(y, x, s)
else:
self.stdscr.addstr(y, x, s, a)
except Exception as err:
pass
# note: errors are expected in writes to bottom-right
#log(f'Error writing str to screen. curses_size={self.curses_size} linelen={len(line)} i={i} err={str(err)}')
def _redraw_contents(self):
line_width = min(self.curses_size[1], self.orig_pane['pane_size'][0])
max_line = min(self.curses_size[0], len(self.display_content_lines))
for i in range(max_line):
line = self.display_content_lines[i][:line_width].ljust(self.curses_size[0])
self.addstr(i, 0, line)
def _redraw_highlight_ranges(self):
if not self.highlight_ranges: return
line_width = min(self.curses_size[1], self.orig_pane['pane_size'][0])
hlattr = curses.color_pair(3)
for rng in self.highlight_ranges:
for i in range(rng[0][1], rng[1][1] + 1):
line = self.display_content_lines[i]
if i < rng[0][1] or i > rng[1][1]: # whole line not hl
continue
elif i > rng[0][1] and i < rng[1][1]: # whole line hl
self.addstr(i, 0, line.ljust(line_width), hlattr)
elif i == rng[0][1] and i == rng[1][1]: # range starts and stops on this line
self.addstr(i, rng[0][0], line[rng[0][0]:rng[1][0]+1], hlattr)
elif i == rng[0][1]: # range starts on this line
self.addstr(i, rng[0][0], line.ljust(line_width)[rng[0][0]:], hlattr)
elif i == rng[1][1]: # range ends on this line
self.addstr(i, 0, line[0:rng[1][0]+1], hlattr)
else:
assert(False)
def _redraw_labels(self):
line_width = min(self.curses_size[1], self.orig_pane['pane_size'][0])
if self.match_locations:
for col, row, label in self.match_locations:
if col + len(label) > line_width:
label = label[:line_width - col]
if len(label) > self.cur_label_pos:
try:
self.stdscr.addstr(row, col, label[self.cur_label_pos], curses.color_pair(1))
except Exception as err:
pass
#log(f'Error writing str to screen. curses_size={self.curses_size} linelen={len(line)} i={i} err={str(err)}')
if len(label) > self.cur_label_pos + 1:
try:
self.stdscr.addstr(row, col+1, label[self.cur_label_pos+1:], curses.color_pair(2))
except Exception as err:
pass
#log(f'Error writing str to screen. curses_size={self.curses_size} linelen={len(line)} i={i} err={str(err)}')
def redraw(self):
self._redraw_contents()
self._redraw_labels()
# highlight ranges
self._redraw_highlight_ranges()
# status message
if self.status_msg:
try:
self.stdscr.addstr(self.curses_size[0] - 1, self.curses_size[1] - len(self.status_msg), self.status_msg, curses.color_pair(4))
except:
pass
# refresh
self.stdscr.refresh()
def setstatus(self, msg):
self.status_msg = msg
def cancel(self):
raise ActionCanceled()
def getkey(self, valid=None):
if valid == None:
valid = lambda k: len(k) == 1 and k.isprintable()
while True:
try:
key = self.stdscr.getkey()
except: # fix occasional weird curses bug where this behaves as non-blocking
key = 'none'
#if key in ('^[', '^C', '\n', '\x1b'):
if key in self.cancel_keys:
self.cancel()
if key == 'KEY_RESIZE':
self.curses_size = self.stdscr.getmaxyx()
self.redraw()
continue
if valid(key):
return key
#key = ' '.join([str(hex(ord(c))) for c in key])
#self.stdscr.addstr(0, 0, key)
def run(self):
pass
class EasyMotionAction(PaneJumpAction):
def __init__(self, stdscr, search_len=1):
super().__init__(stdscr)
self.search_len = search_len
self.case_sensitive_search = get_tmux_option('@copytk-case-sensitive-search', 'upper') # value values: on, off, upper
self.min_match_spacing = int(get_tmux_option('@copytk-min-match-spacing', '2'))
self.loc_label_mapping = {} # override mapping from match loc tuples to labels
def _em_filter_locs(self, locs):
d = args.search_direction
cursor = self.orig_pane['cursor']
if d == 'forward' or d == 'down':
return [
loc
for loc in locs
if loc[1] > cursor[1] or (loc[1] == cursor[1] and loc[0] >= cursor[0])
]
elif d == 'reverse' or d == 'up' or d == 'backward':
return [
loc
for loc in locs
if loc[1] < cursor[1] or (loc[1] == cursor[1] and loc[0] < cursor[0])
]
else:
return locs
def _em_sort_locs_cursor_proximity(self, locs, cursor=None):
# Sort locations by proximity to cursor
if cursor == None:
cursor = self.orig_pane['cursor']
locs.sort(key=lambda pos: abs(cursor[0] - pos[0]) + abs(cursor[1] - pos[1]) * self.orig_pane['pane_size'][0])
def _em_search_lines(self, datalines, srch, min_match_spacing=2, matchcase=False):
if not matchcase: srch = srch.lower()
results = [] # (x, y)
for linenum, line in reversed(list(enumerate(datalines))):
if not matchcase: line = line.lower()
pos = 0
while True:
r = line.find(srch, pos)
if r == -1: break
results.append((r, linenum))
pos = r + len(srch) + min_match_spacing
return results
def _em_input_search_chars(self):
search_str = ''
self.setstatus('INPUT CHAR')
self.redraw()
for i in range(self.search_len):
search_str += self.getkey()
self.setstatus(None)
self.redraw()
return search_str
def get_locations(self, action):
"""Returns a list of (x, y) locations of potential match locations.
Arguments:
action -- Either 'search' (to input a search char) or 'lines' (to use each line as a location)
Returns:
A list of (x, y) tuples where y is the line number and x is the character in the line. The lines
represent "physical" lines (eg. a single wrapped line is treated as multiple physical lines here.)
"""
pane_search_lines = self.display_content_lines
log('\n'.join(pane_search_lines), 'pane_search_lines')
if action == 'search':
search_str = self._em_input_search_chars()
return self._em_search_lines(
pane_search_lines,
search_str,
self.min_match_spacing,
self.case_sensitive_search == 'on' or (self.case_sensitive_search == 'upper' and search_str.lower() != search_str)
)
elif action == 'lines':
return [ (0, y) for y in range(self.orig_pane['pane_size'][1]) ]
else:
raise Exception('Invalid copytk easymotion action')
def _input_easymotion_keys(self):
"""Waits for easymotion keypresses to select match; filters possible matches as is executed."""
# Wait for label presses
keyed_label = ''
while True: # loop over each key/char in the label
keyed_label += self.getkey()
self.cur_label_pos += 1
self.match_locations = [ m for m in self.match_locations if m[2].startswith(keyed_label) ]
if len(self.match_locations) < 2:
break
self.redraw()
log('keyed label: ' + keyed_label, time=True)
def do_easymotion(self, action, filter_locs=None, sort_close_to=None, save_labels=False):
# Get possible jump locations sorted by proximity to cursor
locs = self.get_locations(action)
locs = self._em_filter_locs(locs)
if filter_locs:
locs = [ l for l in locs if filter_locs(l) ]
if len(locs) == 0:
raise ActionCanceled()
self._em_sort_locs_cursor_proximity(locs, sort_close_to)
# Assign each match a label
label_it = gen_em_labels(len(locs), self.em_label_chars)
self.match_locations = []
used_labels = { label : loc for loc, label in self.loc_label_mapping.items() }
for ml in locs:
if ml in self.loc_label_mapping:
label = self.loc_label_mapping[ml]
else:
while True:
label = next(label_it)
if label not in used_labels:
break
used_labels[label] = ml
self.match_locations.append(( ml[0], ml[1], label ))
# If save_labels is true, preserve labels for locations across batches
if save_labels:
self.loc_label_mapping.update({ loc : label for label, loc in used_labels.items() })
# Draw labels
self.redraw()
# Wait for keypresses
self._input_easymotion_keys()
if len(self.match_locations) == 0:
return None
else:
return (self.match_locations[0][0], self.match_locations[0][1])
def run(self, action):
log('easymotion swapping in hidden pane', time=True)
swap_hidden_pane(True)
loc = self.do_easymotion(action)
# If a location was found, move cursor there in original pane
if loc:
log('match location: ' + str(loc), time=True)
move_tmux_cursor((loc[0], loc[1]), self.orig_pane['pane_id'])
class EasyCopyAction(EasyMotionAction):
def __init__(self, stdscr, search_len=1):
super().__init__(stdscr, search_len)
def run(self):
log('easycopy swapping in hidden pane', time=True)
swap_hidden_pane(True)
# Input searches to get bounds
pos1 = self.do_easymotion('search')
if not pos1: return
self.highlight_ranges = [ (pos1, pos1) ]
self.reset(keep_highlight=True)
# restrict second search to after first position
pos2 = self.do_easymotion(
'search',
filter_locs=lambda loc: loc[1] > pos1[1] or (loc[1] == pos1[1] and loc[0] > pos1[0]),
sort_close_to=pos1
)
if not pos2: return
# since typing last n letters of word, advance end position by n-1 (-1 because range is inclusive)
pos2 = (pos2[0] + self.search_len - 1, pos2[1])
# Find the data associated with this range and run the copy command
selected_data = self.copy_data[self.disp_copy_map[pos1] : self.disp_copy_map[pos2] + 1]
log('Copied: ' + selected_data)
execute_copy(selected_data)
# Flash selected range as confirmation
self.flash_highlight_range((pos1, pos2))
class LineCopyAction(EasyMotionAction):
def __init__(self, stdscr):
super().__init__(stdscr)
# override from EasyMotionAction to support single-char line selection
def _input_easymotion_keys(self):
"""Waits for easymotion keypresses to select match; filters possible matches as is executed."""
keyed_label = ''
while True: # loop over each key/char in the label
k = self.getkey()
if not self.has_capital_label_chars and re.fullmatch('[A-Z]', k) and self.easymotion_phase == 0:
# Enable single-line-copy mode
k = k.lower()
self.single_line_copy = True
keyed_label += k
self.cur_label_pos += 1
self.match_locations = [ m for m in self.match_locations if m[2].startswith(keyed_label) ]
if len(self.match_locations) < 2:
break
self.redraw()
log('keyed label: ' + keyed_label, time=True)
def run(self):
log('easycopy linecopy swapping in hidden pane', time=True)
swap_hidden_pane(True)
# Input searches to get bounds
self.easymotion_phase = 0
self.single_line_copy = False
pos1 = self.do_easymotion('lines', save_labels=True)
if not pos1: return
if self.single_line_copy:
# Copy single logical line starting at pos1.
# Find end of line as a copy data index
startidx = self.disp_copy_map[pos1]
endidx = self.copy_data.find('\n', startidx)
if endidx == -1:
endidx = len(self.copy_data)
pos2 = self.copy_disp_map[len(self.copy_data) - 1]
selected_data = self.copy_data[startidx:]
else:
pos2 = self.copy_disp_map[endidx-1]
selected_data = self.copy_data[startidx:endidx]
else:
self.highlight_ranges = [ (pos1, pos1) ]
self.reset(keep_highlight=True)
# restrict second search to after first position
self.easymotion_phase = 1
pos2 = self.do_easymotion(
'lines',
filter_locs=lambda loc: loc[1] > pos1[1] or (loc[1] == pos1[1] and loc[0] >= pos1[0]),
sort_close_to=pos1
)
if not pos2: return
# since typing last n letters of word, advance end position by n-1 (-1 because range is inclusive)
pos2 = (self.orig_pane['pane_size'][0] - 1, pos2[1])
# Find the data associated with this range and run the copy command
selected_data = self.copy_data[self.disp_copy_map[pos1] : self.disp_copy_map[pos2] + 1]
log('Copied: ' + selected_data)
execute_copy(selected_data)
# Flash selected range as confirmation
self.flash_highlight_range((pos1, pos2))
class QuickCopyAction(PaneJumpAction):
def __init__(self, stdscr, options_prefix='@copytk-quickcopy-'):
super().__init__(stdscr)
self.options_prefix = options_prefix
self._load_options(options_prefix)
self.em_label_chars = ''.join(( c for c in self.em_label_chars if c not in self.next_batch_char ))
def _load_options(self, prefix='@copytk-quickcopy-'):
# Load in the tiers of match expressions.
# Options for this are in the form: @copytk-quickcopy-match-<Tier>-<TierIndex>