Repository navigation
Expand file tree
/
Copy pathtab4dos.c
More file actions
1452 lines (1301 loc) · 53.9 KB
/
Copy pathtab4dos.c
File metadata and controls
1452 lines (1301 loc) · 53.9 KB
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
/*
* TAB4DOS - TAB filename completion for MS-DOS
* Open Watcom C (16-bit, real mode). Version: see TAB4DOS_VERSION below.
*
* Copyright (c) 2026 Projanglez
* SPDX-License-Identifier: MIT
*
* Architecture: standalone line editor, hooks INT 21h / AH=0Ah only.
* Keys read via INT 16h (as normal caller, no hook). InDOS==0 guaranteed on entry.
* SS != DS in hook: all buffers must be global (DGROUP). No int86/intdos in resident code.
*
* Features: TAB completion (files, dirs, paths, DOS commands, PATH executables),
* command history (Up/Down), mid-line editing (Left/Right, Home, End, Del, Ins,
* Ctrl+Left/Right), ESC to clear line, /u uninstall.
*
* Build: build.bat Test: real DOS hardware (DOSBox masks our TAB completion).
*/
#include <dos.h>
#include <i86.h>
#define TAB4DOS_VERSION "1.1.1"
extern unsigned _psp;
unsigned get_ss( void );
#pragma aux get_ss = "mov ax, ss" value [ax];
unsigned get_sp( void );
#pragma aux get_sp = "mov ax, sp" value [ax];
unsigned get_ds( void );
#pragma aux get_ds = "mov ax, ds" value [ax];
/* -------- Hook + InDOS -------------------------------------------------- */
static void (__interrupt __far *old21)();
static unsigned char far *indos_ptr = 0;
/* -------- Signature for /u detection ------------------------------------ */
static const char sig[] = "TAB4DOS-RES-1";
static unsigned my_psp_seg = 0;
/* -------- File name cache ----------------------------------------------- */
#define MAX_FILES 64
#define NAME_LEN 13
static char file_cache[MAX_FILES][NAME_LEN];
static unsigned char file_is_dir[MAX_FILES];
static int file_count;
/* DTA must be global (SS != DS in hook) */
static unsigned char dta_buf[64];
/* Sort scratch: must be global, NOT a local. A local lives on the caller's
stack (SS), but a near pointer passed to strcmp_ci/entry_before is
dereferenced via DS (SS != DS in the hook) and would read garbage. */
static char sort_name[NAME_LEN];
static unsigned char sort_dir;
/* -------- Command name cache (DOS internals + PATH executables) ---------- */
/* Built once at install, written incrementally to a NAME_LEN-record file in
%TEMP% and read on demand during completion (SmartDrive keeps it RAM-fast).
Keeping it out of resident BSS saves CMD_MAX*NAME_LEN bytes; the file is
built record-by-record with disk-based dedup, so no resident staging buffer
is needed. */
/* Records live in the on-disk index file, so this cap costs no resident
memory — it only bounds the per-TAB linear read (512*13 = 6.5 KB, RAM-fast
under SmartDrive) and the O(n^2) install-time dedup. 128 was too small:
28 internals + a stocked C:\DOS already crowd out later PATH dirs, whose
commands then silently never complete. */
#define CMD_MAX 512
static int cmd_count = 0; /* number of records in idx_path */
static char idx_path[80]; /* full path to the index file */
static char cmd_name[NAME_LEN]; /* record read buffer / matched name */
static unsigned idx_h; /* install-only: idx file write handle */
/* -------- Completion state ----------------------------------------------- */
#define COMP_FILE 0
#define COMP_CMD 1
static char comp_base[NAME_LEN];
static int comp_base_len = 0;
static int comp_active = 0;
static int comp_cur = -1; /* index of currently shown match, -1=none */
static int shown_len = 0;
static int comp_mode = COMP_FILE;
static int comp_first_word = 0;
static int comp_last_group = -1; /* 0=executable, 1=other, -1=no match shown */
/* Path completion: directory prefix (global: SS != DS) */
/* scan_pat must hold dir_prefix (<=66) + stem (<=12) + "*.*" + NUL = 82 */
static char scan_pat[84];
static char dir_prefix[68];
static int dir_prefix_len = 0;
/* -------- History ring buffer (slot contents live on disk, see hist_path) - */
#define HIST_COUNT 64
#define HIST_MAXLEN 128
/* Each ring slot is a fixed HIST_MAXLEN-byte record in the history file:
rec[0] = length (1..127), rec[1..len] = chars. Slot N is at offset
N*HIST_MAXLEN. Only the ring indices stay resident. */
static char hist_path[80]; /* full path to the history file */
static char hist_rec[HIST_MAXLEN]; /* one-slot read/write scratch */
static int hist_head = 0;
static int hist_total = 0;
static int hist_idx = -1;
static char hist_tmp[HIST_MAXLEN];
static int hist_tmp_len = 0;
/* -------- String helpers ------------------------------------------------- */
static int strlen_local( const char *s )
{
int n = 0; while ( s[n] ) n++; return n;
}
static int memcmp_local( const char *a, const char *b, int n )
{
int i; char ca, cb;
for ( i = 0; i < n; i++ ) {
ca = a[i]; cb = b[i];
if ( ca >= 'a' && ca <= 'z' ) ca -= 0x20;
if ( cb >= 'a' && cb <= 'z' ) cb -= 0x20;
if ( ca != cb ) return 1;
}
return 0;
}
static int strcmp_ci( const char *a, const char *b )
{
unsigned char ca, cb;
for ( ;; ) {
ca = (unsigned char)*a++; cb = (unsigned char)*b++;
if ( ca >= 'a' && ca <= 'z' ) ca -= 0x20;
if ( cb >= 'a' && cb <= 'z' ) cb -= 0x20;
if ( ca != cb ) return (int)ca - (int)cb;
if ( ca == 0 ) return 0;
}
}
/* -------- Console output via BIOS INT 10h/0Eh --------------------------- */
/* Full volatile modify list (CLAUDE.md #6): a TSR that hooks INT 10h (e.g. a
mouse driver hiding/showing its cursor) may clobber the whole volatile set,
not just the AH/BX this teletype call itself uses. A narrow list lets the
compiler park a live value (e.g. old_vec's offset) in DX/SI/... across a
con_out/msg call -> corruption only under a full config (hooked INT 10h),
silently fine on a bare boot. */
void con_out( char c );
#pragma aux con_out = \
"mov ah,0x0E" \
"mov bx,0x0007" \
"int 0x10" \
parm [al] \
modify [ah bx cx dx si di es];
static void msg( char *s ) { while ( *s ) con_out( *s++ ); }
/* -------- PC speaker chirp (direct port I/O, hook-safe) ------------------ */
/* Marks the cycle transition from executable to non-executable matches.
Pure IN/OUT — no DOS or BIOS call, so it is safe inside the 0Ah hook. */
/* Program PIT channel 2 with `divisor` and gate the speaker on. Calling it
again while the speaker is on just changes the pitch (no click/gap). */
void spk_on( unsigned divisor );
#pragma aux spk_on = \
"mov bx,ax" \
"mov al,0xB6" \
"out 0x43,al" \
"mov al,bl" \
"out 0x42,al" \
"mov al,bh" \
"out 0x42,al" \
"in al,0x61" \
"or al,3" \
"out 0x61,al" \
parm [ax] \
modify [ax bx];
void spk_off( void );
#pragma aux spk_off = \
"in al,0x61" \
"and al,0xFC" \
"out 0x61,al" \
modify [ax];
/* Wait `n` toggles of the DRAM refresh bit (port 61h bit 4, ~15 us per
toggle on AT-class hardware => ~66 toggles per ms). CPU-speed independent
and interrupt-free. DX bounds each toggle wait so a stuck bit can only
shorten the tone, never hang the machine. */
void io_delay( unsigned n );
#pragma aux io_delay = \
"xor bl,bl" \
"mov dx,0xFFFF" \
"w_poll:" \
"in al,0x61" \
"and al,0x10" \
"cmp al,bl" \
"jne w_tog" \
"dec dx" \
"jnz w_poll" \
"jmp w_done" \
"w_tog:" \
"mov bl,al" \
"mov dx,0xFFFF" \
"dec cx" \
"jnz w_poll" \
"w_done:" \
parm [cx] \
modify [ax bx cx dx];
/* Short two-note rising chirp (~988 Hz 30 ms -> ~1319 Hz 45 ms). The loop
keeps io_delay expanded only once (it is an inline #pragma aux body). */
static void chirp( void )
{
static const unsigned notes[2][2] = { { 1208, 1980 }, { 905, 2970 } };
int i;
for ( i = 0; i < 2; i++ ) {
spk_on( notes[i][0] );
io_delay( notes[i][1] );
}
spk_off();
}
/* -------- Key read via INT 16h/00h (direct opcode, no int86) ------------ */
/* Full volatile modify list (CLAUDE.md #6): KEYB and other TSRs hook INT 16h
and may clobber the volatile set; without this the compiler could keep a
live value across a key read and lose it only under a full config. */
unsigned get_key( void );
#pragma aux get_key = "mov ah,0" "int 0x16" value [ax] modify [bx cx dx si di es];
/* -------- Direct INT 21h helpers ---------------------------------------- */
void far *dos_get_dta( void );
#pragma aux dos_get_dta = \
"mov ah,0x2F" \
"int 0x21" \
"mov ax,bx" \
"mov dx,es" \
value [dx ax] \
modify [bx cx si di es];
void dos_set_dta( void far *p );
#pragma aux dos_set_dta = \
"push ds" \
"mov ds,dx" \
"mov dx,ax" \
"mov ah,0x1A" \
"int 0x21" \
"pop ds" \
parm [dx ax] \
modify [ax bx cx si di es];
unsigned dos_findfirst( void far *pat, unsigned attr );
#pragma aux dos_findfirst = \
"push ds" \
"mov ds,dx" \
"mov dx,ax" \
"mov ah,0x4E" \
"int 0x21" \
"pop ds" \
"sbb ax,ax" \
parm [dx ax] [cx] \
value [ax] \
modify [bx cx dx si di es];
unsigned dos_findnext( void );
#pragma aux dos_findnext = \
"mov ah,0x4F" \
"int 0x21" \
"sbb ax,ax" \
value [ax] \
modify [bx cx dx si di es];
/* -------- Direct INT 21h file I/O (open/read/close + create/write) -------- */
/* InDOS==0 in the 0Ah hook, so these are safe in resident code. Direct int
opcode only (no intdos/int86). Full volatile modify list per CLAUDE.md #6.
All paths/buffers are DGROUP globals and DS==DGROUP at every call site (the
__interrupt prolog sets DS in the hook; normal context in init), so we pass a
NEAR offset and use the live DS as segment. This deliberately avoids a far
pointer in a custom register pair: Watcom assigns the seg/off halves to the
two registers by its own rule, not the order listed, which silently put the
offset where the body expected the segment (DS <- offset -> reads failed,
/u hung). A single near register sidesteps that entirely. */
/* Open existing file read-only (AH=3Dh, AL=0). Returns handle, 0xFFFF on CF. */
unsigned dos_open( const char *path );
#pragma aux dos_open = \
"mov ax,0x3D00" \
"int 0x21" \
"jnc o_ok" \
"mov ax,0xFFFF" \
"o_ok:" \
parm [dx] \
value [ax] \
modify [bx cx dx si di es];
/* Read up to n bytes (AH=3Fh) into buf. Returns bytes read, 0xFFFF on CF. */
unsigned dos_read( unsigned handle, char *buf, unsigned n );
#pragma aux dos_read = \
"mov ah,0x3F" \
"int 0x21" \
"jnc r_ok" \
"mov ax,0xFFFF" \
"r_ok:" \
parm [bx] [dx] [cx] \
value [ax] \
modify [bx cx dx si di es];
/* Close a handle (AH=3Eh). */
void dos_close( unsigned handle );
#pragma aux dos_close = \
"mov ah,0x3E" \
"int 0x21" \
parm [bx] \
modify [ax bx cx dx si di es];
/* Create/truncate file (AH=3Ch, normal attr). Returns handle, 0xFFFF on CF. */
unsigned dos_create( const char *path );
#pragma aux dos_create = \
"xor cx,cx" \
"mov ah,0x3C" \
"int 0x21" \
"jnc c_ok" \
"mov ax,0xFFFF" \
"c_ok:" \
parm [dx] \
value [ax] \
modify [bx cx dx si di es];
/* Write n bytes from buf (AH=40h). Returns bytes written, 0xFFFF on CF. */
unsigned dos_write( unsigned handle, char *buf, unsigned n );
#pragma aux dos_write = \
"mov ah,0x40" \
"int 0x21" \
"jnc w_ok" \
"mov ax,0xFFFF" \
"w_ok:" \
parm [bx] [dx] [cx] \
value [ax] \
modify [bx cx dx si di es];
/* Seek from start of file (AH=42h, AL=0). off < 64KB (CX=0). Used for the
fixed-record index dedup and the history slot ring. */
void dos_lseek( unsigned handle, unsigned off );
#pragma aux dos_lseek = \
"mov ax,0x4200" \
"xor cx,cx" \
"int 0x21" \
parm [bx] [dx] \
modify [ax bx cx dx si di es];
/* Open existing file read/write (AH=3Dh, AL=2). Returns handle, 0xFFFF on CF.
Used by hist_save (read-dedup then write on one handle). */
unsigned dos_open_rw( const char *path );
#pragma aux dos_open_rw = \
"mov ax,0x3D02" \
"int 0x21" \
"jnc orw_ok" \
"mov ax,0xFFFF" \
"orw_ok:" \
parm [dx] \
value [ax] \
modify [bx cx dx si di es];
/* -------- Init/uninstall DOS helpers (direct INT 21h, no CRT wrappers) --- */
/* NOTE: every modify list MUST cover the full volatile set [bx cx dx si di es]
that an INT 21h call may clobber (the DOS dispatch and any chained handler
are free to trash these). A too-narrow list let the compiler keep a live
value (the resident PSP) in SI across the set-vector call in do_uninstall,
which then freed a garbage segment -> MCB corruption -> hang. */
/* Get current INT 21h vector (AH=35h) -> far pointer in DX:AX */
void far *dos_getvect21( void );
#pragma aux dos_getvect21 = \
"mov ax,0x3521" \
"int 0x21" \
"mov ax,bx" \
"mov dx,es" \
value [dx ax] \
modify [bx cx si di es];
/* Set INT 21h vector (AH=25h), DS:DX = handler (passed as seg:off in dx:ax) */
void dos_setvect21( void far *handler );
#pragma aux dos_setvect21 = \
"push ds" \
"mov ds,dx" \
"mov dx,ax" \
"mov ax,0x2521" \
"int 0x21" \
"pop ds" \
parm [dx ax] \
modify [ax bx cx dx si di es];
/* Get InDOS flag pointer (AH=34h) -> far pointer in DX:AX */
void far *dos_get_indos( void );
#pragma aux dos_get_indos = \
"mov ah,0x34" \
"int 0x21" \
"mov ax,bx" \
"mov dx,es" \
value [dx ax] \
modify [bx cx si di es];
/* Free a memory block (AH=49h), ES = segment */
void dos_free_seg( unsigned seg );
#pragma aux dos_free_seg = \
"mov es,ax" \
"mov ah,0x49" \
"int 0x21" \
parm [ax] \
modify [ax bx cx dx si di es];
/* Terminate and stay resident (AH=31h, AL=0), DX = paragraphs to keep */
void tsr_keep( unsigned para );
#pragma aux tsr_keep = \
"mov ax,0x3100" \
"int 0x21" \
parm [dx] \
modify [ax bx cx si di es];
/* Terminate process directly (AH=4Ch, AL=0). Never returns. Used by /u to end
the uninstaller WITHOUT the Watcom C-runtime exit path (FiniRtns/atexit/
null-check), which hangs under a full config after a successful unhook+free
(set-vector and free both verified to complete; only the C exit hung). */
void dos_exit( void );
#pragma aux dos_exit = \
"mov ax,0x4C00" \
"int 0x21" \
aborts;
/* -------- Directory scan ------------------------------------------------- */
/* Executable = plain file ending in .EXE/.COM/.BAT (cache names are stored
lowercase). Directories count as non-executable. */
static int entry_is_exec_name( const char *n, unsigned char is_dir )
{
int l;
if ( is_dir ) return 0;
l = strlen_local( n );
if ( l < 5 || n[l-4] != '.' ) return 0;
return memcmp_local( n+l-3, "exe", 3 ) == 0 ||
memcmp_local( n+l-3, "com", 3 ) == 0 ||
memcmp_local( n+l-3, "bat", 3 ) == 0;
}
/* Cycle order: in command position (first word of the line, i.e. the name
that will be executed) executables before non-executables, alphabetical
within each group. In argument position (e.g. after TYPE) plain
alphabetical — grouping would be wrong there. Returns nonzero if entry
(a,ad) sorts before entry (b,bd). */
static int entry_before( const char *a, unsigned char ad,
const char *b, unsigned char bd )
{
if ( comp_first_word ) {
int ga = entry_is_exec_name( a, ad ) ? 0 : 1;
int gb = entry_is_exec_name( b, bd ) ? 0 : 1;
if ( ga != gb ) return ga < gb;
}
return strcmp_ci( a, b ) < 0;
}
static void scan_directory_path( void far *pat )
{
void far *save_dta;
unsigned ok;
file_count = 0;
save_dta = dos_get_dta();
dos_set_dta( (void far *)dta_buf );
ok = dos_findfirst( pat, 0x10 );
while ( ok == 0 && file_count < MAX_FILES ) {
if ( dta_buf[30] != '.' ) {
int i; char c;
for ( i = 0; i < NAME_LEN - 1 && dta_buf[30+i]; i++ ) {
c = dta_buf[30+i];
if ( c >= 'A' && c <= 'Z' ) c += 0x20; /* store lowercase */
file_cache[file_count][i] = c;
}
file_cache[file_count][i] = 0;
file_is_dir[file_count] = (dta_buf[21] & 0x10) ? 1 : 0;
file_count++;
}
ok = dos_findnext();
}
/* Sort results in entry_before order (position-dependent, see there;
insertion sort, max 64 entries). Scratch entry lives in the global
sort_name/sort_dir (SS != DS, see declaration). */
{
int a, j, b;
for ( a = 1; a < file_count; a++ ) {
for ( b = 0; b < NAME_LEN; b++ ) sort_name[b] = file_cache[a][b];
sort_dir = file_is_dir[a];
j = a - 1;
while ( j >= 0 && entry_before( sort_name, sort_dir,
file_cache[j], file_is_dir[j] ) ) {
for ( b = 0; b < NAME_LEN; b++ ) file_cache[j+1][b] = file_cache[j][b];
file_is_dir[j+1] = file_is_dir[j];
j--;
}
for ( b = 0; b < NAME_LEN; b++ ) file_cache[j+1][b] = sort_name[b];
file_is_dir[j+1] = sort_dir;
}
}
dos_set_dta( save_dta );
}
/* -------- History helpers ------------------------------------------------ */
/* Save line from COMMAND.COM buffer (bseg:boff+2, len chars) to the history
file. Writes one fixed HIST_MAXLEN record at slot hist_head. Runs in the 0Ah
hook (InDOS==0) so direct DOS file I/O is safe; any I/O failure just skips
this entry (never hangs). */
static void hist_save( unsigned bseg, unsigned boff, int len )
{
char far *data = (char far *)MK_FP( bseg, boff + 2 );
unsigned h;
int i;
if ( len == 0 || hist_path[0] == 0 ) return;
if ( len > HIST_MAXLEN - 1 ) len = HIST_MAXLEN - 1;
h = dos_open_rw( hist_path );
if ( h == 0xFFFF ) return;
/* Skip an exact (case-insensitive) duplicate of the most recent entry. */
if ( hist_total > 0 ) {
int prev = (hist_head - 1 + HIST_COUNT) % HIST_COUNT;
dos_lseek( h, (unsigned)prev * HIST_MAXLEN );
if ( dos_read( h, hist_rec, HIST_MAXLEN ) == HIST_MAXLEN
&& (int)(unsigned char)hist_rec[0] == len ) {
int match = 1;
for ( i = 0; i < len; i++ ) {
char ca = hist_rec[1+i], cb = data[i];
if ( ca >= 'a' && ca <= 'z' ) ca -= 0x20;
if ( cb >= 'a' && cb <= 'z' ) cb -= 0x20;
if ( ca != cb ) { match = 0; break; }
}
if ( match ) { dos_close( h ); return; }
}
}
/* Build the record [len][data...0pad] and write it at slot hist_head. */
hist_rec[0] = (char)len;
for ( i = 0; i < len; i++ ) hist_rec[1+i] = data[i];
for ( i = len; i < HIST_MAXLEN - 1; i++ ) hist_rec[1+i] = 0;
dos_lseek( h, (unsigned)hist_head * HIST_MAXLEN );
dos_write( h, hist_rec, HIST_MAXLEN );
dos_close( h );
hist_head = (hist_head + 1) % HIST_COUNT;
if ( hist_total < HIST_COUNT ) hist_total++;
}
/* Read history slot `entry` from the file into hist_rec (data at hist_rec+1,
length in hist_rec[0]). Returns 1 on success, 0 on any failure. Resident;
runs in the 0Ah hook. */
static int hist_load( int entry )
{
unsigned h;
if ( hist_path[0] == 0 ) return 0;
h = dos_open( hist_path );
if ( h == 0xFFFF ) return 0;
dos_lseek( h, (unsigned)entry * HIST_MAXLEN );
if ( dos_read( h, hist_rec, HIST_MAXLEN ) != HIST_MAXLEN ) {
dos_close( h );
return 0;
}
dos_close( h );
return 1;
}
/* Erase current line and write new content from DGROUP buffer.
Cursor must be at end of line (old_len chars past prompt) before calling. */
static int line_replace( char far *buf, int old_len,
const char *new_data, int new_len )
{
int i, maxlen;
maxlen = (unsigned char)buf[0];
for ( i = 0; i < old_len; i++ )
{ con_out(0x08); con_out(' '); con_out(0x08); }
if ( new_len > maxlen - 1 ) new_len = maxlen - 1;
for ( i = 0; i < new_len; i++ ) {
buf[2+i] = new_data[i];
con_out( new_data[i] );
}
return new_len;
}
/* -------- Move cursor n positions left ---------------------------------- */
static void cursor_left_n( int n )
{
while ( n-- > 0 ) con_out( 0x08 );
}
/* -------- QoL: fix a trailing backslash for CD/CHDIR/DIR ----------------- */
/* A directory completion ends in '\', but DOS rejects "CD x\" / "DIR x\".
If the first word is CD/CHDIR/DIR (case-insensitive) and the line ends with
'\', append '.' so it becomes the valid, equivalent "CD x\.". Echoes the '.'
so the shown line matches what is executed. buf is the far COMMAND.COM
buffer; returns the (possibly incremented) length. */
static int fixup_cd_dir_backslash( char far *buf, int len )
{
int maxlen = (unsigned char)buf[0];
static const char * const verbs[] = { "CD", "CHDIR", "DIR", 0 };
int p, wl, i;
if ( len < 1 || buf[2+len-1] != '\\' ) return len;
if ( len >= maxlen - 1 ) return len; /* no room for '.' + CR */
p = 0;
while ( p < len && (buf[2+p] == ' ' || buf[2+p] == '\t') ) p++;
wl = 0;
while ( p+wl < len && buf[2+p+wl] != ' ' && buf[2+p+wl] != '\t' ) wl++;
for ( i = 0; verbs[i]; i++ ) {
const char *v = verbs[i];
int j, vl = strlen_local( v ), ok = ( vl == wl );
for ( j = 0; ok && j < vl; j++ ) {
char c = buf[2+p+j];
if ( c >= 'a' && c <= 'z' ) c -= 0x20;
if ( c != v[j] ) ok = 0;
}
if ( ok ) {
buf[2+len] = '.';
con_out( '.' );
return len + 1;
}
}
return len;
}
/* -------- Command lookup from the index file ----------------------------- */
/* Find the target-th (0-based) command in idx_path whose name matches
comp_base[0..comp_base_len). On success copies the name into cmd_name and
returns 1; on no-match or any I/O error returns 0 (caller beeps, never hangs).
Re-reads the file from the start each call; SmartDrive keeps it RAM-fast. */
static int cmd_find( int target )
{
unsigned h, got;
int i, count;
h = dos_open( idx_path );
if ( h == 0xFFFF ) return 0;
/* Read each record straight into cmd_name; on the target-th match it is
already in place, so just close and return. cmd_name is only consulted
by the caller after a successful (return 1) find. */
count = 0;
for ( i = 0; i < cmd_count; i++ ) {
got = dos_read( h, cmd_name, NAME_LEN );
if ( got != NAME_LEN ) break; /* short read / EOF / error */
if ( comp_base_len == 0 ||
( strlen_local(cmd_name) >= comp_base_len &&
memcmp_local(cmd_name, comp_base, comp_base_len) == 0 ) ) {
if ( count == target ) { dos_close( h ); return 1; }
count++;
}
}
dos_close( h );
return 0;
}
/* True if cache entry e matches the typed stem comp_base[0..comp_base_len). */
static int comp_matches( const char *e )
{
return comp_base_len == 0 ||
( strlen_local(e) >= comp_base_len &&
memcmp_local(e, comp_base, comp_base_len) == 0 );
}
/* Count matching command records in idx_path (0 on any I/O error). */
static int cmd_count_matches( void )
{
unsigned h, got;
int i, n = 0;
h = dos_open( idx_path );
if ( h == 0xFFFF ) return 0;
for ( i = 0; i < cmd_count; i++ ) {
got = dos_read( h, cmd_name, NAME_LEN );
if ( got != NAME_LEN ) break;
if ( comp_matches( cmd_name ) ) n++;
}
dos_close( h );
return n;
}
/* Count matching file_cache entries. */
static int file_count_matches( void )
{
int i, n = 0;
for ( i = 0; i < file_count; i++ )
if ( comp_matches( file_cache[i] ) ) n++;
return n;
}
/* Return file_cache index of the target-th match, or -1. */
static int file_nth_match( int target )
{
int i, c = 0;
for ( i = 0; i < file_count; i++ )
if ( comp_matches( file_cache[i] ) ) {
if ( c == target ) return i;
c++;
}
return -1;
}
/* -------- TAB completion ------------------------------------------------- */
/* dir = +1 (TAB, forward) or -1 (Shift+TAB, backward). */
static int do_complete( unsigned bseg, unsigned boff, int len, int dir )
{
char far *buf = (char far *)MK_FP( bseg, boff );
int maxlen = (unsigned char)buf[0];
int i, target, count, matched, namelen, addlen, avail;
if ( !comp_active ) {
int arg_start, slash_pos, j;
/* arg_start: position after last space before cursor. Set the
command-position flag BEFORE the directory scan below: the sort
in scan_directory_path reads it (entry_before). */
arg_start = len;
while ( arg_start > 0 && buf[2+arg_start-1] != ' ' ) arg_start--;
comp_first_word = ( arg_start == 0 );
/* slash_pos: position after last \ or / in current argument */
slash_pos = arg_start;
for ( j = arg_start; j < len; j++ )
if ( buf[2+j] == '\\' || buf[2+j] == '/' ) slash_pos = j + 1;
/* extract dir_prefix */
dir_prefix_len = slash_pos - arg_start;
if ( dir_prefix_len >= (int)(sizeof dir_prefix) - 1 )
dir_prefix_len = (int)(sizeof dir_prefix) - 2;
for ( j = 0; j < dir_prefix_len; j++ )
dir_prefix[j] = buf[2+arg_start+j];
dir_prefix[dir_prefix_len] = 0;
/* extract comp_base (stem to match against) */
comp_base_len = len - slash_pos;
if ( comp_base_len > NAME_LEN - 1 ) comp_base_len = NAME_LEN - 1;
for ( j = 0; j < comp_base_len; j++ )
comp_base[j] = buf[2+slash_pos+j];
/* Scan directory on first TAB. The typed stem goes INTO the FindFirst
pattern ("DARK*.*", not "*.*"): DOS filters before our 64-entry
cache fills, so a match is found even in directories with more than
MAX_FILES entries (a bare "*.*" scan capped at 64 silently dropped
later entries). "*.*" is appended only if the stem has no dot yet
(FCB matching: "DARK*" alone would not match "DARKLAND.EXE"). */
{
int sp = 0, has_dot = 0;
for ( j = 0; j < dir_prefix_len; j++ ) scan_pat[sp++] = dir_prefix[j];
for ( j = 0; j < comp_base_len; j++ ) {
if ( comp_base[j] == '.' ) has_dot = 1;
scan_pat[sp++] = comp_base[j];
}
scan_pat[sp++] = '*';
if ( !has_dot ) { scan_pat[sp++] = '.'; scan_pat[sp++] = '*'; }
scan_pat[sp] = 0;
scan_directory_path( (void far *)scan_pat );
}
comp_mode = COMP_FILE; /* always try files first */
comp_cur = -1; /* nothing shown yet */
comp_last_group = -1;
shown_len = dir_prefix_len + comp_base_len;
}
/* Count matches in the current mode. If file mode has none and we may fall
back to commands (first word, >=1 char typed), switch to command mode. */
count = (comp_mode == COMP_CMD) ? cmd_count_matches() : file_count_matches();
if ( count == 0 && comp_mode == COMP_FILE &&
comp_first_word && comp_base_len > 0 ) {
comp_mode = COMP_CMD;
comp_cur = -1;
count = cmd_count_matches();
}
if ( count == 0 ) { con_out(0x07); comp_active = 0; return len; }
/* Pick the next match index in the requested direction, wrapping. From a
fresh start (comp_cur < 0) forward shows the first, backward the last. */
if ( comp_cur < 0 )
target = ( dir > 0 ) ? 0 : count - 1;
else
target = ( comp_cur + dir + count ) % count;
/* Resolve the chosen match. Commands land in cmd_name; files give an index
into file_cache. matched is unused (0) in command mode. */
matched = 0;
if ( comp_mode == COMP_CMD ) {
if ( !cmd_find( target ) ) { con_out(0x07); comp_active = 0; return len; }
namelen = strlen_local( cmd_name );
} else {
matched = file_nth_match( target );
if ( matched < 0 ) { con_out(0x07); comp_active = 0; return len; }
namelen = strlen_local( file_cache[matched] );
}
if ( comp_mode == COMP_CMD ) {
addlen = namelen + 1; /* +1 for trailing space */
} else {
addlen = namelen + (file_is_dir[matched] ? 1 : 0);
}
avail = (maxlen - 1) - (len - shown_len);
if ( dir_prefix_len + addlen > avail ) {
con_out(0x07); comp_active = 0; return len;
}
/* Erase the previously shown completion */
for ( i = 0; i < shown_len; i++ )
{ con_out(0x08); con_out(' '); con_out(0x08); }
len -= shown_len;
/* Write dir_prefix */
for ( i = 0; i < dir_prefix_len; i++ )
{ buf[2+len] = dir_prefix[i]; con_out(dir_prefix[i]); len++; }
/* Write matched name */
{
const char *e = (comp_mode == COMP_CMD) ? cmd_name : file_cache[matched];
for ( i = 0; i < namelen; i++ )
{ buf[2+len] = e[i]; con_out(e[i]); len++; }
}
if ( comp_mode == COMP_CMD ) {
buf[2+len] = ' '; con_out(' '); len++;
} else if ( file_is_dir[matched] ) {
buf[2+len] = '\\'; con_out('\\'); len++; /* cycles within dir, not descends */
}
shown_len = dir_prefix_len + addlen;
comp_active = 1;
comp_cur = target;
/* Audible cue when cycling crosses from the executable group into the
non-executable group. Only in command position — in argument position
the matches are sorted plain alphabetical (no groups, no cue). */
if ( comp_mode == COMP_FILE && comp_first_word ) {
int g = entry_is_exec_name( file_cache[matched],
file_is_dir[matched] ) ? 0 : 1;
if ( comp_last_group == 0 && g == 1 ) chirp();
comp_last_group = g;
} else {
comp_last_group = -1;
}
return len;
}
/* -------- Line editor ---------------------------------------------------- */
static void do_readline( unsigned bseg, unsigned boff )
{
char far *buf = (char far *)MK_FP( bseg, boff );
int maxlen = (unsigned char)buf[0];
int len = 0;
int cur = 0; /* cursor position 0..len */
int ins = 1; /* 1=insert, 0=overwrite */
unsigned k; unsigned char ascii, scan;
int i;
comp_active = 0; comp_base_len = 0; shown_len = 0; comp_cur = -1;
hist_idx = -1;
for ( ;; ) {
k = get_key();
ascii = (unsigned char)( k & 0xFF );
scan = (unsigned char)( k >> 8 );
if ( ascii == 0x0D ) { /* ENTER */
while ( cur < len ) { con_out( buf[2+cur] ); cur++; }
hist_save( bseg, boff, len ); /* store the original line */
hist_idx = -1;
len = fixup_cd_dir_backslash( buf, len );
buf[1] = (char)len;
buf[2+len] = 0x0D;
con_out(0x0D); con_out(0x0A);
return;
}
else if ( ascii == 0x09 ) { /* TAB: forward, end of line */
if ( cur < len ) { con_out(0x07); }
else {
len = do_complete( bseg, boff, len, +1 );
cur = len;
}
}
else if ( ascii == 0x08 ) { /* Backspace */
if ( cur > 0 ) {
cur--;
con_out(0x08);
for ( i = cur; i < len - 1; i++ ) buf[2+i] = buf[2+i+1];
len--;
for ( i = cur; i < len; i++ ) con_out( buf[2+i] );
con_out(' ');
cursor_left_n( len - cur + 1 );
}
comp_active = 0; hist_idx = -1;
}
else if ( ascii == 0x1B ) { /* ESC: clear line */
while ( cur < len ) { con_out( buf[2+cur] ); cur++; }
for ( i = 0; i < len; i++ ) { con_out(0x08); con_out(' '); con_out(0x08); }
len = 0; cur = 0;
comp_active = 0; hist_idx = -1;
}
else if ( ascii == 0x00 ) { /* Extended key */
if ( scan == 0x0F ) { /* Shift+TAB: backward */
if ( cur < len ) { con_out(0x07); }
else {
len = do_complete( bseg, boff, len, -1 );
cur = len;
}
continue; /* keep comp_active for cycling */
}
comp_active = 0;
if ( scan == 0x48 ) { /* Up: history */
if ( hist_total == 0 ) { con_out(0x07); continue; }
while ( cur < len ) { con_out( buf[2+cur] ); cur++; }
if ( hist_idx == -1 ) {
for ( i = 0; i < len && i < HIST_MAXLEN-1; i++ )
hist_tmp[i] = buf[2+i];
hist_tmp_len = len;
hist_idx = 0;
} else if ( hist_idx < hist_total - 1 ) {
hist_idx++;
} else { con_out(0x07); continue; }
{
int entry = (hist_head - 1 - hist_idx + HIST_COUNT*2) % HIST_COUNT;
if ( hist_load( entry ) )
len = line_replace( buf, len, hist_rec+1,
(unsigned char)hist_rec[0] );
cur = len;
}
}
else if ( scan == 0x50 ) { /* Down: history */
if ( hist_idx < 0 ) { con_out(0x07); continue; }
while ( cur < len ) { con_out( buf[2+cur] ); cur++; }
hist_idx--;
if ( hist_idx < 0 ) {
len = line_replace( buf, len, hist_tmp, hist_tmp_len );
} else {
int entry = (hist_head - 1 - hist_idx + HIST_COUNT*2) % HIST_COUNT;
if ( hist_load( entry ) )
len = line_replace( buf, len, hist_rec+1,
(unsigned char)hist_rec[0] );
}
cur = len;
}
else if ( scan == 0x4B ) { /* Left arrow */
if ( cur > 0 ) { cur--; con_out(0x08); }
}
else if ( scan == 0x4D ) { /* Right arrow */
if ( cur < len ) { con_out( buf[2+cur] ); cur++; }
}
else if ( scan == 0x47 ) { /* Home */
cursor_left_n( cur ); cur = 0;
}
else if ( scan == 0x4F ) { /* End */
while ( cur < len ) { con_out( buf[2+cur] ); cur++; }
}
else if ( scan == 0x53 ) { /* Del */
if ( cur < len ) {
for ( i = cur; i < len - 1; i++ ) buf[2+i] = buf[2+i+1];
len--;
for ( i = cur; i < len; i++ ) con_out( buf[2+i] );
con_out(' ');
cursor_left_n( len - cur + 1 );
}
}
else if ( scan == 0x52 ) { /* Ins: toggle mode */
ins ^= 1;
}
else if ( scan == 0x73 ) { /* Ctrl+Left: word jump */
int steps = 0;
while ( cur > 0 && buf[2+cur-1] == ' ' ) { cur--; steps++; }
while ( cur > 0 && buf[2+cur-1] != ' ' ) { cur--; steps++; }
cursor_left_n( steps );
}
else if ( scan == 0x74 ) { /* Ctrl+Right: word jump */
while ( cur < len && buf[2+cur] != ' ' )
{ con_out( buf[2+cur] ); cur++; }
while ( cur < len && buf[2+cur] == ' ' )
{ con_out( buf[2+cur] ); cur++; }
}
/* All other extended keys: ignore */
}
else if ( ascii >= 0x20 && ascii < 0x7F ) { /* Printable */
if ( cur == len ) {
/* Append */
if ( len < maxlen - 1 ) {
buf[2+len] = ascii; con_out(ascii); len++; cur++;
}
} else if ( ins ) {
/* Insert mid-line */
if ( len < maxlen - 1 ) {