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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
|
-- Copyright (C) 2019 the mpv developers
--
-- Permission to use, copy, modify, and/or distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
--
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
-- SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
-- OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
-- CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
local utils = require 'mp.utils'
local assdraw = require 'mp.assdraw'
-- Default options
local opts = {
-- All drawing is scaled by this value, including the text borders and the
-- cursor. Change it if you have a high-DPI display.
scale = 1,
-- Set the font used for the REPL and the console.
-- This has to be a monospaced font.
font = "",
-- Set the font size used for the REPL and the console. This will be
-- multiplied by "scale".
font_size = 16,
border_size = 1,
case_sensitive = true,
-- Remove duplicate entries in history as to only keep the latest one.
history_dedup = true,
-- The ratio of font height to font width.
-- Adjusts table width of completion suggestions.
-- Values in the range 1.8..2.5 make sense for common monospace fonts.
font_hw_ratio = 'auto',
}
function detect_platform()
local platform = mp.get_property_native('platform')
if platform == 'darwin' or platform == 'windows' then
return platform
elseif os.getenv('WAYLAND_DISPLAY') then
return 'wayland'
end
return 'x11'
end
-- Pick a better default font for Windows and macOS
local platform = detect_platform()
if platform == 'windows' then
opts.font = 'Consolas'
opts.case_sensitive = false
elseif platform == 'darwin' then
opts.font = 'Menlo'
else
opts.font = 'monospace'
end
-- Apply user-set options
require 'mp.options'.read_options(opts)
local styles = {
-- Colors are stolen from base16 Eighties by Chris Kempson
-- and converted to BGR as is required by ASS.
-- 2d2d2d 393939 515151 697374
-- 939fa0 c8d0d3 dfe6e8 ecf0f2
-- 7a77f2 5791f9 66ccff 99cc99
-- cccc66 cc9966 cc99cc 537bd2
debug = '{\\1c&Ha09f93&}',
v = '{\\1c&H99cc99&}',
warn = '{\\1c&H66ccff&}',
error = '{\\1c&H7a77f2&}',
fatal = '{\\1c&H5791f9&\\b1}',
suggestion = '{\\1c&Hcc99cc&}',
selected_suggestion = '{\\1c&H2fbdfa&\\b1}',
}
local terminal_styles = {
debug = '\027[1;30m',
v = '\027[32m',
warn = '\027[33m',
error = '\027[31m',
fatal = '\027[1;31m',
selected_suggestion = '\027[7m',
}
local repl_active = false
local insert_mode = false
local pending_update = false
local line = ''
local cursor = 1
local default_prompt = '>'
local prompt = default_prompt
local default_id = 'default'
local id = default_id
local histories = {[id] = {}}
local history = histories[id]
local history_pos = 1
local log_buffers = {[id] = {}}
local key_bindings = {}
local global_margins = { t = 0, b = 0 }
local input_caller
local suggestion_buffer = {}
local selected_suggestion_index
local completion_start_position
local completion_append
local file_commands = {}
local path_separator = platform == 'windows' and '\\' or '/'
local completion_old_line
local completion_old_cursor
local update_timer = nil
update_timer = mp.add_periodic_timer(0.05, function()
if pending_update then
update()
else
update_timer:kill()
end
end)
update_timer:kill()
mp.observe_property("user-data/osc/margins", "native", function(_, val)
if val then
global_margins = val
else
global_margins = { t = 0, b = 0 }
end
update()
end)
do
local width_length_ratio = 0.5
local osd_width, osd_height = 100, 100
---Update osd resolution if valid
local function update_osd_resolution()
local dim = mp.get_property_native('osd-dimensions')
if not dim or dim.w == 0 or dim.h == 0 then
return
end
osd_width = dim.w
osd_height = dim.h
end
local text_osd = mp.create_osd_overlay('ass-events')
text_osd.compute_bounds, text_osd.hidden = true, true
local function measure_bounds(ass_text)
update_osd_resolution()
text_osd.res_x, text_osd.res_y = osd_width, osd_height
text_osd.data = ass_text
local res = text_osd:update()
return res.x0, res.y0, res.x1, res.y1
end
---Measure text width and normalize to a font size of 1
---text has to be ass safe
local function normalized_text_width(text, size, horizontal)
local align, rotation = horizontal and 7 or 1, horizontal and 0 or -90
local template = '{\\pos(0,0)\\rDefault\\blur0\\bord0\\shad0\\q2\\an%s\\fs%s\\fn%s\\frz%s}%s'
local x1, y1 = nil, nil
size = size / 0.8
-- prevent endless loop
local repetitions_left = 5
repeat
size = size * 0.8
local ass = assdraw.ass_new()
ass.text = template:format(align, size, opts.font, rotation, text)
_, _, x1, y1 = measure_bounds(ass.text)
repetitions_left = repetitions_left - 1
-- make sure nothing got clipped
until (x1 and x1 < osd_width and y1 < osd_height) or repetitions_left == 0
local width = (repetitions_left == 0 and not x1) and 0 or (horizontal and x1 or y1)
return width / size, horizontal and osd_width or osd_height
end
local function fit_on_osd(text)
local estimated_width = #text * width_length_ratio
if osd_width >= osd_height then
-- Fill the osd as much as possible, bigger is more accurate.
return math.min(osd_width / estimated_width, osd_height), true
else
return math.min(osd_height / estimated_width, osd_width), false
end
end
local measured_font_hw_ratio = nil
function get_font_hw_ratio()
local font_hw_ratio = tonumber(opts.font_hw_ratio)
if font_hw_ratio then
return font_hw_ratio
end
if not measured_font_hw_ratio then
local alphabet = 'abcdefghijklmnopqrstuvwxyz'
local text = alphabet:rep(3)
update_osd_resolution()
local size, horizontal = fit_on_osd(text)
local normalized_width = normalized_text_width(text, size * 0.9, horizontal)
measured_font_hw_ratio = #text / normalized_width * 0.95
end
return measured_font_hw_ratio
end
end
-- Add a line to the log buffer (which is limited to 100 lines)
function log_add(text, style, terminal_style)
local log_buffer = log_buffers[id]
log_buffer[#log_buffer + 1] = {
text = text,
style = style or '',
terminal_style = terminal_style or '',
}
if #log_buffer > 100 then
table.remove(log_buffer, 1)
end
if repl_active then
if not update_timer:is_enabled() then
update()
update_timer:resume()
else
pending_update = true
end
end
end
-- Escape a string for verbatim display on the OSD
function ass_escape(str)
return mp.command_native({'escape-ass', str})
end
-- Takes a list of strings, a max width in characters and
-- optionally a max row count.
-- The result contains at least one column.
-- Rows are cut off from the top if rows_max is specified.
-- returns a string containing the formatted table and the row count
function format_table(list, width_max, rows_max)
if #list == 0 then
return '', 0
end
local spaces_min = 2
local spaces_max = 8
local list_size = #list
local column_count = 1
local row_count = list_size
local column_widths
-- total width without spacing
local width_total = 0
local list_widths = {}
for i, item in ipairs(list) do
list_widths[i] = len_utf8(item)
end
-- use as many columns as possible
for columns = 2, list_size do
local rows_lower_bound = math.min(rows_max, math.ceil(list_size / columns))
local rows_upper_bound = math.min(rows_max, list_size, math.ceil(list_size / (columns - 1) - 1))
for rows = rows_upper_bound, rows_lower_bound, -1 do
cw = {}
width_total = 0
-- find out width of each column
for column = 1, columns do
local width = 0
for row = 1, rows do
local i = row + (column - 1) * rows
local item_width = list_widths[i]
if not item_width then break end
if width < item_width then
width = item_width
end
end
cw[column] = width
width_total = width_total + width
if width_total + (columns - 1) * spaces_min > width_max then
break
end
end
if width_total + (columns - 1) * spaces_min <= width_max then
row_count = rows
column_count = columns
column_widths = cw
else
break
end
end
if width_total + (columns - 1) * spaces_min > width_max then
break
end
end
local spaces = math.floor((width_max - width_total) / (column_count - 1))
spaces = math.max(spaces_min, math.min(spaces_max, spaces))
local spacing = column_count > 1
and ass_escape(string.format('%' .. spaces .. 's', ' '))
or ''
local rows = {}
for row = 1, row_count do
local columns = {}
for column = 1, column_count do
local i = row + (column - 1) * row_count
if i > #list then break end
-- more then 99 leads to 'invalid format (width or precision too long)'
local format_string = column == column_count and '%s'
or '%-' .. math.min(column_widths[column], 99) .. 's'
columns[column] = ass_escape(string.format(format_string, list[i]))
if i == selected_suggestion_index then
columns[column] = styles.selected_suggestion .. columns[column]
.. '{\\b0}'.. styles.suggestion
end
end
-- first row is at the bottom
rows[row_count - row + 1] = table.concat(columns, spacing)
end
return table.concat(rows, ass_escape('\n')), row_count
end
local function print_to_terminal()
-- Clear the log after closing the console.
if not repl_active then
mp.osd_message('')
return
end
local log = ''
for _, log_line in ipairs(log_buffers[id]) do
log = log .. log_line.terminal_style .. log_line.text .. '\027[0m'
end
local suggestions = ''
for i, suggestion in ipairs(suggestion_buffer) do
if i == selected_suggestion_index then
suggestions = suggestions .. terminal_styles.selected_suggestion ..
suggestion .. '\027[0m'
else
suggestions = suggestions .. suggestion
end
suggestions = suggestions .. (i < #suggestion_buffer and '\t' or '\n')
end
local before_cur = line:sub(1, cursor - 1)
local after_cur = line:sub(cursor)
-- Ensure there is a character with inverted colors to print.
if after_cur == '' then
after_cur = ' '
end
mp.osd_message(log .. suggestions .. prompt .. ' ' .. before_cur ..
'\027[7m' .. after_cur:sub(1, 1) .. '\027[0m' ..
after_cur:sub(2), 999)
end
-- Render the REPL and console as an ASS OSD
function update()
pending_update = false
-- Unlike vo-configured, current-vo doesn't become falsy while switching VO,
-- which would print the log to the OSD.
if not mp.get_property('current-vo') then
print_to_terminal()
return
end
local dpi_scale = mp.get_property_native("display-hidpi-scale", 1.0)
dpi_scale = dpi_scale * opts.scale
local screenx, screeny, aspect = mp.get_osd_size()
screenx = screenx / dpi_scale
screeny = screeny / dpi_scale
-- Clear the OSD if the REPL is not active
if not repl_active then
mp.set_osd_ass(screenx, screeny, '')
return
end
local coordinate_top = math.floor(global_margins.t * screeny + 0.5)
local clipping_coordinates = '0,' .. coordinate_top .. ',' ..
screenx .. ',' .. screeny
local ass = assdraw.ass_new()
local has_shadow = mp.get_property('osd-back-color'):sub(2, 3) == '00'
local style = '{\\r' ..
'\\1a&H00&\\3a&H00&\\1c&Heeeeee&\\3c&H111111&' ..
(has_shadow and '\\4a&H99&\\4c&H000000&' or '') ..
'\\fn' .. opts.font .. '\\fs' .. opts.font_size ..
'\\bord' .. opts.border_size .. '\\xshad0\\yshad1\\fsp0\\q1' ..
'\\clip(' .. clipping_coordinates .. ')}'
-- Create the cursor glyph as an ASS drawing. ASS will draw the cursor
-- inline with the surrounding text, but it sets the advance to the width
-- of the drawing. So the cursor doesn't affect layout too much, make it as
-- thin as possible and make it appear to be 1px wide by giving it 0.5px
-- horizontal borders.
local cheight = opts.font_size * 8
local cglyph = '{\\rDefault' ..
(mp.get_property_native('focused') == false
and '\\alpha&HFF&' or '\\1a&H44&\\3a&H44&\\4a&H99&') ..
'\\1c&Heeeeee&\\3c&Heeeeee&\\4c&H000000&' ..
'\\xbord0.5\\ybord0\\xshad0\\yshad1\\p4\\pbo24}' ..
'm 0 0 l 1 0 l 1 ' .. cheight .. ' l 0 ' .. cheight ..
'{\\p0}'
local before_cur = ass_escape(line:sub(1, cursor - 1))
local after_cur = ass_escape(line:sub(cursor))
-- Render log messages as ASS.
-- This will render at most screeny / font_size - 1 messages.
-- lines above the prompt
-- subtract 1.5 to account for the input line
local screeny_factor = (1 - global_margins.t - global_margins.b)
local lines_max = math.ceil(screeny * screeny_factor / opts.font_size - 1.5)
-- Estimate how many characters fit in one line
local width_max = math.ceil(screenx / opts.font_size * get_font_hw_ratio())
local suggestions, rows = format_table(suggestion_buffer, width_max, lines_max)
local suggestion_ass = style .. styles.suggestion .. suggestions
local log_ass = ''
local log_buffer = log_buffers[id]
local log_messages = #log_buffer
local log_max_lines = math.max(0, lines_max - rows)
if log_max_lines < log_messages then
log_messages = log_max_lines
end
for i = #log_buffer - log_messages + 1, #log_buffer do
log_ass = log_ass .. style .. log_buffer[i].style .. ass_escape(log_buffer[i].text)
end
ass:new_event()
ass:an(1)
ass:pos(2, screeny - 2 - global_margins.b * screeny)
ass:append(log_ass .. '\\N')
if #suggestions > 0 then
ass:append(suggestion_ass .. '\\N')
end
ass:append(style .. ass_escape(prompt) .. ' ' .. before_cur)
ass:append(cglyph)
ass:append(style .. after_cur)
-- Redraw the cursor with the REPL text invisible. This will make the
-- cursor appear in front of the text.
ass:new_event()
ass:an(1)
ass:pos(2, screeny - 2 - global_margins.b * screeny)
ass:append(style .. '{\\alpha&HFF&}' .. ass_escape(prompt) .. ' ' .. before_cur)
ass:append(cglyph)
ass:append(style .. '{\\alpha&HFF&}' .. after_cur)
mp.set_osd_ass(screenx, screeny, ass.text)
end
-- Set the REPL visibility ("enable", Esc)
function set_active(active)
if active == repl_active then return end
if active then
repl_active = true
insert_mode = false
mp.enable_key_bindings('console-input', 'allow-hide-cursor+allow-vo-dragging')
define_key_bindings()
if not input_caller then
prompt = default_prompt
id = default_id
history = histories[id]
history_pos = #history + 1
mp.enable_messages('terminal-default')
end
else
repl_active = false
suggestion_buffer = {}
undefine_key_bindings()
mp.enable_messages('silent:terminal-default')
if input_caller then
mp.commandv('script-message-to', input_caller, 'input-event',
'closed', line, cursor)
input_caller = nil
line = ''
cursor = 1
end
collectgarbage()
end
update()
end
-- Show the repl if hidden and replace its contents with 'text'
-- (script-message-to repl type)
function show_and_type(text, cursor_pos)
text = text or ''
cursor_pos = tonumber(cursor_pos)
-- Save the line currently being edited, just in case
if line ~= text and line ~= '' and history[#history] ~= line then
history_add(line)
end
line = text
if cursor_pos ~= nil and cursor_pos >= 1
and cursor_pos <= line:len() + 1 then
cursor = math.floor(cursor_pos)
else
cursor = line:len() + 1
end
history_pos = #history + 1
insert_mode = false
if repl_active then
update()
else
set_active(true)
end
end
-- Naive helper function to find the next UTF-8 character in 'str' after 'pos'
-- by skipping continuation bytes. Assumes 'str' contains valid UTF-8.
function next_utf8(str, pos)
if pos > str:len() then return pos end
repeat
pos = pos + 1
until pos > str:len() or str:byte(pos) < 0x80 or str:byte(pos) > 0xbf
return pos
end
-- As above, but finds the previous UTF-8 character in 'str' before 'pos'
function prev_utf8(str, pos)
if pos <= 1 then return pos end
repeat
pos = pos - 1
until pos <= 1 or str:byte(pos) < 0x80 or str:byte(pos) > 0xbf
return pos
end
function len_utf8(str)
local len = 0
local pos = 1
while pos <= str:len() do
pos = next_utf8(str, pos)
len = len + 1
end
return len
end
local function handle_edit()
suggestion_buffer = {}
update()
if input_caller then
mp.commandv('script-message-to', input_caller, 'input-event', 'edited',
line)
end
end
-- Insert a character at the current cursor position (any_unicode)
function handle_char_input(c)
if insert_mode then
line = line:sub(1, cursor - 1) .. c .. line:sub(next_utf8(line, cursor))
else
line = line:sub(1, cursor - 1) .. c .. line:sub(cursor)
end
cursor = cursor + #c
handle_edit()
end
-- Remove the character behind the cursor (Backspace)
function handle_backspace()
if cursor <= 1 then return end
local prev = prev_utf8(line, cursor)
line = line:sub(1, prev - 1) .. line:sub(cursor)
cursor = prev
handle_edit()
end
-- Remove the character in front of the cursor (Del)
function handle_del()
if cursor > line:len() then return end
line = line:sub(1, cursor - 1) .. line:sub(next_utf8(line, cursor))
handle_edit()
end
-- Toggle insert mode (Ins)
function handle_ins()
insert_mode = not insert_mode
end
-- Move the cursor to the next character (Right)
function next_char(amount)
cursor = next_utf8(line, cursor)
suggestion_buffer = {}
update()
end
-- Move the cursor to the previous character (Left)
function prev_char(amount)
cursor = prev_utf8(line, cursor)
suggestion_buffer = {}
update()
end
-- Clear the current line (Ctrl+C)
function clear()
line = ''
cursor = 1
insert_mode = false
history_pos = #history + 1
handle_edit()
end
-- Close the REPL if the current line is empty, otherwise delete the next
-- character (Ctrl+D)
function maybe_exit()
if line == '' then
set_active(false)
else
handle_del()
end
end
function help_command(param)
local cmdlist = mp.get_property_native('command-list')
table.sort(cmdlist, function(c1, c2)
return c1.name < c2.name
end)
local output = ''
if param == '' then
output = 'Available commands:\n'
for _, cmd in ipairs(cmdlist) do
output = output .. ' ' .. cmd.name
end
output = output .. '\n'
output = output .. 'Use "help command" to show information about a command.\n'
output = output .. "ESC or Ctrl+d exits the console.\n"
else
local cmd = nil
for _, curcmd in ipairs(cmdlist) do
if curcmd.name:find(param, 1, true) then
cmd = curcmd
if curcmd.name == param then
break -- exact match
end
end
end
if not cmd then
log_add('No command matches "' .. param .. '"!\n', styles.error,
terminal_styles.error)
return
end
output = output .. 'Command "' .. cmd.name .. '"\n'
for _, arg in ipairs(cmd.args) do
output = output .. ' ' .. arg.name .. ' (' .. arg.type .. ')'
if arg.optional then
output = output .. ' (optional)'
end
output = output .. '\n'
end
if cmd.vararg then
output = output .. 'This command supports variable arguments.\n'
end
end
log_add(output)
end
-- Add a line to the history and deduplicate
function history_add(text)
if opts.history_dedup then
-- More recent entries are more likely to be repeated
for i = #history, 1, -1 do
if history[i] == text then
table.remove(history, i)
break
end
end
end
history[#history + 1] = text
end
-- Run the current command and clear the line (Enter)
function handle_enter()
if line == '' and input_caller == nil then
return
end
if history[#history] ~= line and line ~= '' then
history_add(line)
end
if input_caller then
mp.commandv('script-message-to', input_caller, 'input-event', 'submit',
line)
else
-- match "help [<text>]", return <text> or "", strip all whitespace
local help = line:match('^%s*help%s+(.-)%s*$') or
(line:match('^%s*help$') and '')
if help then
help_command(help)
else
mp.command(line)
end
end
clear()
end
-- Go to the specified position in the command history
function go_history(new_pos)
local old_pos = history_pos
history_pos = new_pos
-- Restrict the position to a legal value
if history_pos > #history + 1 then
history_pos = #history + 1
elseif history_pos < 1 then
history_pos = 1
end
-- Do nothing if the history position didn't actually change
if history_pos == old_pos then
return
end
-- If the user was editing a non-history line, save it as the last history
-- entry. This makes it much less frustrating to accidentally hit Up/Down
-- while editing a line.
if old_pos == #history + 1 and line ~= '' and history[#history] ~= line then
history_add(line)
end
-- Now show the history line (or a blank line for #history + 1)
if history_pos <= #history then
line = history[history_pos]
else
line = ''
end
cursor = line:len() + 1
insert_mode = false
suggestion_buffer = {}
update()
end
-- Go to the specified relative position in the command history (Up, Down)
function move_history(amount)
go_history(history_pos + amount)
end
-- Go to the first command in the command history (PgUp)
function handle_pgup()
go_history(1)
end
-- Stop browsing history and start editing a blank line (PgDown)
function handle_pgdown()
go_history(#history + 1)
end
-- Move to the start of the current word, or if already at the start, the start
-- of the previous word. (Ctrl+Left)
function prev_word()
-- This is basically the same as next_word() but backwards, so reverse the
-- string in order to do a "backwards" find. This wouldn't be as annoying
-- to do if Lua didn't insist on 1-based indexing.
cursor = line:len() - select(2, line:reverse():find('%s*[^%s]*', line:len() - cursor + 2)) + 1
suggestion_buffer = {}
update()
end
-- Move to the end of the current word, or if already at the end, the end of
-- the next word. (Ctrl+Right)
function next_word()
cursor = select(2, line:find('%s*[^%s]*', cursor)) + 1
suggestion_buffer = {}
update()
end
local function command_list()
local commands = {}
for i, command in ipairs(mp.get_property_native('command-list')) do
commands[i] = command.name
end
return commands
end
local function command_list_and_help()
local commands = command_list()
commands[#commands + 1] = 'help'
return commands
end
local function property_list()
local properties = mp.get_property_native('property-list')
for _, sub_property in pairs({'video', 'audio', 'sub', 'sub2'}) do
properties[#properties + 1] = 'current-tracks/' .. sub_property
end
for _, option in ipairs(mp.get_property_native('options')) do
properties[#properties + 1] = 'options/' .. option
properties[#properties + 1] = 'file-local-options/' .. option
properties[#properties + 1] = 'option-info/' .. option
for _, sub_property in pairs({
'name', 'type', 'set-from-commandline', 'set-locally',
'default-value', 'min', 'max', 'choices',
}) do
properties[#properties + 1] = 'option-info/' .. option .. '/' ..
sub_property
end
end
return properties
end
local function profile_list()
local profiles = {}
for i, profile in ipairs(mp.get_property_native('profile-list')) do
profiles[i] = profile.name
end
return profiles
end
local function list_option_list()
local options = {}
-- Don't log errors for renamed and removed properties.
-- (Just mp.enable_messages('fatal') still logs them to the terminal.)
local msg_level_backup = mp.get_property('msg-level')
mp.set_property('msg-level', msg_level_backup == '' and 'cplayer=no'
or msg_level_backup .. ',cplayer=no')
for _, option in pairs(mp.get_property_native('options')) do
if mp.get_property('option-info/' .. option .. '/type', ''):find(' list$') then
options[#options + 1] = option
end
end
mp.set_property('msg-level', msg_level_backup)
return options
end
local function list_option_verb_list(option)
local type = mp.get_property('option-info/' .. option .. '/type')
if type == 'Key/value list' then
return {'add', 'append', 'set', 'remove'}
end
if type == 'String list' or type == 'Object settings list' then
return {'add', 'append', 'clr', 'pre', 'set', 'remove', 'toggle'}
end
return {}
end
local function choice_list(option)
local info = mp.get_property_native('option-info/' .. option, {})
if info.type == 'Flag' then
return { 'no', 'yes' }
end
return info.choices or {}
end
local function find_commands_with_file_argument()
if #file_commands > 0 then
return file_commands
end
for _, command in pairs(mp.get_property_native('command-list')) do
if command.args[1] and
(command.args[1].name == 'filename' or command.args[1].name == 'url') then
file_commands[#file_commands + 1] = command.name
end
end
return file_commands
end
local function file_list(directory)
if directory == '' then
directory = '.'
end
local files = utils.readdir(directory, 'files') or {}
for _, dir in pairs(utils.readdir(directory, 'dirs') or {}) do
files[#files + 1] = dir .. path_separator
end
return files
end
-- List of tab-completions:
-- pattern: A Lua pattern used in string:match. It should return the start
-- position of the word to be completed in the first capture (using
-- the empty parenthesis notation "()"). In patterns with 2
-- captures, the first determines the completions, and the second is
-- the start of the word to be completed.
-- list: A function that returns a list of candidate completion values.
-- append: An extra string to be appended to the end of a successful
-- completion. It is only appended if 'list' contains exactly one
-- match.
function build_completers()
local completers = {
{ pattern = '^%s*()[%w_-]*$', list = command_list_and_help, append = ' ' },
{ pattern = '^%s*help%s+()[%w_-]*$', list = command_list },
{ pattern = '^%s*set%s+"?([%w_-]+)"?%s+()%S*$', list = choice_list },
{ pattern = '^%s*set%s+"?([%w_-]+)"?%s+"()%S*$', list = choice_list, append = '"' },
{ pattern = '^%s*cycle[-_]values%s+"?([%w_-]+)"?.-%s+()%S*$', list = choice_list, append = " " },
{ pattern = '^%s*cycle[-_]values%s+"?([%w_-]+)"?.-%s+"()%S*$', list = choice_list, append = '" ' },
{ pattern = '^%s*apply[-_]profile%s+"()%S*$', list = profile_list, append = '"' },
{ pattern = '^%s*apply[-_]profile%s+()%S*$', list = profile_list },
{ pattern = '^%s*change[-_]list%s+()[%w_-]*$', list = list_option_list, append = ' ' },
{ pattern = '^%s*change[-_]list%s+()"[%w_-]*$', list = list_option_list, append = '" ' },
{ pattern = '^%s*change[-_]list%s+"?([%w_-]+)"?%s+()%a*$', list = list_option_verb_list, append = ' ' },
{ pattern = '^%s*change[-_]list%s+"?([%w_-]+)"?%s+"()%a*$', list = list_option_verb_list, append = '" ' },
{ pattern = '^%s*([av]f)%s+()%a*$', list = list_option_verb_list, append = ' ' },
{ pattern = '^%s*([av]f)%s+"()%a*$', list = list_option_verb_list, append = '" ' },
{ pattern = '${[=>]?()[%w_/-]*$', list = property_list, append = '}' },
}
for _, command in pairs({'set', 'add', 'cycle', 'cycle[-_]values', 'multiply'}) do
completers[#completers + 1] = {
pattern = '^%s*' .. command .. '%s+()[%w_/-]*$',
list = property_list,
append = ' ',
}
completers[#completers + 1] = {
pattern = '^%s*' .. command .. '%s+"()[%w_/-]*$',
list = property_list,
append = '" ',
}
end
for _, command in pairs(find_commands_with_file_argument()) do
completers[#completers + 1] = {
pattern = '^%s*' .. command:gsub('-', '[-_]') ..
'%s+["\']?(.-)()[^' .. path_separator ..']*$',
list = file_list,
-- Unfortunately appending " here would append it everytime a
-- directory is fully completed, even if you intend to browse it
-- afterwards.
}
end
return completers
end
function common_prefix_length(s1, s2)
local common_count = 0
for i = 1, #s1 do
if s1:byte(i) ~= s2:byte(i) then
break
end
common_count = common_count + 1
end
return common_count
end
function max_overlap_length(s1, s2)
for s1_offset = 0, #s1 - 1 do
local match = true
for i = 1, #s1 - s1_offset do
if s1:byte(s1_offset + i) ~= s2:byte(i) then
match = false
break
end
end
if match then
return #s1 - s1_offset
end
end
return 0
end
-- If str starts with the first or last characters of prefix, strip them.
local function strip_common_characters(str, prefix)
return str:sub(1 + math.max(
common_prefix_length(prefix, str),
max_overlap_length(prefix, str)))
end
-- Find the longest common case-sensitive prefix of the entries in "list".
local function find_common_prefix(list)
local prefix = list[1]
for i = 2, #list do
prefix = prefix:sub(1, common_prefix_length(prefix, list[i]))
end
return prefix
end
-- Return the entries of "list" beginning with "part" and the longest common
-- prefix of the matches.
local function complete_match(part, list)
local completions = {}
for _, candidate in pairs(list) do
if candidate:sub(1, part:len()) == part then
completions[#completions + 1] = candidate
end
end
local prefix = find_common_prefix(completions)
if opts.case_sensitive then
return completions, prefix
end
completions = {}
local lower_case_completions = {}
local lower_case_part = part:lower()
for _, candidate in pairs(list) do
if candidate:sub(1, part:len()):lower() == lower_case_part then
completions[#completions + 1] = candidate
lower_case_completions[#lower_case_completions + 1] = candidate:lower()
end
end
local lower_case_prefix = find_common_prefix(lower_case_completions)
-- Behave like GNU readline with completion-ignore-case On.
-- part = 'fooBA', completions = {'foobarbaz', 'fooBARqux'} =>
-- prefix = 'fooBARqux', lower_case_prefix = 'foobar', return 'fooBAR'
if prefix then
return completions, prefix:sub(1, lower_case_prefix:len())
end
-- part = 'fooba', completions = {'fooBARbaz', 'fooBarqux'} =>
-- prefix = nil, lower_case_prefix ='foobar', return 'fooBAR'
if lower_case_prefix then
return completions, completions[1]:sub(1, lower_case_prefix:len())
end
return {}, part
end
local function cycle_through_suggestions(backwards)
selected_suggestion_index = selected_suggestion_index + (backwards and -1 or 1)
if selected_suggestion_index > #suggestion_buffer then
selected_suggestion_index = 1
elseif selected_suggestion_index < 1 then
selected_suggestion_index = #suggestion_buffer
end
local before_cur = line:sub(1, completion_start_position - 1) ..
suggestion_buffer[selected_suggestion_index] .. completion_append
line = before_cur .. strip_common_characters(line:sub(cursor), completion_append)
cursor = before_cur:len() + 1
update()
end
-- Complete the option or property at the cursor (TAB)
function complete(backwards)
if #suggestion_buffer > 0 then
cycle_through_suggestions(backwards)
return
end
if input_caller then
completion_old_line = line
completion_old_cursor = cursor
mp.commandv('script-message-to', input_caller, 'input-event',
'complete', line:sub(1, cursor - 1))
return
end
local before_cur = line:sub(1, cursor - 1)
local after_cur = line:sub(cursor)
-- Try the first completer that works
for _, completer in ipairs(build_completers()) do
-- Completer patterns should return the start of the word to be
-- completed as the first capture.
local s2
completion_start_position, s2 = before_cur:match(completer.pattern)
if not completion_start_position then
-- Multiple input commands can be separated by semicolons, so all
-- completions that are anchored at the start of the string with
-- '^' can start from a semicolon as well. Replace ^ with ; and try
-- to match again.
completion_start_position, s2 =
before_cur:match(completer.pattern:gsub('^^', ';'))
end
if completion_start_position then
local hint
if s2 then
hint = completion_start_position
completion_start_position = s2
end
-- Expand ~ in file completion.
if completer.list == file_list and hint:find('^~' .. path_separator) then
local home = mp.command_native({'expand-path', '~/'})
before_cur = before_cur:sub(1, completion_start_position - #hint - 1) ..
home ..
before_cur:sub(completion_start_position - #hint + 1)
hint = home .. hint:sub(2)
completion_start_position = completion_start_position + #home - 1
end
-- If the completer's pattern found a word, check the completer's
-- list for possible completions
local part = before_cur:sub(completion_start_position)
local completions, prefix = complete_match(part, completer.list(hint))
if #completions > 0 then
-- If there was only one full match from the list, add
-- completer.append to the final string. This is normally a
-- space or a quotation mark followed by a space.
completion_append = completer.append or ''
if #completions == 1 then
prefix = prefix .. completion_append
after_cur = strip_common_characters(after_cur, completion_append)
else
table.sort(completions)
suggestion_buffer = completions
selected_suggestion_index = 0
end
-- Insert the completion and update
before_cur = before_cur:sub(1, completion_start_position - 1) ..
prefix
cursor = before_cur:len() + 1
line = before_cur .. after_cur
update()
return
end
end
end
end
-- Move the cursor to the beginning of the line (HOME)
function go_home()
cursor = 1
suggestion_buffer = {}
update()
end
-- Move the cursor to the end of the line (END)
function go_end()
cursor = line:len() + 1
suggestion_buffer = {}
update()
end
-- Delete from the cursor to the beginning of the word (Ctrl+Backspace)
function del_word()
local before_cur = line:sub(1, cursor - 1)
local after_cur = line:sub(cursor)
before_cur = before_cur:gsub('[^%s]+%s*$', '', 1)
line = before_cur .. after_cur
cursor = before_cur:len() + 1
handle_edit()
end
-- Delete from the cursor to the end of the word (Ctrl+Del)
function del_next_word()
if cursor > line:len() then return end
local before_cur = line:sub(1, cursor - 1)
local after_cur = line:sub(cursor)
after_cur = after_cur:gsub('^%s*[^%s]+', '', 1)
line = before_cur .. after_cur
handle_edit()
end
-- Delete from the cursor to the end of the line (Ctrl+K)
function del_to_eol()
line = line:sub(1, cursor - 1)
handle_edit()
end
-- Delete from the cursor back to the start of the line (Ctrl+U)
function del_to_start()
line = line:sub(cursor)
cursor = 1
handle_edit()
end
-- Empty the log buffer of all messages (Ctrl+L)
function clear_log_buffer()
log_buffers[id] = {}
update()
end
-- Returns a string of UTF-8 text from the clipboard (or the primary selection)
function get_clipboard(clip)
if platform == 'x11' then
local res = utils.subprocess({
args = { 'xclip', '-selection', clip and 'clipboard' or 'primary', '-out' },
playback_only = false,
})
if not res.error then
return res.stdout
end
elseif platform == 'wayland' then
local res = utils.subprocess({
args = { 'wl-paste', clip and '-n' or '-np' },
playback_only = false,
})
if not res.error then
return res.stdout
end
elseif platform == 'windows' then
local res = utils.subprocess({
args = { 'powershell', '-NoProfile', '-Command', [[& {
Trap {
Write-Error -ErrorRecord $_
Exit 1
}
$clip = ""
if (Get-Command "Get-Clipboard" -errorAction SilentlyContinue) {
$clip = Get-Clipboard -Raw -Format Text -TextFormatType UnicodeText
} else {
Add-Type -AssemblyName PresentationCore
$clip = [Windows.Clipboard]::GetText()
}
$clip = $clip -Replace "`r",""
$u8clip = [System.Text.Encoding]::UTF8.GetBytes($clip)
[Console]::OpenStandardOutput().Write($u8clip, 0, $u8clip.Length)
}]] },
playback_only = false,
})
if not res.error then
return res.stdout
end
elseif platform == 'darwin' then
local res = utils.subprocess({
args = { 'pbpaste' },
playback_only = false,
})
if not res.error then
return res.stdout
end
end
return ''
end
-- Paste text from the window-system's clipboard. 'clip' determines whether the
-- clipboard or the primary selection buffer is used (on X11 and Wayland only.)
function paste(clip)
local text = get_clipboard(clip)
local before_cur = line:sub(1, cursor - 1)
local after_cur = line:sub(cursor)
line = before_cur .. text .. after_cur
cursor = cursor + text:len()
handle_edit()
end
-- List of input bindings. This is a weird mashup between common GUI text-input
-- bindings and readline bindings.
function get_bindings()
local bindings = {
{ 'esc', function() set_active(false) end },
{ 'ctrl+[', function() set_active(false) end },
{ 'enter', handle_enter },
{ 'kp_enter', handle_enter },
{ 'shift+enter', function() handle_char_input('\n') end },
{ 'ctrl+j', handle_enter },
{ 'ctrl+m', handle_enter },
{ 'bs', handle_backspace },
{ 'shift+bs', handle_backspace },
{ 'ctrl+h', handle_backspace },
{ 'del', handle_del },
{ 'shift+del', handle_del },
{ 'ins', handle_ins },
{ 'shift+ins', function() paste(false) end },
{ 'mbtn_mid', function() paste(false) end },
{ 'left', function() prev_char() end },
{ 'ctrl+b', function() prev_char() end },
{ 'right', function() next_char() end },
{ 'ctrl+f', function() next_char() end },
{ 'up', function() move_history(-1) end },
{ 'ctrl+p', function() move_history(-1) end },
{ 'wheel_up', function() move_history(-1) end },
{ 'down', function() move_history(1) end },
{ 'ctrl+n', function() move_history(1) end },
{ 'wheel_down', function() move_history(1) end },
{ 'wheel_left', function() end },
{ 'wheel_right', function() end },
{ 'ctrl+left', prev_word },
{ 'alt+b', prev_word },
{ 'ctrl+right', next_word },
{ 'alt+f', next_word },
{ 'tab', complete },
{ 'ctrl+i', complete },
{ 'shift+tab', function() complete(true) end },
{ 'ctrl+a', go_home },
{ 'home', go_home },
{ 'ctrl+e', go_end },
{ 'end', go_end },
{ 'pgup', handle_pgup },
{ 'pgdwn', handle_pgdown },
{ 'ctrl+c', clear },
{ 'ctrl+d', maybe_exit },
{ 'ctrl+k', del_to_eol },
{ 'ctrl+l', clear_log_buffer },
{ 'ctrl+u', del_to_start },
{ 'ctrl+v', function() paste(true) end },
{ 'meta+v', function() paste(true) end },
{ 'ctrl+bs', del_word },
{ 'ctrl+w', del_word },
{ 'ctrl+del', del_next_word },
{ 'alt+d', del_next_word },
{ 'kp_dec', function() handle_char_input('.') end },
}
for i = 0, 9 do
bindings[#bindings + 1] =
{'kp' .. i, function() handle_char_input('' .. i) end}
end
return bindings
end
local function text_input(info)
if info.key_text and (info.event == "press" or info.event == "down"
or info.event == "repeat")
then
handle_char_input(info.key_text)
end
end
function define_key_bindings()
if #key_bindings > 0 then
return
end
for _, bind in ipairs(get_bindings()) do
-- Generate arbitrary name for removing the bindings later.
local name = "_console_" .. (#key_bindings + 1)
key_bindings[#key_bindings + 1] = name
mp.add_forced_key_binding(bind[1], name, bind[2], {repeatable = true})
end
mp.add_forced_key_binding("any_unicode", "_console_text", text_input,
{repeatable = true, complex = true})
key_bindings[#key_bindings + 1] = "_console_text"
end
function undefine_key_bindings()
for _, name in ipairs(key_bindings) do
mp.remove_key_binding(name)
end
key_bindings = {}
end
-- Add a global binding for enabling the REPL. While it's enabled, its bindings
-- will take over and it can be closed with ESC.
mp.add_key_binding(nil, 'enable', function()
set_active(true)
end)
mp.register_script_message('disable', function()
set_active(false)
end)
-- Add a script-message to show the REPL and fill it with the provided text
mp.register_script_message('type', function(text, cursor_pos)
show_and_type(text, cursor_pos)
end)
mp.register_script_message('get-input', function (script_name, args)
if repl_active then
return
end
input_caller = script_name
args = utils.parse_json(args)
prompt = args.prompt or default_prompt
line = args.default_text or ''
cursor = tonumber(args.cursor_position) or line:len() + 1
id = args.id or script_name .. prompt
if histories[id] == nil then
histories[id] = {}
log_buffers[id] = {}
end
history = histories[id]
history_pos = #history + 1
set_active(true)
mp.commandv('script-message-to', input_caller, 'input-event', 'opened')
end)
mp.register_script_message('log', function (message)
-- input.get's edited handler is invoked after submit, so avoid modifying
-- the default log.
if input_caller == nil then
return
end
message = utils.parse_json(message)
log_add(message.text .. '\n',
message.error and styles.error or message.style,
message.error and terminal_styles.error or message.terminal_style)
end)
mp.register_script_message('set-log', function (log)
if input_caller == nil then
return
end
log = utils.parse_json(log)
log_buffers[id] = {}
for i = 1, #log do
if type(log[i]) == 'table' then
log[i].text = log[i].text .. '\n'
log[i].style = log[i].style or ''
log[i].terminal_style = log[i].terminal_style or ''
log_buffers[id][i] = log[i]
else
log_buffers[id][i] = {
text = log[i] .. '\n',
style = '',
terminal_style = '',
}
end
end
update()
end)
mp.register_script_message('complete', function(list, start_pos)
if line ~= completion_old_line or cursor ~= completion_old_cursor then
return
end
local completions, prefix = complete_match(line:sub(start_pos, cursor),
utils.parse_json(list))
local before_cur = line:sub(1, start_pos - 1) .. prefix
local after_cur = line:sub(cursor)
cursor = before_cur:len() + 1
line = before_cur .. after_cur
if #completions > 1 then
suggestion_buffer = completions
selected_suggestion_index = 0
completion_start_position = start_pos
completion_append = ''
end
update()
end)
-- Redraw the REPL when the OSD size changes. This is needed because the
-- PlayRes of the OSD will need to be adjusted.
mp.observe_property('osd-width', 'native', update)
mp.observe_property('osd-height', 'native', update)
mp.observe_property('display-hidpi-scale', 'native', update)
mp.observe_property('focused', 'native', update)
-- Enable log messages. In silent mode, mpv will queue log messages in a buffer
-- until enable_messages is called again without the silent: prefix.
mp.enable_messages('silent:terminal-default')
mp.register_event('log-message', function(e)
-- Ignore log messages from the OSD because of paranoia, since writing them
-- to the OSD could generate more messages in an infinite loop.
if e.prefix:sub(1, 3) == 'osd' then return end
-- Ignore messages output by this script.
if e.prefix == mp.get_script_name() then return end
-- Ignore buffer overflow warning messages. Overflowed log messages would
-- have been offscreen anyway.
if e.prefix == 'overflow' then return end
-- Filter out trace-level log messages, even if the terminal-default log
-- level includes them. These aren't too useful for an on-screen display
-- without scrollback and they include messages that are generated from the
-- OSD display itself.
if e.level == 'trace' then return end
-- Use color for debug/v/warn/error/fatal messages.
log_add('[' .. e.prefix .. '] ' .. e.text, styles[e.level],
terminal_styles[e.level])
end)
collectgarbage()
|