Browse Source

Implement debug saving to file

rexim 4 years ago
parent
commit
08b333b4d9
3 changed files with 26 additions and 11 deletions
  1. 19 0
      editor.c
  2. 1 0
      editor.h
  3. 6 11
      main.c

+ 19 - 0
editor.c

@@ -1,6 +1,8 @@
 #include <assert.h>
 #include <string.h>
 #include <stdbool.h>
+#include <stdio.h>
+#include <errno.h>
 #include "./editor.h"
 
 #define LINE_INIT_CAPACITY 1024
@@ -163,3 +165,20 @@ const char *editor_char_under_cursor(const Editor *editor)
     }
     return NULL;
 }
+
+void editor_save_to_file(const Editor *editor, const char *file_path)
+{
+    FILE *f = fopen(file_path, "w");
+    if (f == NULL) {
+        fprintf(stdout, "ERROR: could not open file `%s`: %s\n",
+                file_path, strerror(errno));
+        exit(1);
+    }
+
+    for (size_t row = 0; row < editor->size; ++row) {
+        fwrite(editor->lines[row].chars, 1, editor->lines[row].size, f);
+        fputc('\n', f);
+    }
+
+    fclose(f);
+}

+ 1 - 0
editor.h

@@ -21,6 +21,7 @@ typedef struct {
     size_t cursor_col;
 } Editor;
 
+void editor_save_to_file(const Editor *editor, const char *file_path);
 void editor_insert_text_before_cursor(Editor *editor, const char *text);
 void editor_insert_new_line(Editor *editor);
 void editor_backspace(Editor *editor);

+ 6 - 11
main.c

@@ -169,27 +169,18 @@ void render_cursor(SDL_Renderer *renderer, const Font *font)
     }
 }
 
-// TODO: Multiple lines
 // TODO: Save/Load file
 // TODO: Jump forward/backward by a word
 // TODO: Delete a word
 // TODO: Blinking cursor
+// TODO: Delete line
+// TODO: Split the line on Enter
 
 int main(int argc, char **argv)
 {
     (void) argc;
     (void) argv;
 
-    editor_insert_text_before_cursor(&editor, "dhjfhskjdfhkjshdf");
-    editor_insert_new_line(&editor);
-    editor_insert_text_before_cursor(&editor, "3j4k23l4j");
-    editor_insert_new_line(&editor);
-    editor_insert_text_before_cursor(&editor, "456kj356klj35l6j");
-    editor_insert_new_line(&editor);
-    editor_insert_text_before_cursor(&editor, "46jkl45jkljclslkj");
-    editor_insert_new_line(&editor);
-    editor_insert_text_before_cursor(&editor, "tjk5kfkdjgk");
-
     scc(SDL_Init(SDL_INIT_VIDEO));
 
     SDL_Window *window =
@@ -219,6 +210,10 @@ int main(int argc, char **argv)
                 }
                 break;
 
+                case SDLK_F2: {
+                    editor_save_to_file(&editor, "output");
+                } break;
+
                 case SDLK_RETURN: {
                     editor_insert_new_line(&editor);
                 } break;