/* parc * Copyright (C) 2025 Ekaitz Zarraga * * 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 . */ #include #include #include #include #include "piece-table.h" typedef struct _string { char *start; size_t length; } string; void string_init (string *str) { str->start = NULL; str->length = 0; } string read_file (const char *path) { /* * The buffer has to be freed later. */ string out; FILE *in; char *buff = NULL; size_t read = 0, total_size = 0, block_size = 1024; in = fopen (path, "r"); /* TODO: Error handling!*/ do { buff = realloc (buff, sizeof (*buff) * (total_size + block_size)); read = fread (buff + total_size, sizeof (*buff), block_size, in); total_size += read; } while (read == block_size ); buff = realloc (buff, sizeof (*buff) * total_size); fclose (in); out.start = buff; out.length = total_size; return out; } typedef struct _editor { piece_table *pt; const char *path; string orig; } editor; /* * https://texteditors.org/cgi-bin/wiki.pl?Implementing_Undo_For_Text_Editors */ editor * editor_create (void) { editor *ed = malloc (sizeof (*ed)); ed->pt = piece_table_create_from_str ("", 0); ed->path = NULL; string_init (&ed->orig); return ed; } void editor_open (editor *ed, const char *path) { ed->path = path; piece_table_destroy (ed->pt); ed->orig = read_file (ed->path); ed->pt = piece_table_create_from_str (ed->orig.start, ed->orig.length); } void editor_destroy (editor *ed) { free (ed->orig.start); piece_table_destroy (ed->pt); free (ed); } void editor_display (editor *ed) { /* Debug only */ size_t len = piece_table_length (ed->pt); char *disp = malloc (sizeof (*disp) * len + 1); piece_table_to_string (ed->pt, disp, len); printf ("%s", disp); free (disp); }