-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
newtrodit_core_win.h
1622 lines (1396 loc) · 38.2 KB
/
newtrodit_core_win.h
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
/*
Newtrodit: A console text editor
Copyright (c) 2021-2023 anic17 Software
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>
*/
#pragma once
#ifndef _NEWTRODIT_CORE_H_
#define _NEWTRODIT_CORE_H_
#else
#error "A newtrodit_core file has already been included"
#endif
#include <string.h> // All string functions
#include <stdlib.h> // Some standard functions (malloc, calloc)
#include <stdio.h> // Standard I/O
#include <stdarg.h> // va_list
#include <errno.h> // errno
#include <Windows.h> // Console access
#include <conio.h> // getch()
#include <direct.h> // _access()
#include <process.h> // _beginthread()
#include <fcntl.h> // _setmode, _fileno
#include <ctype.h> // isxdigit, etc.
#include <wchar.h> // For UTF-8 support
#include <stdint.h> // uintptr_t
#include "../dialog.h"
/* =============================== SETTINGS ================================== */
#define _NEWTRODIT_OLD_SUPPORT 0 // Toggle support for old versions of Windows (Windows XP and below)
#define _NEWTRODIT_EXPERIMENTAL_RESTORE_BUFFER 1 // Toggle support for restoring buffer on exit (currently experimental)
#define DEBUG_MODE 1
#define TAB_WIDE_ 2
#define CURSIZE_ 20
#define CURSIZE_INS 80
#define MIN_BUFSIZE 256
#define LINE_MAX 8192
#define MAX_TABS 48 // Maximum number of files opened at once
#ifndef MAX_PATH
#define MAX_PATH 260
#endif
#if 1
#define HORIZONTAL_SCROLL
#endif
#ifndef __bool_true_false_are_defined
#define _bool_true_false_are_defined
typedef int bool;
#define false 0
#define true 1
#endif
#ifndef SIGTRAP
#define SIGTRAP 5
#endif
#ifndef UNDO_STACK_SIZE
#define UNDO_STACK_SIZE 2048
#endif
const char *filename_text_ = "Untitled"; // Default filename
#define DEFAULT_BUFFER_X 640
#define MAKE_INT64(hi, lo) ((LONGLONG(DWORD(hi) & 0xffffffff) << 32) | LONGLONG(DWORD(lo) & 0xffffffff)) // https://stackoverflow.com/a/21022647/12613647
// Only used for debugging, not for release
#if DEBUG_MODE
#define DEBUG \
PrintBottomString("OK. File:%s Line:%d\n", __FILE__, __LINE__); \
getch_n();
#else
#define DEBUG
#endif
#include "../globals.h"
enum ConsoleQueryList
{
XWINDOW = 1,
XBUFFER_SIZE = 2,
YWINDOW = 4,
YBUFFER_SIZE = 8,
XCURSOR = 16,
YCURSOR = 32,
COLOR = 64,
XMAX_WINDOW = 128,
YMAX_WINDOW = 256,
CURSOR_SIZE = 512,
CURSOR_VISIBLE = 1024,
};
int GetConsoleInfo(int type);
#define XSIZE GetConsoleInfo(XWINDOW)
#define YSIZE GetConsoleInfo(YWINDOW)
#define YSCROLL GetConsoleInfo(YWINDOW) - 2
#define BOTTOM GetConsoleInfo(YWINDOW) - 1
#define DEFAULT_ALLOC_SIZE 512
#define MACRO_ALLOC_SIZE 2048
#define _xpos Tab_stack[file_index].xpos // For simplicity
#define _ypos Tab_stack[file_index].ypos
int BUFFER_X = DEFAULT_BUFFER_X;
int BUFFER_Y = 6400;
int BUFFER_INCREMENT = 150; // How much to increment the buffer size by when it is full.
int BUFFER_INCREMENT_LOADFILE = 50; // When loading a file, how much to increment the buffer size by.
/* ============================ END OF SETTINGS ============================== */
#if !defined ENABLE_VIRTUAL_TERMINAL_PROCESSING || !defined DISABLE_NEWLINE_AUTO_RETURN
#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
#define DISABLE_NEWLINE_AUTO_RETURN 0x0008
#endif
#ifdef _WIN32
const char PATHTOKENS[] = "\\/";
#else
const char PATHTOKENS[] = "/";
#endif
typedef struct Startup_info
{
char *location; // Location of the file (full path)
char *dir; // Directory that is changed with 'cd' or 'chdir'
int xsize; // X size of the window
int ysize; // Y size of the window
int xbuf;
int ybuf;
int color;
char **argv;
int argc;
int manual_open;
LPSTR console_buffer; // Console buffer contents
bool save_buffer;
char *log_file_name;
bool using_log;
struct cursor
{
int x;
int y;
} cursor;
} Startup_info; // Startup data when Newtrodit is started
typedef struct Undo_stack
{
char *line;
int line_count;
int line_pos;
size_t size;
bool create_nl;
bool delete_nl;
} Undo_stack;
typedef struct Syntax_info
{
// File and file type
char *syntax_file;
char *syntax_lang;
char *separators;
// Colors
int capital_color;
int comment_color;
int default_color;
int num_color;
int override_color;
int quote_color;
// Various size parameters
size_t keyword_count;
size_t comment_count;
size_t enclosing_count;
size_t capital_min; // Minimum length of a word to be highlighted as capital
bool capital_enabled;
bool multi_line_comment;
bool single_quotes;
bool finish_quotes;
// Highlight pairs of brackets, parenthesis, and square brackets {}, (), [] (not supported as of 0.6)
size_t bracket_pair_count;
size_t parenthesis_pair_count;
size_t square_bracket_pair_count;
// Keyword info
char **comments;
char **keywords;
char **enclosing_char; // Enclosing quote-like characters
int *color;
} Syntax_info; // Syntax highlighting information
typedef struct Compiler
{
char *path;
char *flags;
char *output;
} Compiler; // Compiler settings, used for macro building command lines
typedef struct File_info
{
char *filename;
char *fullpath;
char *language; // Language (e.g: PowerShell, C, C++, etc.)
bool is_readonly;
int permissions;
bool is_loaded;
bool utf8;
// File information
int xpos;
int ypos;
int display_x; // X scrolling
int display_y; // Y scrolling
int last_dispy; // Used for line number highlighting
int last_y;
int last_pos_scroll; // Last X position before scrolling
bool scrolled_x; // If the cursor is scrolled to the right
bool scrolled_y; // If the file is scrolled vertically
char **strsave; // Buffer to store the file
int **tabcount; // Number of tabs in the line
size_t *linesize; // Size of the line
size_t linecount;
size_t linecount_wide;
long long size;
size_t bufx;
size_t bufy;
char *newline;
bool is_saved; // Replacing old variables 'isSaved', 'isModified', 'isUntitled'
bool is_modified;
bool is_untitled;
Undo_stack *Ustack;
Syntax_info Syntaxinfo;
Compiler Compilerinfo;
HANDLE hFile; // File handle
FILETIME fwrite_time;
FILETIME fread_time;
select_t selection;
} File_info; // File information. This is used to store all the information about the file.
Startup_info SInf;
File_info Tab_stack[MAX_TABS];
DWORD dwStdoutMode, dwStdinMode;
HANDLE hOldBuf = INVALID_HANDLE_VALUE, hNewBuf = INVALID_HANDLE_VALUE;
bool used_tab_indexes[MAX_TABS];
/* =================================== TERM ===================================== */
/* -------------------------------- TERM CURSOR ---------------------------------- */
/* Set cursor's X, Y position */
void gotoxy(int x, int y)
{
COORD dwPos = {x, y};
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), dwPos);
}
/* Change the visibility of the terminal cursor */
void DisplayCursor(bool disp)
{
CONSOLE_CURSOR_INFO cursor;
cursor.bVisible = disp;
cursor.dwSize = CURSIZE;
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor);
}
/* ---------------------------- TERM SCREEN CONTROL ------------------------------ */
int VTSettings(bool enabled)
{
#ifdef _WIN32
DWORD lmode; // Process ANSI escape sequences
HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleMode(hStdout, &lmode);
if (enabled)
{
lmode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING & ~DISABLE_NEWLINE_AUTO_RETURN;
}
else
{
lmode &= ~ENABLE_VIRTUAL_TERMINAL_PROCESSING | DISABLE_NEWLINE_AUTO_RETURN;
}
return SetConsoleMode(hStdout, lmode);
#endif
}
/* Enter or quit alternate screen buffer (unfinished) */
int SetAltConsoleBuffer(bool enabled)
{
#if _NEWTRODIT_EXPERIMENTAL_RESTORE_BUFFER
if (VTSettings(true))
{
fputs(enabled ? "\e[?1049h" : "\e[?1049l", stdout);
VTSettings(false);
return 1;
}
#endif
return 0;
}
/* Restore original screen buffer (if not already active) */
int RestoreConsoleBuffer()
{
SetConsoleActiveScreenBuffer(hOldBuf);
CloseHandle(hNewBuf);
SetStdHandle(STD_OUTPUT_HANDLE, hOldBuf);
fclose(stdout);
fclose(stderr);
return 0;
}
/* Set default FG color for text */
void SetColor(int color)
{
if (color > 255) // RGB
{
// TODO: Add RGB support for Windows
}
else
{
HANDLE hConsoleColor = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsoleColor, color);
}
}
/* Set color of a specific terminal cell (specified by X, and Y) */
int SetCharColor(size_t count, int color, int x, int y)
{
if (x < 0 || y < 0)
{
return 0;
}
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
COORD writePos = {x, y};
DWORD dwWritten = 0;
FillConsoleOutputAttribute(hConsole, color, count, writePos, &dwWritten);
return 1;
}
/* Clear entire screen (keeping terminal cursor in the same location) */
void ClearScreen()
{
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csbi;
DWORD count, cellCount;
COORD homeCoords = {0, 0};
if (hStdOut == INVALID_HANDLE_VALUE)
{
return;
}
if (!GetConsoleScreenBufferInfo(hStdOut, &csbi))
{
return;
}
cellCount = csbi.dwSize.X * csbi.dwSize.Y; // All the buffer, not only the visible part
FillConsoleOutputCharacter(hStdOut, L' ', cellCount, homeCoords, &count);
FillConsoleOutputAttribute(hStdOut, csbi.wAttributes, cellCount, homeCoords, &count);
SetConsoleCursorPosition(hStdOut, homeCoords);
}
/* Clear a section of the screen
*
* Think of it as a rectangle. All this function does is create a rectangle
* of a specified width and height at a position on the screen. Anything in
* the rectangle will be cleared are replaced by a empty cell.
*/
void ClearPartial(int x, int y, int width, int height) // Clears a section of the screen
{
if (!width || !height)
{
return;
}
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csbi;
DWORD count;
COORD homeCoords = {x, y};
if (hStdOut == INVALID_HANDLE_VALUE)
{
return;
}
if (!GetConsoleScreenBufferInfo(hStdOut, &csbi))
{
return;
}
for (int i = 0; i < height; i++)
{
FillConsoleOutputCharacter(hStdOut, ' ', width, homeCoords, &count);
FillConsoleOutputAttribute(hStdOut, csbi.wAttributes, width, homeCoords, &count);
homeCoords.Y++;
}
homeCoords.Y = y;
SetConsoleCursorPosition(hStdOut, homeCoords);
return;
}
/* Function for printing a string on the last row of the screen */
size_t strlen_n(const char *s) // Safe strlen() version
{
if (!s)
{
return 0;
}
return strlen(s);
}
void PrintBottomString(char *str, ...)
{
va_list args;
va_start(args, str);
int xs = XSIZE;
char *printbuf = calloc(xs + 1, sizeof(char));
vsnprintf(printbuf, xs + 1, str, args);
size_t len = strlen_n(printbuf);
ClearPartial(len, BOTTOM, xs - len, 1);
gotoxy(0, BOTTOM);
printf("%.*s", xs, printbuf); // Don't get out of the buffer
free(printbuf);
va_end(args);
return;
}
/* Set size of the console window */
void SetConsoleSize(int xsize, int ysize, int xbuf, int ybuf)
{
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
COORD a = {xsize, ysize};
SMALL_RECT rect;
rect.Top = 0;
rect.Left = 0;
rect.Bottom = xsize - 2;
rect.Right = ysize - 2;
SetConsoleScreenBufferSize(handle, a);
SetConsoleWindowInfo(handle, 1, &rect);
SetConsoleScreenBufferSize(handle, a);
}
/* Convert a string hex to a decimal number
*
* Makes life a bit easier by removing repeditive calls
*/
int HexStrToDec(char *s)
{
return strtol(s, NULL, 16);
}
int atoi_tf(char *s)
{
if (!_stricmp(s, "true") || atoi(s) == 1)
{
return 1;
}
return 0;
}
int SetBoolValue(int *boolv, char *s)
{
int retval = atoi_tf(s);
*boolv = !!retval;
return retval;
}
int IsNumberString(char *s)
{
for (size_t i = 0; i < strlen_n(s); i++)
{
if (!isdigit(s[i]))
{
return 0;
}
}
return 1;
}
char *Substring(size_t start, size_t count, const char *str)
{
char *new_str = calloc(sizeof(char), count + 1);
strncat(new_str, str + start, count);
return new_str;
}
char *ParseHexString(char *hexstr)
{
int hstd_return = 0, index = 0;
char *hex_prefix = "0x";
char *ptr_tokenize;
size_t max_len = 2 * (strlen_n(hexstr) + 1);
char *str = calloc(max_len, sizeof(char));
if (!str)
{
last_known_exception = NEWTRODIT_ERROR_OUT_OF_MEMORY;
return NULL;
}
char *delims = ", \t\n";
if (!strpbrk(hexstr, "01234567890abcdefABCDEF")) // Make sure strings contains hex characters
{
return hexstr;
}
// Convert the string to a hex string
ptr_tokenize = strtok(hexstr, delims);
while (ptr_tokenize != NULL)
{
strlwr(ptr_tokenize);
if (!strncmp(ptr_tokenize, hex_prefix, strlen_n(hex_prefix))) // Only parse if the strings starts with 0x
{
hstd_return = HexStrToDec(ptr_tokenize);
if (hstd_return % 256) // Ignore null values
{
str[index] = HexStrToDec(ptr_tokenize);
index++;
}
}
ptr_tokenize = strtok(NULL, delims);
}
return hexstr;
}
/* =============================== END OF TERM ================================== */
/* Get line length, ignoring linefeeds */
size_t NoLfLen(char *s)
{
char *exclude = Tab_stack[file_index].newline;
if (!strchr(exclude, '\n')) // Always exclude a newline (\n) even if it's not present
{
// strncat(exclude, "\n", 2);
}
size_t len = 0;
while (*s)
{
if (!strchr(exclude, *s))
{
len++;
}
s++;
}
return len;
}
/* Count the number of chars in a string, chars to search set via delim.
*
* E.g. `TokCount(str, "!*")` will return the number of occurrences of `!`
* and `*` in `s`
*/
int TokCount(char *s, char *delim)
{
int count = 0;
for (int i = 0; i < strlen_n(s); i++)
{
for (int j = 0; j < strlen_n(delim); j++)
{
if (s[i] == delim[j])
{
count++;
}
}
}
return count;
}
/* ? */
int TokLastPos(char *s, const char *token)
{
int lastpos = -1;
if (!s || !token)
{
return lastpos;
}
for (int i = 0; i < strlen_n(s); i++)
{
for (int j = 0; j < strlen_n(token); j++)
{
if (s[i] == token[j])
{
lastpos = i;
}
}
}
return lastpos;
}
/* ? */
char *StrLastTok(char *tok, const char *char_token)
{
if (!tok | !char_token)
{
return tok;
}
int pos = TokLastPos(tok, char_token);
return tok + pos + 1;
}
/* ? */
int TokBackPos(char *s, char *p, char *p2)
{
/*
p is the delimiter on the last position
p2 is the delimiter for an index of + 1
*/
for (int i = strlen_n(s); i > 0; i--)
{
for (int k = 0; k < strlen_n(p2); k++)
{
if (s[i] == p2[k])
{
while (s[i] == p2[k])
{
i--;
}
return i + 2;
}
}
for (int j = 0; j < strlen_n(p); j++)
{
if (s[i] == p[j])
{
while (s[i] == p[j])
{
i--;
}
return i + 1;
}
}
}
return 0;
}
/* Base name (no path, no extension) */
char *GetBaseName(char *file)
{
char *ptr = StrLastTok(file, PATHTOKENS), *pchar = strrchr(ptr, '.'); // Remove the path
char *basename = calloc(MAX_PATH + 1, sizeof(char));
if (!pchar)
{
return ptr;
}
memcpy(basename, ptr, pchar - ptr); // Copy until the last dot
return basename;
}
/* Compare string and check for tokens */
int strcmptok(char *s, char *short_s, char *tok)
{
if (!s || !short_s || !tok)
{
return -1;
}
if (!strncmp(s, short_s, strlen_n(short_s)))
{
for (size_t k = 0; k < strlen_n(tok); k++)
{
if (s[strlen_n(short_s)] == tok[k])
{
return 0;
}
}
}
return 1;
}
/* Print tab of set size? */
char *PrintTab(int tab_count)
{
char *s = calloc(sizeof(char), (tab_count + 1));
memset(s, 32, tab_count);
return s;
}
/* ============================ STRING MANIPULATION ============================== */
/* Custom strtok() function */
char *strtok_n(char *str, char *tokens)
{
if (!str || !tokens)
{
return NULL;
}
size_t span = strcspn(str, tokens);
if (span == strlen_n(str))
{
return NULL;
}
return Substring(0, span, str);
}
/* Safe version of strcpy() and strncpy() */
char *strncpy_n(char *dest, const char *src, size_t count)
{
// Better version that strncpy() because it always null terminates strings
if (count)
{
memset(dest, 0, count);
strncat(dest, src, count);
return dest;
}
return NULL;
}
/* ? */
size_t strrpbrk(char *s, char *find) // Reverse strpbrk, just like strrchr but for multiple characters
{
size_t findlen = strlen_n(find);
size_t slen = strlen_n(s);
for (size_t i = slen; i > 0; i--)
{
for (size_t j = 0; j < findlen; j++)
{
if (s[i - 1] == find[j])
{
return i - 1;
}
}
}
return 0;
}
size_t strcmpcount(char *s1, char *s2)
{
size_t l1 = strlen_n(s1);
size_t l2 = strlen_n(s2);
if (!l1 || !l2)
{
return 0;
}
size_t complen = l1 > l2 ? l2 : l1, cnt = 0;
for (int i = 0; i < complen; i++)
{
if (s1[i] == s2[i])
{
cnt++;
}
else
{
return cnt;
}
}
return cnt;
}
/* Find a needle in a haystack.
*
* Search a string for a sub-string
*/
int FindString(char *str, char *find)
{
char *ptr = strstr(str, find);
return (ptr) ? (ptr - str) : strlen_n(str);
}
/* ? */
// Remove the quotes on a string
char *RemoveQuotes(char *s)
{
size_t len = strlen_n(s);
if (s[0] == '\"' && s[len - 1] == '\"')
{
memmove(s, s + 1, len - 2);
s[len] = '\0';
}
return s;
}
// Replace a string
char *ReplaceString(char *s, char *find, char *replace, int *occurenceCount)
{
char *result;
int c = 0;
int replacelen = strlen_n(replace);
int findlen = strlen_n(find);
size_t sz = strlen_n(s) + replacelen + 1;
// BUG: Assigning to 'char *' from incompatible type 'void *'
result = malloc(sz);
if (!result)
{
last_known_exception = NEWTRODIT_ERROR_OUT_OF_MEMORY;
return s;
}
for (size_t i = 0; s[i] != '\0'; i++)
{
if (strncmp(s + i, find, findlen) == 0)
{
strcpy(result + c, replace);
if (replacelen > findlen) // Allocate more memory in case it is needed
{
sz += replacelen - findlen;
result = realloc(result, sz);
}
(*occurenceCount)++;
c += replacelen;
i += findlen - 1;
}
else
{
result[c++] = s[i];
}
}
result[c] = '\0';
return result;
}
/* Safely join two strings by allocating memory */
char *join(char *s1, const char *s2)
{
if (!s2)
{
return s1;
}
size_t arr_size = strlen_n(s1) + strlen_n(s2) + 1;
char *s = calloc(arr_size, sizeof(char));
if (!s)
{
last_known_exception = NEWTRODIT_ERROR_OUT_OF_MEMORY;
return NULL;
}
strncpy_n(s, s1, arr_size);
strncat(s, s2, arr_size);
return s;
}
/* Returns a string where all characters are lower case */
char *strlwr(char *s)
{
for (int i = 0; i < strlen_n(s); i++)
{
s[i] = tolower(s[i]);
}
return s;
}
char *InsertStr(char *s1, const char *s2, size_t pos, bool allocstring, size_t maxsize)
{
size_t l1 = strlen_n(s1), l2 = strlen_n(s2);
char *new_str;
if (allocstring)
{
new_str = calloc(l1 + l2 + 3, sizeof(char));
memcpy(new_str, s1, strlen_n(s1));
if (!new_str)
{
last_known_exception = NEWTRODIT_ERROR_OUT_OF_MEMORY;
return NULL;
}
}
else
{
new_str = s1;
}
if (l1 + l2 < maxsize && !allocstring)
{
memmove(new_str + pos + l2, new_str + pos, l1);
memcpy(new_str + pos, s2, l2);
} else {
return NULL;
}
new_str[strlen_n(new_str)] = '\0';
return new_str;
}
// Insert a single character at a specific index
char *InsertChar(char *str, char c, int pos, bool allocstring, size_t maxsz)
{
char s2[2] = {c, '\0'};
return InsertStr(str, s2, pos, allocstring, maxsz);
}
// Delete a string on a specified position
char *DeleteStr(char *str, int pos, size_t count)
{
size_t len = strlen_n(str);
if (pos + count > len)
{
return str;
}
memmove(str + pos, str + pos + count, len - (pos + count));
str[len - count] = '\0';
return str;
}
char *DeleteChar(char *str, int pos) // This function is limited to lines with a length of 2^31 - 1 characters
{
size_t len = strlen_n(str);
if (len > pos)
{
memmove(str + pos, str + pos + 1, len - pos);
str[strlen_n(str)] = '\0';
}
return str;
}
char *InsertRow(char **arr, int startpos, size_t arrsize, char *arrvalue)
{
for (int i = arrsize; i > startpos; i--)
{
arr[i] = arr[i - 1];
}
arr[startpos + 1] = arrvalue;
return arr[startpos];
}
/* ? */
char *DeleteRow(char **arr, int startpos, size_t arrsize)
{
for (int i = startpos; i < arrsize; i++)
{
arr[i] = arr[i + 1];
}
return arr[startpos];
}
/* ? */
char *InsertDeletedRow(File_info *tstack)
{
int n = NoLfLen(tstack->strsave[tstack->ypos]);
strncat(tstack->strsave[tstack->ypos - 1], tstack->strsave[tstack->ypos], strlen_n(tstack->strsave[tstack->ypos])); // Concatenate the next line
memset(tstack->strsave[tstack->ypos] + n, 0, BUFFER_X - n); // Empty the new line
if (tstack->ypos != 1)
{
// Add the newline string only if the ypos isn't 1
strncat(tstack->strsave[tstack->ypos - 1], tstack->newline, strlen_n(tstack->newline));
}
// Delete the old row, shifting other rows down
DeleteRow(tstack->strsave, tstack->ypos, tstack->bufy - 1);
// Decrease the yp pointer by one
tstack->xpos = NoLfLen(tstack->strsave[tstack->ypos]);
last_known_exception = NEWTRODIT_ERROR_OUT_OF_MEMORY;
return tstack->strsave[tstack->ypos];
}
/* ========================= END OF STRING MANIPULATION ========================== */
/* =================================== SYSTEM =================================== */
/* Improved getch(), returns all codes in a single call */
int getch_n()
{
int gc_n = 0;
gc_n = getch();
if (gc_n == 0)
{
gc_n = getch();
gc_n |= BIT_ESC0;
}
else if (gc_n == 0xE0)
{
gc_n = getch();