-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheditor.py
1986 lines (1759 loc) · 82.7 KB
/
editor.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
# MIT License
#
# Copyright (c) 2023 Adrian F. Hoefflin [srccircumflex]
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# This code is neither beautiful, economical, innovative, or compatible -- do it better.
from __future__ import annotations
import sys
from threading import Thread
from time import sleep, time
from typing import Callable, Literal, Any, Sequence
from re import sub, Pattern, compile
import atexit
try:
ROOT = sub("[/\\\\]_demo[/\\\\][^/\\\\]+$", "", __file__)
sys.path.append(ROOT)
finally:
pass
from vtframework.iosys.vtermios import mod_ansiin, mod_ansiout, mod_nonimpldef, mod_nonprocess
from vtframework.textbuffer.buffer import TextBuffer
from vtframework.textbuffer.exceptions import CursorError, DatabaseInitError
from vtframework.io.io import flushio, out, StdinAdapter, SpamHandleOne
from vtframework.io.modem import InputRouter, InputSuperModem
from vtframework.textbuffer.display.displays import DisplayScrollable, DisplayBrowsable, HighlighterBase
from vtframework.textbuffer.display.items import VisRowItem, DisplayRowItem
from vtframework.iodata.c1ctrl import ManualESC
from vtframework.iodata.esccontainer import EscSegment, EscContainer
from vtframework.iodata.sgr import BOLD, SGRParams, SGRSeqs, SGRWrap, Ground, INVERT, Fore, StyleResets, UNDERLINE
from vtframework.iodata.chars import Char
from vtframework.iodata.keys import NavKey, DelIns, Ctrl, Meta
from vtframework.iodata.cursor import CursorStyle, CursorNavigate
from vtframework.iodata.textctrl import Erase
from vtframework.iodata.decpm import (
ScreenAlternateBuffer,
CursorAutowrapMode,
BracketedPasteMode,
CursorShow,
CursorBlinking
)
from vtframework.iodata.eval import BasicKeyComp
from _demo._geowatcher import GeoWatcher
from _demo._highlighter_factory import python_darkula
from vtframework.textbuffer._buffercomponents.row import _Row
HEAD_SGR: SGRParams = Fore.hex('D3D7CF') + Ground.hex('555954')
HEAD_HISTORY_STAR_PAST = "<"
HEAD_HISTORY_STAR_FUTURE = ">"
HEAD_HISTORY_STAR_SGR_NOTREACHABLE = Fore.name('red') + Ground.hex('555954') + BOLD
HEAD_HISTORY_STAR_SGR_REACHABLE_DO = Fore.hex('77FFFA') + Ground.hex('555954') + BOLD
HEAD_HISTORY_STAR_SGR_REACHABLE_FORK = Fore.name('magenta') + Ground.hex('555954') + BOLD
LOAD_ANIMATION_SGR: SGRParams = Fore.hex('77FFFA') + Ground.hex('555954') + BOLD
MSG_ERROR_SGR: SGRParams = Fore.yellow + Ground.red + BOLD
MSG_WARN_SGR: SGRParams = Fore.hex("C4A000") + Ground.hex("333333")
MSG_INFO_SGR: SGRParams = Fore.hex("06989A") + Ground.hex("D3D7CF")
MSG_DEBUG_SGR: SGRParams = Fore.black + Ground.hex("73C48F")
FOOTER_SGR: SGRParams = Fore.hex('D3D7CF') + Ground.hex('313030')
FOOTER_KEY_SGR: SGRParams = Fore.hex("A9F4E2") + Ground.hex('313030') + BOLD
FOOTER_DESCRIPTION_SGR: SGRParams = Fore.white + Ground.hex('313030')
INPUT_GOTO_ROWNUM_PROMPT_SGR = (
Fore.white + Ground.hex("242623"),
SGRParams(),
SGRParams()
)
INPUT_GOTO_LINENUM_PROMPT_SGR = (
Fore.white + Ground.hex("242623"),
SGRParams(),
SGRParams()
)
INPUT_GOTO_DATA_PROMPT_SGR = (
Fore.white + Ground.hex("242623"),
SGRParams(),
SGRParams()
)
INPUT_FILE_LOAD_PROMPT_SGR = (
Fore.white + Ground.hex("242623"),
SGRParams(),
SGRParams()
)
INPUT_FILE_OPEN_PROMPT_SGR = (
Fore.white + Ground.hex("242623"),
SGRParams(),
SGRParams()
)
INPUT_DB_EXPORT_PROMPT_SGR = (
Fore.white + Ground.hex("242623"),
SGRParams(),
SGRParams()
)
INPUT_DB_IMPORT_PROMPT_SGR = (
Fore.white + Ground.hex("242623"),
SGRParams(),
SGRParams()
)
INPUT_FILE_WRITE_PROMPT_SGR = (
Fore.white + Ground.hex("242623"),
SGRParams(),
SGRParams()
)
INPUT_FIND_PROMPT_SGR = (
Fore.white + Ground.hex("242623"),
SGRParams(),
SGRParams()
)
MANUAL_KEY_SGR = Fore.cyan + BOLD
FOUND_SGR = Ground.yellow + BOLD
# EDITOR BUFFER BASE PARAMETERS
TAB_SIZE: int = 8
TAB_TO_BLANK: bool = False
JUMP_POINTS_RE: Pattern | None = None
BACK_JUMP_RE: Pattern | None = None
# EDITOR BUFFER SWAP PARAMETERS
SWAP_DB_PATH: Literal[':memory:'] | str = 'SWAP.db'
SWAP_DB_UNLINK_ATEXIT: bool = True
# EDITOR BUFFER LOCAL_HISTORY PARAMETERS
LOCAL_HISTORY_MAXITEMS: int = 20
LOCAL_HISTORY_CHUNK_SIZE: int = 10
LOCAL_HISTORY_MAXITEMS_ACTION: Callable[[], ...] = lambda: None
LOCAL_HISTORY_UNDO_LOCK: bool = False
LOCAL_HISTORY_BRANCH_FORKS: bool = True
LOCAL_HISTORY_DB_PATH: Literal[':memory:', ':swap:'] | str = 'LOCALHISTORY.db'
LOCAL_HISTORY_DB_UNLINK_ATEXIT: bool = True
# EDITOR BUFFER MARKER PARAMETERS
MARKER_MULTI_MARKS: bool = True
MARKER_BACKJUMP_MARKS: bool = True
# EDITOR BUFFER DISPLAY PARAMETERS
DISPLAY_TYPE: Literal['scrollable', 's', 'browsable', 'b'] = 'browsable'
HIGHLIGHTER_TYPE: Literal['regex', 'advanced'] | None = 'advanced'
STDCURPOS: int | Literal['follow', 'parallel', 'end'] = 0
VISENDPOS: Literal['data', 'data f', 'visN1'] = 'data'
HIGHLIGHTER_FACTORY: Callable[[HighlighterBase], Any] = python_darkula
# EDITOR BUFFER VISUALISATION PARAMETERS
VIS_OVERFLOW: tuple[str, str, str] = (
SGRWrap('<', INVERT),
SGRWrap('>', INVERT),
SGRWrap('<<', INVERT)
)
VIS_TAB: tuple[str, str] = (
SGRWrap('→', Fore.hex('FF761F')),
SGRWrap('·', Fore.hex('C2AB00'))
)
VIS_MARK: tuple[Callable[[str], EscSegment | EscContainer], Callable[[str], EscSegment | EscContainer]] = (
lambda c: SGRWrap(c, Ground.hex('11ACAE') + Fore.black, cellular=True),
lambda c: SGRWrap(c, Ground.hex('66B8B1') + Fore.black, cellular=True)
)
VIS_END: Sequence[str | None, str | None, str | None] | None = (
SGRWrap('↵', Fore.name("orange2")),
SGRWrap('↵', Ground.hex('11ACAE') + Fore.name("orange")),
SGRWrap('↵', Ground.hex('66B8B1') + Fore.name("orange"))
)
VIS_NB_END: Sequence[str | None, str | None, str | None] | None = (
SGRWrap('↵', Fore.name("gray")),
SGRWrap('↵', Ground.hex('11ACAE') + Fore.name("gray")),
SGRWrap('↵', Ground.hex('66B8B1') + Fore.name("gray"))
)
VIS_ANCHOR: Callable[[str], EscSegment | EscContainer] = \
lambda c: SGRWrap(c, Ground.hex('FFF800'), inner=True)
VIS_CURSOR_ROW: Callable[[str], EscSegment | EscContainer] = \
lambda vr: SGRWrap(vr, Ground.name('gray10'), cellular=True) + SGRSeqs(Ground.name('gray10'))
VIS_CURSOR_INSERT: tuple[Callable[[], Any], Callable[[str], EscSegment | EscContainer]] = (
(lambda: out(CursorStyle.blinking_underline())),
(lambda c: SGRWrap(c, INVERT, inner=True, cellular=True))
)
VIS_CURSOR_LINEINSERT: tuple[Callable[[], Any], Callable[[str], EscSegment | EscContainer]] = (
(lambda: out(CursorStyle.blinking_bar())),
(lambda c: SGRWrap(c, Ground.name('red4'), inner=True, cellular=True))
)
VIS_CURSOR_LINEASSINSERT: tuple[Callable[[], Any], Callable[[str], EscSegment | EscContainer]] = (
(lambda: out(CursorStyle.blinking_bar())),
(lambda c: SGRWrap(c, Ground.name('red1'), inner=True, cellular=True))
)
VIS_CURSOR_NORMAL: tuple[Callable[[], Any], Callable[[str], EscSegment | EscContainer]] = (
(lambda: out(CursorStyle.default())),
(lambda c: c)
)
ENUM_BORDER_SGR: tuple[SGRParams, SGRParams] = (
Fore.black + Ground.hex("73C48F"),
Fore.black + Ground.hex("73C48F")
)
ENUM_ANCHOR_SGR: tuple[SGRParams, SGRParams] = (
Fore.black + Ground.hex('D9A343'),
Fore.black + Ground.hex('D9A343')
)
_error: Literal["e"] = "e"
_warning: Literal["w"] = "w"
_info: Literal["i"] = "i"
_debug: Literal["d"] = "d"
class _Manual:
geo_watcher: GeoWatcher
__buffer__: TextBuffer
__display__: DisplayBrowsable | DisplayScrollable
__inputmodem__: InputSuperModem
info: _Head
def __init__(self, geo_watcher: GeoWatcher):
self.geo_watcher = geo_watcher
self.__buffer__ = TextBuffer(
top_row_vis_maxsize=None,
future_row_vis_maxsize=None,
tab_size=4,
tab_to_blank=False,
autowrap_points=True,
jump_points_re=None,
back_jump_re=None
)
self.__display__ = DisplayScrollable(
__buffer__=self.__buffer__,
width=self.geo_watcher.size[0],
height=self.geo_watcher.size[1] - 4,
y_auto_scroll_distance=3,
prompt_factory=lambda *_: (EscSegment(""), EscSegment("")),
promptl_len=0,
promptr_len=0,
lapping=0,
vis_overflow=("", "", ""),
width_min_char=EscSegment(" "),
highlighter="regex",
highlighted_rows_cache_max=None,
highlighted_row_segments_max=None,
vis_tab=None,
vis_marked=None,
vis_end=None,
vis_nb_end=None,
visendpos="data",
vis_cursor=None,
vis_anchor=None,
vis_cursor_row=None,
stdcurpos="parallel",
i_rowitem_generator=None,
i_display_generator=None,
i_before_framing=None,
)
self.__display__.__highlighter__.globals.add(compile("^\\S+(?=\\s )"), MANUAL_KEY_SGR)
self.__display__.__highlighter__.globals.add(compile("GNU-NANO"), Ground.black + Fore.hex("9200FF") + BOLD)
self.__display__.__highlighter__.globals.add(compile("VT-Python"), Ground.hex("2D7078") + Fore.hex("5ADC3C") + BOLD)
self.__display__.__highlighter__.globals.add(compile("^__.+__"), Ground.hex("2D7078") + Fore.hex("5ADC3C"))
self.__display__.__highlighter__.globals.add(compile("^.+:"), Fore.hex("C9C90B") + UNDERLINE)
self.__inputmodem__ = InputSuperModem(thread_spam=SpamHandleOne(),
manual_esc_tt=0,
use_alter_bindings=True,
find_all_bindings=True)
with open(ROOT + "/_demo/_editor_man.txt", encoding="utf8") as f:
self.__buffer__.write(f.read(), move_cursor=False)
def move_cursor(self, nk: NavKey):
if nk in BasicKeyComp.NavKeys.arrow_lr:
return self.__buffer__.cursor_move(z_column=int(nk), cross=False) is not None
elif nk in BasicKeyComp.NavKeys.arrow_ud:
return self.__display__.scroll_y({2: 1, -2: -1}[int(nk)], False) is not None
def resize(self):
self.__display__.settings(width=self.geo_watcher.size[0], height=self.geo_watcher.size[1] - 4)
def img(self):
return self.__display__.make_display()
class _Body:
geo_watcher: GeoWatcher
__buffer__: TextBuffer
__display__: DisplayBrowsable | DisplayScrollable
__inputmodem__: InputSuperModem
info: _Head
_get_prompt: Callable[
[_Row, Literal[0, 1, 2, 3, 4]], Sequence[EscSegment | EscContainer, EscSegment | EscContainer]]
_i_rowitem: Callable[[VisRowItem], None]
mode_insert: bool
mode_lineinsert: bool
mode_enum: bool
mode_move_cursor: bool
def __init__(
self,
geo_watcher: GeoWatcher,
# buffer base parameter
tab_size: int,
tab_to_blank: bool,
jump_points_re: Pattern | None,
back_jump_re: Pattern | None,
# buffer swap parameter
swap_db_path: Literal[':memory:'] | str,
swap_db_unlink_atexit: bool,
# buffer local history parameter
local_history_maxitems: int,
local_history_chunk_size: int,
local_history_maxitems_action: Callable[[], ...],
local_history_undo_lock: bool,
local_history_branch_forks: bool,
local_history_db_path: Literal[':memory:', ':swap:'] | str,
local_history_db_unlink_atexit: bool,
# buffer marker parameter
marker_multi_marks: bool,
marker_backjump_marks: bool,
# display parameter
display_type: Literal['scrollable', 's', 'browsable', 'b'],
highlighter: Literal['regex', 'advanced'] | None,
stdcursor: int | Literal['follow', 'parallel', 'end'],
visendpos: Literal['data', 'data f', 'visN1'],
highlighter_factory: Callable[[HighlighterBase], Any]
):
self.geo_watcher = geo_watcher
self.__buffer__ = TextBuffer(
top_row_vis_maxsize=None,
future_row_vis_maxsize=None,
tab_size=tab_size,
tab_to_blank=tab_to_blank,
autowrap_points=True,
jump_points_re=jump_points_re,
back_jump_re=back_jump_re
)
self.__buffer__.init_localhistory(
maximal_items=local_history_maxitems,
items_chunk_size=local_history_chunk_size,
maximal_items_action=local_history_maxitems_action,
undo_lock=local_history_undo_lock,
branch_forks=local_history_branch_forks,
db_path=local_history_db_path,
unlink_atexit=local_history_db_unlink_atexit
)
self.__buffer__.init_rowmax__swap(
rows_maximal=300,
chunk_size=80,
load_distance=80,
keep_top_row_size=False,
db_path=swap_db_path,
unlink_atexit=swap_db_unlink_atexit
)
self.__buffer__.init_marker(
multy_marks=marker_multi_marks,
backjump_mode=marker_backjump_marks
)
__buffer__: TextBuffer = \
self.__buffer__
width: int = \
self.geo_watcher.size[0]
height: int = \
self.geo_watcher.size[1] - 4 # header=1, info=1, footer=2
y_auto_scroll_distance: int = \
3
prompt_factory: Callable[[_Row, Literal[0, 1, 2, 3, 4]], Sequence[EscSegment | EscContainer, EscSegment | EscContainer]] = \
lambda *args: self._get_prompt(*args)
promptl_len: int = \
0
promptr_len: int = \
0
lapping: int = \
3
vis_overflow: Sequence[str, str, str] = \
VIS_OVERFLOW
highlighter: Literal["regex", "r", "advanced", "a"] | None = \
highlighter
highlighted_rows_cache_max: int | None = \
1000
highlighted_row_segments_max: int | None = \
None
vis_tab: Callable[[int], str] | None = \
lambda n: (VIS_TAB[0] * bool(n) + VIS_TAB[1] * (n - 1) if n else '')
vis_marked: Sequence[Callable[[str, VisRowItem, list[int, int]], str], Callable[[str, VisRowItem, list[int, int]], str]] | None = \
(lambda c, itm, coord: VIS_MARK[0](c), lambda c, itm, coord: VIS_MARK[1](c))
vis_end: Sequence[str | None, str | None, str | None] | None = \
VIS_END
vis_nb_end: Sequence[str | None, str | None, str | None] | None = \
VIS_NB_END
visendpos: Literal["data", "d", "data f", "df", "visN1", "v", "v1"] = visendpos
vis_cursor: Callable[[str, VisRowItem], str] | None = self._cursor_visual
vis_anchor: Callable[[str, VisRowItem, tuple[int | str, int]], str] | None = lambda c, itm, _: VIS_ANCHOR(c)
vis_cursor_row: Callable[[str, VisRowItem], str] | None = lambda vr, itm: VIS_CURSOR_ROW(vr)
stdcurpos: int | Literal["follow", "f", "parallel", "p", "end", "e"] = stdcursor
i_rowitem_generator: Callable[[VisRowItem], Any] | None = lambda *args: self._i_rowitem(*args)
i_display_generator: Callable[[DisplayRowItem], Any] | None = None
i_before_framing: Callable[[str, VisRowItem], str] | None = None
if display_type[0] == 's':
self.__display__ = DisplayScrollable(
__buffer__=__buffer__, width=width, height=height, y_auto_scroll_distance=y_auto_scroll_distance,
prompt_factory=prompt_factory, promptl_len=promptl_len, promptr_len=promptr_len, lapping=lapping,
vis_overflow=vis_overflow, width_min_char=EscSegment(" "), highlighter=highlighter,
highlighted_rows_cache_max=highlighted_rows_cache_max,
highlighted_row_segments_max=highlighted_row_segments_max,
vis_tab=vis_tab, vis_marked=vis_marked, vis_end=vis_end, vis_nb_end=vis_nb_end, visendpos=visendpos,
vis_cursor=vis_cursor, vis_anchor=vis_anchor, vis_cursor_row=vis_cursor_row, stdcurpos=stdcurpos,
i_rowitem_generator=i_rowitem_generator, i_display_generator=i_display_generator,
i_before_framing=i_before_framing,
)
else:
self.__display__ = DisplayBrowsable(
__buffer__=__buffer__, width=width, height=height, y_auto_scroll_distance=y_auto_scroll_distance,
prompt_factory=prompt_factory, promptl_len=promptl_len, promptr_len=promptr_len, lapping=lapping,
vis_overflow=vis_overflow, width_min_char=EscSegment(" "), highlighter=highlighter,
highlighted_rows_cache_max=highlighted_rows_cache_max,
highlighted_row_segments_max=highlighted_row_segments_max,
vis_tab=vis_tab, vis_marked=vis_marked, vis_end=vis_end, vis_nb_end=vis_nb_end, visendpos=visendpos,
vis_cursor=vis_cursor, vis_anchor=vis_anchor, vis_cursor_row=vis_cursor_row, stdcurpos=stdcurpos,
i_rowitem_generator=i_rowitem_generator, i_display_generator=i_display_generator,
i_before_framing=i_before_framing,
)
highlighter_factory(self.__display__.__highlighter__)
self.mode_move_cursor = True
self.mode_insert = False
self.mode_lineinsert = False
self.mode_enum = True
self.enum()
self.__inputmodem__ = InputSuperModem(thread_spam=SpamHandleOne(),
manual_esc_tt=0,
use_alter_bindings=True,
find_all_bindings=True)
self.__inputmodem__.__interpreter__.SPACE_TARGETS.set(*self.__inputmodem__.__interpreter__.SPACE_TARGETS.ANY)
def _cursor_visual(self, c: str, _=None):
if self.mode_lineinsert:
if self.mode_insert:
VIS_CURSOR_LINEASSINSERT[0]()
c = VIS_CURSOR_LINEASSINSERT[1](c)
else:
VIS_CURSOR_LINEINSERT[0]()
c = VIS_CURSOR_LINEINSERT[1](c)
elif self.mode_insert:
VIS_CURSOR_INSERT[0]()
c = VIS_CURSOR_INSERT[1](c)
else:
VIS_CURSOR_NORMAL[0]()
c = VIS_CURSOR_NORMAL[1](c)
return c
def enum(self):
def _vis_anchor(rowitm: VisRowItem):
if (_l := len(rowitm.v_anchors)) > 1:
rowitm.row_frame.lr_prompt[1] = (
SGRWrap('| ', ENUM_BORDER_SGR[1]) +
SGRWrap('+', ENUM_ANCHOR_SGR[1]))
elif _l == 1:
rowitm.row_frame.lr_prompt[1] = (
SGRWrap('| ', ENUM_BORDER_SGR[1]) +
SGRWrap(str(rowitm.v_anchors[0][0][0]), ENUM_ANCHOR_SGR[0]))
else:
pass
def _none_vis_anchor(*_):
pass
def _get_none_prompt(*args):
return EscSegment(''), EscSegment('')
def _get_num_prompt(row: _Row, disp_part: Literal[0, 1, 2, 3, 4]):
nonlocal plen
if (_plen := len(str(self.__buffer__.__eof_line_num__))) != plen:
plen = _plen
self.__display__.settings(promptl_len=plen + 2, promptr_len=5)
prompt_l = SGRWrap(('%%-%dd|' % plen) % row.__row_num__, ENUM_BORDER_SGR[0]) + ' '
if row.inrow():
curn = str(row.cursors.content)
if len(curn) >= 4:
prompt_r = SGRWrap('|999+', ENUM_BORDER_SGR[1])
else:
prompt_r = SGRWrap('|%-4s' % curn, ENUM_BORDER_SGR[1])
else:
prompt_r = SGRWrap('| ', ENUM_BORDER_SGR[1])
return [prompt_l, prompt_r]
if self.mode_enum:
self._get_prompt = _get_none_prompt
self._i_rowitem = _none_vis_anchor
self.__display__.settings(promptl_len=0, promptr_len=0)
self.mode_enum = False
else:
self._get_prompt = _get_num_prompt
self._i_rowitem = _vis_anchor
self.__display__.settings(
promptl_len=(plen := len(str(self.__buffer__.__eof_line_num__))) + 2,
promptr_len=5)
self.mode_enum = True
return True
def resize(self):
self.__display__.settings(width=self.geo_watcher.size[0], height=self.geo_watcher.size[1] - 4)
def img(self):
return self.__display__.make_display()
class _Input:
__buffer__: TextBuffer
__display__: DisplayScrollable
__inputmodem__: InputSuperModem
geo_watcher: GeoWatcher
_prompt: tuple[EscSegment, EscSegment]
cache: list[str]
cache_cur: int
action: Callable
def __init__(self, geo_watcher: GeoWatcher, prompt: EscSegment | EscContainer, eol: EscSegment = SGRSeqs(StyleResets.purge_sgr)):
self._prompt = (prompt, eol)
self.geo_watcher = geo_watcher
self.__buffer__ = TextBuffer(
top_row_vis_maxsize=None,
future_row_vis_maxsize=None,
tab_size=4,
tab_to_blank=False,
autowrap_points=False,
jump_points_re=None,
back_jump_re=None
)
self.__buffer__.init_rowmax__restrict(
rows_maximal=1,
last_row_maxsize=None
)
self.__display__ = DisplayScrollable(
self.__buffer__,
height=1,
y_auto_scroll_distance=0,
prompt_factory=lambda *_: self._prompt,
promptl_len=len(prompt),
promptr_len=len(eol),
width=self.geo_watcher.size[0],
lapping=int((self.geo_watcher.size[0] - (len(prompt) + len(eol))) * .8),
vis_overflow=VIS_OVERFLOW,
width_min_char=EscSegment(" "),
vis_marked=None,
vis_end=None,
vis_nb_end=None,
vis_tab=None,
vis_cursor=None,
vis_anchor=None,
vis_cursor_row=None,
highlighter=None,
stdcurpos=0,
visendpos='visN1',
i_rowitem_generator=None,
i_display_generator=None,
i_before_framing=None,
highlighted_rows_cache_max=1000,
highlighted_row_segments_max=None
)
self.__inputmodem__ = InputSuperModem(thread_spam=SpamHandleOne(), manual_esc_tt=0, use_alter_bindings=True)
self.cache = list()
self.cache_cur = 0
self.action = lambda: None
def bind(self, func: Callable):
self.action = func
def move_cursor(self, nk: NavKey):
if nk in BasicKeyComp.NavKeys.arrow_lr:
return self.__buffer__.cursor_move(
z_column=int(nk),
jump=NavKey.M.CTRL in nk.MOD)
elif nk in BasicKeyComp.NavKeys.border:
return self.__buffer__.cursor_move(
z_column=int(nk),
border=True)
elif nk in BasicKeyComp.NavKeys.arrow_ud:
if nk.KEY == nk.K.A_UP:
try:
cont = self.cache[(cache_cur := self.cache_cur - 1)]
except IndexError:
return
else:
self.cache_cur = cache_cur
self.__buffer__.reinitialize()
self.__buffer__.write(cont)
return True
else:
if self.cache_cur:
self.cache_cur += 1
if self.cache_cur:
self.__buffer__.reinitialize()
self.__buffer__.write(self.cache[self.cache_cur])
else:
self.__buffer__.reinitialize()
else:
self.__buffer__.reinitialize()
return True
def resize(self):
self.__display__.settings(
width=self.geo_watcher.size[0], height=1,
lapping=int(
(self.geo_watcher.size[0] - ((_ll := len(self._prompt[0])) + (_lr := len(self._prompt[1])))) * .8),
promptl_len=_ll, promptr_len=_lr
)
def pop(self) -> str:
cont = self.__buffer__.reader(endings={'\n': b''}).read()
self.__buffer__.reinitialize()
self.cache.append(cont)
if len(self.cache) > 120:
self.cache = self.cache[-100:]
self.cache_cur = 0
return cont
def img(self):
return self.__display__.make_display()
class _Head:
geo_watcher: GeoWatcher
text: str
_text: str
star: str
sgr: SGRParams
def __init__(self, geo_watcher: GeoWatcher, sgr: SGRParams):
self.geo_watcher = geo_watcher
self.text = self._text = str()
self.star = " "
self.sgr = sgr
def settitle(self, head: str):
self._text = head
if (lt := len(head)) > (width := self.geo_watcher.size[0] - 2):
space = width - 3
_l = space // 2
_r = (space - _l) - 2
self.text = head[:_l] + ' … ' + head[-_r:]
else:
space = self.geo_watcher.size[0] - lt
_l = space // 2
_r = (space - _l) - 2
self.text = (" " * _l) + head + (" " * _r)
def setstar(self, star: str):
self.star = " " + star
def img(self):
return SGRSeqs(self.sgr) + self.text + self.star + "\x1b[m"
def resize(self):
self.settitle(self._text)
class _Info(_Head):
timestamp: float
msg: bool
def __init__(self, geo_watcher: GeoWatcher, sgr: SGRParams):
_Head.__init__(self, geo_watcher, sgr)
self.timestamp = time()
self.msg = False
def setmsg(self, msg, level: Literal["error", "e", "warn", "w", "info", "i", "debug", "d"]):
self.timestamp = time()
self.msg = True
self.settitle(SGRWrap(msg, {
"e": MSG_ERROR_SGR,
"w": MSG_WARN_SGR,
"i": MSG_INFO_SGR,
"d": MSG_DEBUG_SGR
}[level[0]]))
def img(self):
return self.text
def poll_time(self):
if self.msg and time() - self.timestamp > 32:
self.settitle("")
self.msg = False
class _Footer:
geo_watcher: GeoWatcher
footer: tuple[str, str]
_footer: tuple[str, str]
_footers: dict[Any, tuple[str, str]]
def __init__(self, geo_watcher: GeoWatcher):
self.geo_watcher = geo_watcher
def key_desc(key, sep, desc):
return (SGRWrap(desc, FOOTER_DESCRIPTION_SGR) +
SGRWrap(sep, FOOTER_SGR) +
SGRWrap(key, FOOTER_KEY_SGR) +
SGRSeqs(FOOTER_SGR))
self._footers = {
0: (
SGRSeqs(FOOTER_SGR)
+ key_desc("^_", ": ", "|manual")
+ key_desc("^T", ": ", "|open testfile")
+ key_desc("M-l", ": ", "|line-insert")
+ key_desc("M-l;<ins>", ": ", "|associative line-insert")
+ key_desc("^<backspace>", ": ", "|remove marked")
+ key_desc("M-u", ": ", "|undo")
+ key_desc("M-r", ": ", "|redo")
+ key_desc("M-H", ": ", "|history branch")
+ key_desc("M-[sS]", ": ", "|shift marked")
+ key_desc("M-[tT]", ": ", "|replace marked tabs")
+ key_desc("^C", ": ", "|cat")
,
SGRSeqs(FOOTER_SGR)
+ key_desc("^Q", ": ", "|quit")
+ key_desc("^O", ": ", "|open file")
+ key_desc("^W", ": ", "|write file")
+ key_desc("^G", ": ", "|goto row")
+ key_desc("^D", ": ", "|goto data")
+ key_desc("^S", ": ", "|load file")
+ key_desc("^B", ": ", "|export")
+ key_desc("^U", ": ", "|import")
+ key_desc("M-[0-9]", ": ", "|set anchor")
+ key_desc("^A", ": ", "|goto anchor")
+ key_desc("^F", ": ", "|find pattern")
+ key_desc("M-f", ": ", "|find next")
+ key_desc("M-w", ": ", "|where was")
+ key_desc("M-c", ": ", "|cursor movement")
),
1: (
SGRSeqs(FOOTER_SGR)
+ key_desc("◂▸▴▾", ": ", "|scrolling")
,
SGRSeqs(FOOTER_SGR)
+ key_desc("<ESC>", ": ", "|back")
+ key_desc("^Q", ": ", "|quit program")
),
2: (
SGRSeqs(FOOTER_SGR)
+ key_desc("<enter>", ": ", "|execute")
+ key_desc("^<backspace>", ": ", "|clear buffer")
,
SGRSeqs(FOOTER_SGR)
+ key_desc("<ESC>", ": ", "|cancel")
+ key_desc("▴▾", ": ", "|history")
)
}
self.switch_footer(0)
def resize(self):
self.footer = (
(self._footer[0][:self.geo_watcher.width - 1] + SGRSeqs(FOOTER_SGR) + '…'
if len(self._footer[0]) > self.geo_watcher.width
else (EscSegment("%%-%ds" % self.geo_watcher.width) % self._footer[0])),
(self._footer[1][:self.geo_watcher.width - 1] + SGRSeqs(FOOTER_SGR) + '…'
if len(self._footer[1]) > self.geo_watcher.width
else (EscSegment("%%-%ds" % self.geo_watcher.width) % self._footer[1]))
)
def switch_footer(self, key):
self._footer = self._footers[key]
self.resize()
def img(self):
return self.footer
class _LoadAnimation(Thread):
val: bool
ani: tuple[str, ...]
def __init__(self):
Thread.__init__(self, daemon=True)
self.val = False
self.start()
self.ani = tuple(SGRWrap(s, LOAD_ANIMATION_SGR) for s in ('[· ]',
'[·· ]',
'[··· ]',
'[ ··· ]',
'[ ···]',
'[ ··]',
'[ ·]'))
def run(self) -> None:
while True:
sleep(1)
if self.val:
_cursor_show.lowout()
_cursor_show.highout()
_cursor_show.lowout()
while True:
if not self.val:
break
for i in self.ani:
if not self.val:
break
out(CursorNavigate.line_absolute(), CursorNavigate.column(), i, flush=True)
sleep(.2)
for i in reversed(self.ani):
if not self.val:
break
out(CursorNavigate.line_absolute(), CursorNavigate.column(), i, flush=True)
sleep(.2)
def enable(self):
self.val = True
def disable(self):
self.val = False
class Editor:
__inputrouter__: InputRouter
head: _Head
body: _Body
info: _Info
footer: _Footer
manual: _Manual
input_goto_rownum: _Input
input_goto_data: _Input
input_goto_linenum: _Input
input_file_load: _Input
input_file_open: _Input
input_db_export: _Input
input_db_import: _Input
input_file_write: _Input
input_goto_anchor: _Input
input_find: _Input
current_infoline: _Input | _Info
inputfocus: bool
manualfocus: bool
cur_find_pattern: str
geo_watcher: GeoWatcher
load_animation: _LoadAnimation
def __init__(
self,
# buffer base parameter
tab_size: int,
tab_to_blank: bool,
jump_points_re: Pattern | None,
back_jump_re: Pattern | None,
# buffer swap parameter
swap_db_path: Literal[':memory:'] | str,
swap_db_unlink_atexit: bool,
# buffer local history parameter
local_history_maxitems: int,
local_history_chunk_size: int,
local_history_maxitems_action: Callable[[], ...],
local_history_undo_lock: bool,
local_history_branch_forks: bool,
local_history_db_path: Literal[':memory:', ':swap:'] | str,
local_history_db_unlink_atexit: bool,
# buffer marker parameter
marker_multi_marks: bool,
marker_backjump_marks: bool,
# display parameter
display_type: Literal['scrollable', 's', 'browsable', 'b'],
highlighter_type: Literal['regex', 'advanced'] | None,
stdcursor: int | Literal['follow', 'parallel', 'end'],
visendpos: Literal['data', 'data f', 'visN1'],
highlighter_factory: Callable[[HighlighterBase], Any],
):
self.geo_watcher = GeoWatcher()
self.geo_watcher.bind(self.resize)
self.__inputrouter__ = InputRouter(thread_block=True)
self.load_animation = _LoadAnimation()
self.head = _Head(self.geo_watcher, HEAD_SGR)
self.head.settitle("Welcome to the VT-Python Editor")
self.current_infoline = self.info = _Info(self.geo_watcher, SGRParams())
self.inputfocus = False
self.info.setmsg("| <DEMO> press ctrl+_ for basic help |", _debug)
self.footer = _Footer(self.geo_watcher)
self.manual = _Manual(self.geo_watcher)
self.manualfocus = False
self.body = _Body(
geo_watcher=self.geo_watcher,
tab_size=tab_size,
tab_to_blank=tab_to_blank,
jump_points_re=jump_points_re,
back_jump_re=back_jump_re,
swap_db_path=swap_db_path,
swap_db_unlink_atexit=swap_db_unlink_atexit,
local_history_maxitems=local_history_maxitems,
local_history_chunk_size=local_history_chunk_size,
local_history_maxitems_action=local_history_maxitems_action,
local_history_undo_lock=local_history_undo_lock,
local_history_branch_forks=local_history_branch_forks,
local_history_db_path=local_history_db_path,
local_history_db_unlink_atexit=local_history_db_unlink_atexit,
marker_multi_marks=marker_multi_marks,
marker_backjump_marks=marker_backjump_marks,
display_type=display_type,
highlighter=highlighter_type,
stdcursor=stdcursor,
visendpos=visendpos,
highlighter_factory=highlighter_factory
)
self.__inputrouter__.add_table_entry(self.body, self.body.__inputmodem__)
self.__inputrouter__.switch_gate(self.body)
def bindingwrapper(func):
def wrap(c, v):
self.load_animation.enable(),
if func(c, v):
self.head.setstar(self.get_history_star())
self.window_out()
self.load_animation.disable()
self.info.poll_time()
return wrap
self.body.__inputmodem__.__binder__.bind(
NavKey,
bindingwrapper(lambda k, _: self.move_cursor(k)))
self.body.__inputmodem__.__binder__.bind(
Char,
bindingwrapper(lambda c, _: self.write(c)))
self.body.__inputmodem__.__binder__.bind(
Meta("\n"),
bindingwrapper(lambda *_: self.body.__buffer__.write("\n", nbnl=True,
sub_chars=self.body.mode_insert,
move_cursor=self.body.mode_move_cursor,
sub_line=self.body.mode_lineinsert)))
self.body.__inputmodem__.__binder__.bind(
DelIns(DelIns.K.BACKSPACE),
bindingwrapper(lambda k, _: self.body.__buffer__.backspace()))
self.body.__inputmodem__.__binder__.bind(
DelIns(DelIns.K.DELETE, None),
bindingwrapper(lambda k, _: self.delete(k)))
self.body.__inputmodem__.__binder__.bind(
DelIns(DelIns.K.BACKSPACE, DelIns.M.CTRL),
bindingwrapper(lambda k, _: self.body.__buffer__.__marker__.marked_remove()))
self.body.__inputmodem__.__binder__.bind(