diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/app.c | 1578 | ||||
| -rw-r--r-- | src/buffers.c | 701 | ||||
| -rw-r--r-- | src/config.c | 293 | ||||
| -rw-r--r-- | src/ecex.c | 1630 | ||||
| -rw-r--r-- | src/eval.c | 482 | ||||
| -rw-r--r-- | src/font.c | 258 | ||||
| -rw-r--r-- | src/main.c | 164 | ||||
| -rw-r--r-- | src/render.c | 613 | ||||
| -rw-r--r-- | src/util.c | 71 |
9 files changed, 5790 insertions, 0 deletions
diff --git a/src/app.c b/src/app.c new file mode 100644 index 0000000..3ae368c --- /dev/null +++ b/src/app.c @@ -0,0 +1,1578 @@ +#include "app.h" +#include "common.h" + +#include <dirent.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <sys/stat.h> + +void app_message(app_t *app, const char *msg) { + if (!app || !msg) return; + + snprintf(app->message, sizeof(app->message), "%s", msg); + app->dirty = 1; +} + +static const char *app_clipboard_get(void *userdata) { + app_t *app = userdata; + if (!app || !app->window) return NULL; + return glfwGetClipboardString(app->window); +} + +static void app_clipboard_set(void *userdata, const char *text) { + app_t *app = userdata; + if (!app || !app->window || !text) return; + glfwSetClipboardString(app->window, text); +} + +static void app_reset_completion(app_t *app) { + if (!app) return; + + app->completion_active = 0; + app->completion_query[0] = '\0'; + app->completion_index = 0; + app->completion_count = 0; +} + +static void app_set_minibuffer(app_t *app, const char *text) { + if (!app || !text) return; + + snprintf(app->minibuffer, sizeof(app->minibuffer), "%s", text); + app->minibuffer_len = strlen(app->minibuffer); + app->dirty = 1; +} + +static void app_reset_prompt_completion(app_t *app) { + if (!app) return; + + app->prompt_completion_active = 0; + app->prompt_completion_query[0] = '\0'; + app->prompt_completion_index = 0; + app->prompt_completion_count = 0; +} + +static void app_set_prompt_input(app_t *app, const char *text) { + if (!app || !text) return; + + snprintf(app->prompt_input, sizeof(app->prompt_input), "%s", text); + app->prompt_input_len = strlen(app->prompt_input); + app->dirty = 1; +} + +static char *app_expand_user_path(const char *path) { + if (!path) return NULL; + + if (path[0] != '~' || (path[1] != '\0' && path[1] != '/')) { + char *copy = malloc(strlen(path) + 1); + if (!copy) return NULL; + strcpy(copy, path); + return copy; + } + + const char *home = getenv("HOME"); + if (!home || !home[0]) { + char *copy = malloc(strlen(path) + 1); + if (!copy) return NULL; + strcpy(copy, path); + return copy; + } + + size_t home_len = strlen(home); + size_t rest_len = strlen(path + 1); + + char *expanded = malloc(home_len + rest_len + 1); + if (!expanded) return NULL; + + memcpy(expanded, home, home_len); + memcpy(expanded + home_len, path + 1, rest_len + 1); + return expanded; +} + +typedef struct command_candidate { + const char *name; + int score; + size_t order; +} command_candidate_t; + +static int ascii_lower(int c) { + if (c >= 'A' && c <= 'Z') return c - 'A' + 'a'; + return c; +} + +static int ascii_strncasecmp_local(const char *a, const char *b, size_t n) { + for (size_t i = 0; i < n; i++) { + int ac = ascii_lower((unsigned char)a[i]); + int bc = ascii_lower((unsigned char)b[i]); + + if (ac != bc || ac == '\0' || bc == '\0') { + return ac - bc; + } + } + + return 0; +} + +static int ascii_contains_ci(const char *haystack, const char *needle) { + if (!haystack || !needle) return 0; + if (needle[0] == '\0') return 1; + + size_t needle_len = strlen(needle); + + for (size_t i = 0; haystack[i]; i++) { + if (ascii_strncasecmp_local(haystack + i, needle, needle_len) == 0) { + return 1; + } + } + + return 0; +} + +static int command_fuzzy_score(const char *candidate, const char *query) { + if (!candidate || !query) return -1; + + if (query[0] == '\0') { + return 0; + } + + int score = 0; + int consecutive = 0; + int last_match = -1; + + size_t ci = 0; + size_t qi = 0; + + while (candidate[ci] && query[qi]) { + char c = candidate[ci]; + char q = query[qi]; + + if (c >= 'A' && c <= 'Z') c = (char)(c - 'A' + 'a'); + if (q >= 'A' && q <= 'Z') q = (char)(q - 'A' + 'a'); + + if (c == q) { + score += 10; + + if ((int)ci == last_match + 1) { + consecutive++; + score += 5 * consecutive; + } else { + consecutive = 0; + } + + if (ci == 0) { + score += 20; + } + + if (ci > 0 && + (candidate[ci - 1] == '-' || + candidate[ci - 1] == '_' || + candidate[ci - 1] == ' ')) { + score += 15; + } + + last_match = (int)ci; + qi++; + } + + ci++; + } + + if (query[qi] != '\0') { + return -1; + } + + score -= (int)strlen(candidate); + + if (strncmp(candidate, query, strlen(query)) == 0) { + score += 100; + } + + if (ascii_contains_ci(candidate, query)) { + score += 75; + } + + return score; +} + +static int compare_command_candidates(const void *a, const void *b) { + const command_candidate_t *ca = (const command_candidate_t *)a; + const command_candidate_t *cb = (const command_candidate_t *)b; + + if (ca->score != cb->score) { + return cb->score - ca->score; + } + + if (ca->order < cb->order) return -1; + if (ca->order > cb->order) return 1; + return 0; +} + +static command_candidate_t *collect_command_candidates(ecex_t *ed, + const char *query, + size_t *out_count) { + if (out_count) *out_count = 0; + if (!ed || !query || ed->command_count == 0) return NULL; + + command_candidate_t *items = malloc(ed->command_count * sizeof(*items)); + if (!items) return NULL; + + size_t count = 0; + + for (size_t i = 0; i < ed->command_count; i++) { + const char *name = ed->commands[i].name; + int score = command_fuzzy_score(name, query); + + if (score >= 0) { + items[count].name = name; + items[count].score = score; + items[count].order = i; + count++; + } + } + + if (count == 0) { + free(items); + return NULL; + } + + qsort(items, count, sizeof(*items), compare_command_candidates); + + if (out_count) *out_count = count; + return items; +} + +static const char *command_candidate_at(ecex_t *ed, + const char *query, + size_t index, + size_t *out_count) { + size_t count = 0; + command_candidate_t *items = collect_command_candidates(ed, query, &count); + if (!items || count == 0) return NULL; + + const char *name = items[index % count].name; + + if (out_count) { + *out_count = count; + } + + free(items); + return name; +} + +typedef struct path_candidate { + char *path; + int score; + int is_dir; + size_t order; +} path_candidate_t; + +static void free_path_candidates(path_candidate_t *items, size_t count) { + if (!items) return; + + for (size_t i = 0; i < count; i++) { + free(items[i].path); + } + + free(items); +} + +static int compare_path_candidates(const void *a, const void *b) { + const path_candidate_t *pa = (const path_candidate_t *)a; + const path_candidate_t *pb = (const path_candidate_t *)b; + + if (pa->score != pb->score) { + return pb->score - pa->score; + } + + if (pa->is_dir != pb->is_dir) { + return pb->is_dir - pa->is_dir; + } + + int cmp = strcmp(pa->path, pb->path); + if (cmp != 0) return cmp; + + if (pa->order < pb->order) return -1; + if (pa->order > pb->order) return 1; + return 0; +} + +static int split_path_query(const char *query, + char *display_dir, + size_t display_dir_size, + char *fs_dir, + size_t fs_dir_size, + char *needle, + size_t needle_size) { + if (!query || !display_dir || !fs_dir || !needle) return -1; + + const char *last_slash = strrchr(query, '/'); + + if (last_slash) { + size_t dir_len = (size_t)(last_slash - query) + 1; + if (dir_len >= display_dir_size) dir_len = display_dir_size - 1; + + memcpy(display_dir, query, dir_len); + display_dir[dir_len] = '\0'; + + snprintf(needle, needle_size, "%s", last_slash + 1); + } else { + display_dir[0] = '\0'; + snprintf(needle, needle_size, "%s", query); + } + + if (display_dir[0] == '\0') { + snprintf(fs_dir, fs_dir_size, "."); + } else { + char *expanded = app_expand_user_path(display_dir); + if (!expanded) return -1; + + snprintf(fs_dir, fs_dir_size, "%s", expanded); + free(expanded); + } + + return 0; +} + +static char *join_display_path(const char *display_dir, + const char *name, + int is_dir) { + size_t dir_len = display_dir ? strlen(display_dir) : 0; + size_t name_len = name ? strlen(name) : 0; + size_t slash_len = is_dir ? 1 : 0; + + char *out = malloc(dir_len + name_len + slash_len + 1); + if (!out) return NULL; + + if (dir_len) memcpy(out, display_dir, dir_len); + if (name_len) memcpy(out + dir_len, name, name_len); + if (is_dir) out[dir_len + name_len] = '/'; + out[dir_len + name_len + slash_len] = '\0'; + return out; +} + +static path_candidate_t *collect_path_candidates(const char *query, + size_t *out_count) { + if (out_count) *out_count = 0; + if (!query) return NULL; + + char display_dir[1024]; + char fs_dir[1024]; + char needle[512]; + + if (split_path_query(query, + display_dir, + sizeof(display_dir), + fs_dir, + sizeof(fs_dir), + needle, + sizeof(needle)) != 0) { + return NULL; + } + + DIR *dir = opendir(fs_dir); + if (!dir) return NULL; + + size_t cap = 32; + size_t count = 0; + size_t order = 0; + path_candidate_t *items = malloc(cap * sizeof(*items)); + if (!items) { + closedir(dir); + return NULL; + } + + struct dirent *entry = NULL; + while ((entry = readdir(dir)) != NULL) { + const char *name = entry->d_name; + + if (strcmp(name, ".") == 0) { + continue; + } + + if (name[0] == '.' && needle[0] != '.' && strcmp(name, "..") != 0) { + continue; + } + + int score = command_fuzzy_score(name, needle); + if (score < 0) { + order++; + continue; + } + + char fs_path[2048]; + if (strcmp(fs_dir, ".") == 0) { + snprintf(fs_path, sizeof(fs_path), "%s", name); + } else { + size_t len = strlen(fs_dir); + snprintf(fs_path, + sizeof(fs_path), + "%s%s%s", + fs_dir, + (len > 0 && fs_dir[len - 1] == '/') ? "" : "/", + name); + } + + struct stat st; + int is_dir = stat(fs_path, &st) == 0 && S_ISDIR(st.st_mode); + + if (count == cap) { + size_t new_cap = cap * 2; + path_candidate_t *new_items = realloc(items, new_cap * sizeof(*items)); + if (!new_items) break; + items = new_items; + cap = new_cap; + } + + items[count].path = join_display_path(display_dir, name, is_dir); + if (!items[count].path) continue; + + items[count].score = score + (is_dir ? 20 : 0); + items[count].is_dir = is_dir; + items[count].order = order; + count++; + order++; + } + + closedir(dir); + + if (count == 0) { + free(items); + return NULL; + } + + qsort(items, count, sizeof(*items), compare_path_candidates); + + if (out_count) *out_count = count; + return items; +} + +static const char *path_candidate_at(const char *query, + size_t index, + size_t *out_count) { + static char candidate[1024]; + + size_t count = 0; + path_candidate_t *items = collect_path_candidates(query, &count); + if (!items || count == 0) { + free_path_candidates(items, count); + return NULL; + } + + snprintf(candidate, sizeof(candidate), "%s", items[index % count].path); + + if (out_count) { + *out_count = count; + } + + free_path_candidates(items, count); + return candidate; +} + +static void app_update_prompt_completion_preview(app_t *app) { + if (!app || !app->prompt_completion_active) return; + + size_t count = 0; + path_candidate_t *items = collect_path_candidates(app->prompt_completion_query, &count); + if (!items || count == 0) { + free_path_candidates(items, count); + app->prompt_completion_preview_start = 0; + app->prompt_completion_preview_count = 0; + return; + } + + size_t max_preview = sizeof(app->prompt_completion_preview) / + sizeof(app->prompt_completion_preview[0]); + + size_t start = 0; + if (app->prompt_completion_index >= max_preview) { + start = app->prompt_completion_index - max_preview + 1; + } + + app->prompt_completion_preview_start = start; + app->prompt_completion_preview_count = 0; + + for (size_t i = 0; i < max_preview && start + i < count; i++) { + snprintf(app->prompt_completion_preview[i], + sizeof(app->prompt_completion_preview[i]), + "%s", + items[start + i].path); + app->prompt_completion_preview_count++; + } + + free_path_candidates(items, count); +} + +static void app_begin_prompt_completion(app_t *app, int direction) { + if (!app) return; + + snprintf(app->prompt_completion_query, + sizeof(app->prompt_completion_query), + "%s", + app->prompt_input); + + size_t count = 0; + path_candidate_t *items = collect_path_candidates(app->prompt_completion_query, &count); + + if (!items || count == 0) { + free_path_candidates(items, count); + app_reset_prompt_completion(app); + app_message(app, "No file completions"); + app->mode = APP_MODE_PROMPT; + return; + } + + app->prompt_completion_active = 1; + app->prompt_completion_count = count; + app->prompt_completion_index = direction < 0 ? count - 1 : 0; + + app_set_prompt_input(app, items[app->prompt_completion_index].path); + free_path_candidates(items, count); + app_update_prompt_completion_preview(app); +} + +static void app_cycle_prompt_completion(app_t *app, int delta) { + if (!app) return; + + if (!app->prompt_completion_active || app->prompt_completion_count == 0) { + app_begin_prompt_completion(app, delta); + return; + } + + if (delta < 0) { + app->prompt_completion_index = app->prompt_completion_index == 0 + ? app->prompt_completion_count - 1 + : app->prompt_completion_index - 1; + } else { + app->prompt_completion_index = + (app->prompt_completion_index + 1) % app->prompt_completion_count; + } + + size_t count = 0; + const char *candidate = path_candidate_at(app->prompt_completion_query, + app->prompt_completion_index, + &count); + + if (!candidate || count == 0) { + app_reset_prompt_completion(app); + return; + } + + app->prompt_completion_count = count; + app_set_prompt_input(app, candidate); + app_update_prompt_completion_preview(app); +} + +static void app_begin_completion(app_t *app, int direction) { + if (!app) return; + + snprintf(app->completion_query, + sizeof(app->completion_query), + "%s", + app->minibuffer); + + size_t count = 0; + command_candidate_t *items = + collect_command_candidates(app->ed, app->completion_query, &count); + + if (!items || count == 0) { + free(items); + app_reset_completion(app); + app_message(app, "No command completions"); + app->mode = APP_MODE_MX; + return; + } + + app->completion_active = 1; + app->completion_count = count; + + if (direction < 0) { + app->completion_index = count - 1; + } else { + app->completion_index = 0; + } + + app_set_minibuffer(app, items[app->completion_index].name); + free(items); +} + +static void app_cycle_completion(app_t *app, int delta) { + if (!app) return; + + if (!app->completion_active || app->completion_count == 0) { + app_begin_completion(app, delta); + return; + } + + if (delta < 0) { + if (app->completion_index == 0) { + app->completion_index = app->completion_count - 1; + } else { + app->completion_index--; + } + } else { + app->completion_index = + (app->completion_index + 1) % app->completion_count; + } + + size_t count = 0; + const char *candidate = command_candidate_at(app->ed, + app->completion_query, + app->completion_index, + &count); + + if (!candidate || count == 0) { + app_reset_completion(app); + return; + } + + app->completion_count = count; + app_set_minibuffer(app, candidate); +} + +static void app_enter_mx(app_t *app) { + app->mode = APP_MODE_MX; + app->minibuffer[0] = '\0'; + app->minibuffer_len = 0; + app->prefix[0] = '\0'; + app->prefix_len = 0; + app->message[0] = '\0'; + app_reset_completion(app); + app->dirty = 1; +} + +static void app_cancel_mx(app_t *app) { + app->mode = APP_MODE_EDIT; + app->minibuffer[0] = '\0'; + app->minibuffer_len = 0; + app_reset_completion(app); + app_message(app, "Quit"); +} + + +static void app_update_isearch(app_t *app) { + if (!app || !app->ed) return; + buffer_t *buf = ecex_current_buffer(app->ed); + if (!buf || app->isearch_len == 0) { + app->isearch_has_match = 0; + app->dirty = 1; + return; + } + size_t pos = 0; + size_t start = app->isearch_backward + ? (buf->point > 0 ? buf->point - 1 : buf->len) + : buf->point; + int ok = app->isearch_backward + ? buffer_search_backward(buf, app->isearch_query, start, &pos) + : buffer_search_forward(buf, app->isearch_query, start, &pos); + if (ok == ECEX_OK) { + app->isearch_match = pos; + app->isearch_has_match = 1; + buffer_set_point(buf, pos); + buffer_set_mark(buf, pos + strlen(app->isearch_query)); + } else { + app->isearch_has_match = 0; + } + app->dirty = 1; +} + +static void app_enter_isearch(app_t *app, int backward) { + if (!app || !app->ed) return; + buffer_t *buf = ecex_current_buffer(app->ed); + app->mode = APP_MODE_ISEARCH; + app->isearch_backward = backward ? 1 : 0; + app->isearch_query[0] = '\0'; + app->isearch_len = 0; + app->isearch_origin = buf ? buf->point : 0; + app->isearch_match = app->isearch_origin; + app->isearch_has_match = 0; + app->prefix[0] = '\0'; + app->prefix_len = 0; + app->message[0] = '\0'; + app->dirty = 1; +} + +static void app_cancel_isearch(app_t *app) { + if (!app || !app->ed) return; + buffer_t *buf = ecex_current_buffer(app->ed); + if (buf) { + buffer_set_point(buf, app->isearch_origin); + buffer_clear_mark(buf); + } + app->mode = APP_MODE_EDIT; + app_message(app, "Search cancelled"); +} + +static void app_finish_isearch(app_t *app) { + if (!app || !app->ed) return; + buffer_t *buf = ecex_current_buffer(app->ed); + if (app->isearch_len > 0) { + snprintf(app->last_search_query, sizeof(app->last_search_query), "%s", app->isearch_query); + } + if (buf) buffer_clear_mark(buf); + app->mode = APP_MODE_EDIT; + if (app->isearch_len > 0) app_message(app, app->isearch_has_match ? "Search done" : "Search failed"); + app->dirty = 1; +} + +static void app_enter_prompt(app_t *app, + ecex_prompt_request_t kind, + const char *label) { + if (!app) return; + + app->mode = APP_MODE_PROMPT; + app->prompt_kind = kind; + snprintf(app->prompt_label, + sizeof(app->prompt_label), + "%s", + label ? label : ""); + app->prompt_input[0] = '\0'; + app->prompt_input_len = 0; + app_reset_prompt_completion(app); + app->message[0] = '\0'; + app->dirty = 1; +} + + +static void app_reload_font_if_needed(app_t *app) { + if (!app || !app->ed) return; + + const char *path = NULL; + if (app->ed->theme.font_path && app->ed->theme.font_path[0]) { + path = app->ed->theme.font_path; + } else if (app->font_path[0]) { + path = app->font_path; + } else { + path = font_choose_path(NULL); + } + + if (!path || !path[0]) return; + + float size = app->ed->theme.font_size; + int same_path = app->font_path[0] && strcmp(app->font_path, path) == 0; + int same_size = app->font.size_px == size; + + if (same_path && same_size) return; + + font_t new_font; + if (font_load(&new_font, path, size) != 0) { + char msg[ECEX_MINIBUFFER_SIZE]; + snprintf(msg, sizeof(msg), "Failed to reload font: %s", path); + app_message(app, msg); + return; + } + + font_free(&app->font); + app->font = new_font; + snprintf(app->font_path, sizeof(app->font_path), "%s", path); + app->dirty = 1; +} + +static int app_handle_prompt_request(app_t *app) { + if (!app || !app->ed) return 0; + + if (app->ed->prompt_request == ECEX_PROMPT_NONE) { + return 0; + } + + ecex_prompt_request_t request = app->ed->prompt_request; + char label[sizeof(app->ed->prompt_message)]; + snprintf(label, sizeof(label), "%s", app->ed->prompt_message); + + ecex_clear_prompt_request(app->ed); + if (request == ECEX_PROMPT_ISEARCH_FORWARD) { + app_enter_isearch(app, 0); + } else if (request == ECEX_PROMPT_ISEARCH_BACKWARD) { + app_enter_isearch(app, 1); + } else { + app_enter_prompt(app, request, label); + } + return 1; +} + +static int app_execute_command(app_t *app, const char *command) { + if (!app || !app->ed || !command) return -1; + + int result = ecex_execute_command(app->ed, command); + if (result == 0) { + app_reload_font_if_needed(app); + app_handle_prompt_request(app); + } + + if (app->ed->should_quit && app->window) { + glfwSetWindowShouldClose(app->window, GLFW_TRUE); + glfwPostEmptyEvent(); + } + + app->dirty = 1; + return result; +} + +static void app_cancel_prompt(app_t *app) { + if (!app) return; + + app->mode = APP_MODE_EDIT; + app->prompt_kind = ECEX_PROMPT_NONE; + app->prompt_label[0] = '\0'; + app->prompt_input[0] = '\0'; + app->prompt_input_len = 0; + app_reset_prompt_completion(app); + app_message(app, "Prompt cancelled"); +} + +static void app_submit_prompt(app_t *app) { + if (!app || !app->ed) return; + + if (app->prompt_input_len == 0 && app->prompt_kind != ECEX_PROMPT_COMPILE) { + app_cancel_prompt(app); + return; + } + + char input[sizeof(app->prompt_input)]; + snprintf(input, sizeof(input), "%s", app->prompt_input); + + ecex_prompt_request_t kind = app->prompt_kind; + app->mode = APP_MODE_EDIT; + app->prompt_kind = ECEX_PROMPT_NONE; + app->prompt_label[0] = '\0'; + app->prompt_input[0] = '\0'; + app->prompt_input_len = 0; + + char *expanded_input = app_expand_user_path(input); + const char *path = expanded_input ? expanded_input : input; + + int result = -1; + const char *verb = "Prompt"; + + switch (kind) { + case ECEX_PROMPT_FIND_FILE: + result = ecex_find_file(app->ed, path); + verb = "Opened"; + break; + + case ECEX_PROMPT_WRITE_FILE: + result = ecex_write_current_buffer(app->ed, path); + verb = "Wrote"; + break; + + case ECEX_PROMPT_EVAL_FILE: + result = ecex_eval_file(app->ed, path); + verb = "Evaluated"; + break; + + case ECEX_PROMPT_SWITCH_BUFFER: + result = ecex_switch_buffer(app->ed, input); + verb = "Switched"; + break; + + case ECEX_PROMPT_KILL_BUFFER: + result = ecex_kill_buffer(app->ed, input); + verb = "Killed"; + break; + + case ECEX_PROMPT_COMPILE: + result = ecex_compile(app->ed, input[0] ? input : "make"); + verb = "Compiled"; + break; + + case ECEX_PROMPT_GREP: + result = ecex_grep(app->ed, input); + verb = "Grep"; + break; + + case ECEX_PROMPT_NONE: + default: + result = -1; + break; + } + + if (result == 0) { + app_reload_font_if_needed(app); + } + + char msg[ECEX_MINIBUFFER_SIZE]; + if (result == 0) { + snprintf(msg, sizeof(msg), "%s: %s", verb, path); + } else { + snprintf(msg, sizeof(msg), "Failed: %s", path); + } + + free(expanded_input); + app_reset_prompt_completion(app); + app_message(app, msg); +} + +static void app_execute_mx(app_t *app) { + if (!app) return; + + if (app->minibuffer_len == 0) { + app_cancel_mx(app); + return; + } + + char command[ECEX_MINIBUFFER_SIZE]; + snprintf(command, sizeof(command), "%s", app->minibuffer); + + app->mode = APP_MODE_EDIT; + app->minibuffer[0] = '\0'; + app->minibuffer_len = 0; + app_reset_completion(app); + + if (app_execute_command(app, command) == 0) { + if (app->mode == APP_MODE_EDIT) { + char msg[ECEX_MINIBUFFER_SIZE]; + snprintf(msg, sizeof(msg), "Executed: %s", command); + app_message(app, msg); + } + } else { + char msg[ECEX_MINIBUFFER_SIZE]; + snprintf(msg, sizeof(msg), "No such command: %s", command); + app_message(app, msg); + } + + if (app->ed->should_quit) { + glfwSetWindowShouldClose(app->window, GLFW_TRUE); + glfwPostEmptyEvent(); + } + + app->dirty = 1; +} + +static void app_complete_mx(app_t *app) { + if (!app) return; + + if (app->completion_active) { + app_cycle_completion(app, 1); + } else { + app_begin_completion(app, 1); + } +} + +static void app_enter_prefix(app_t *app, const char *first_key) { + if (!app || !first_key) return; + + app->mode = APP_MODE_PREFIX; + app->minibuffer[0] = '\0'; + app->minibuffer_len = 0; + app_reset_completion(app); + + snprintf(app->prefix, sizeof(app->prefix), "%s", first_key); + app->prefix_len = strlen(app->prefix); + + app->message[0] = '\0'; + app->dirty = 1; +} + +static void app_cancel_prefix(app_t *app) { + if (!app) return; + + app->mode = APP_MODE_EDIT; + app->prefix[0] = '\0'; + app->prefix_len = 0; + + app_message(app, "Prefix cancelled"); +} + +static int app_append_prefix_key(app_t *app, const char *key_name) { + if (!app || !key_name) return -1; + + size_t key_len = strlen(key_name); + + if (app->prefix_len + 1 + key_len + 1 >= sizeof(app->prefix)) { + app_cancel_prefix(app); + return -1; + } + + app->prefix[app->prefix_len++] = ' '; + memcpy(app->prefix + app->prefix_len, key_name, key_len + 1); + app->prefix_len += key_len; + + return 0; +} + +static int key_sequence_has_prefix(app_t *app, const char *prefix) { + if (!app || !app->ed || !prefix) return 0; + return ecex_key_sequence_has_prefix_for_buffer(app->ed, + ecex_current_buffer(app->ed), + prefix); +} + +static void app_finish_prefix(app_t *app) { + if (!app) return; + + const char *command = ecex_lookup_key_for_buffer(app->ed, ecex_current_buffer(app->ed), app->prefix); + + if (command) { + if (app_execute_command(app, command) == 0) { + if (app->mode == APP_MODE_EDIT) { + char msg[ECEX_MINIBUFFER_SIZE]; + snprintf(msg, sizeof(msg), "Executed: %s", command); + app_message(app, msg); + } + } else { + char msg[ECEX_MINIBUFFER_SIZE]; + snprintf(msg, sizeof(msg), "Command failed: %s", command); + app_message(app, msg); + } + + if (app->ed->should_quit) { + glfwSetWindowShouldClose(app->window, GLFW_TRUE); + glfwPostEmptyEvent(); + } + + if (app->mode != APP_MODE_PROMPT) { + app->mode = APP_MODE_EDIT; + } + app->prefix[0] = '\0'; + app->prefix_len = 0; + app->dirty = 1; + return; + } + + if (key_sequence_has_prefix(app, app->prefix)) { + app->dirty = 1; + return; + } + + char msg[ECEX_MINIBUFFER_SIZE]; + snprintf(msg, sizeof(msg), "Undefined key: %s", app->prefix); + + app->mode = APP_MODE_EDIT; + app->prefix[0] = '\0'; + app->prefix_len = 0; + + app_message(app, msg); +} + + +static float app_mono_cell_width(app_t *app) { + float w = text_width(&app->font, "M"); + return w > 1.0f ? w : app->font.size_px * 0.6f; +} + +static float app_status_height(app_t *app) { + float line_h = app->font.line_height > 1.0f ? app->font.line_height : app->font.size_px * 1.2f; + float pad_y = app->font.size_px * 0.35f; + if (pad_y < 4.0f) pad_y = 4.0f; + return line_h + pad_y * 2.0f; +} + +static float app_minibuffer_height(app_t *app) { return app_status_height(app); } + +static int app_minibuffer_visible(app_t *app) { + return app->mode == APP_MODE_MX || app->mode == APP_MODE_PREFIX || + app->mode == APP_MODE_PROMPT || app->mode == APP_MODE_ISEARCH || + app->message[0] != '\0'; +} + +static size_t app_offset_for_line(buffer_t *buf, size_t target_line) { + if (!buf || target_line == 0) return 0; + size_t line = 0; + for (size_t i = 0; i < buf->len; i++) { + if (buf->data[i] == '\n') { + line++; + if (line == target_line) return i + 1; + } + } + return buf->len; +} + +static int app_focus_window_at(app_t *app, double px, double py) { + if (!app || !app->ed || app->ed->window_count == 0) return -1; + float editor_h = (float)app->height - app_status_height(app); + if (app_minibuffer_visible(app)) editor_h -= app_minibuffer_height(app); + if (editor_h < 1.0f) editor_h = 1.0f; + for (size_t i = 0; i < app->ed->window_count; i++) { + ecex_window_t *w = &app->ed->windows[i]; + float x = w->x * (float)app->width; + float y = w->y * editor_h; + float ww = w->w * (float)app->width; + float hh = w->h * editor_h; + if (px >= x && px < x + ww && py >= y && py < y + hh) { + app->ed->current_window_index = i; + ecex_sync_current_buffer(app->ed); + return (int)i; + } + } + return -1; +} + +static void app_move_point_to_pixel(app_t *app, double px, double py) { + int wi = app_focus_window_at(app, px, py); + if (wi < 0) return; + ecex_window_t *w = &app->ed->windows[wi]; + buffer_t *buf = w->buffer; + if (!buf) return; + float editor_h = (float)app->height - app_status_height(app); + if (app_minibuffer_visible(app)) editor_h -= app_minibuffer_height(app); + float wx = w->x * (float)app->width; + float wy = w->y * editor_h; + float pad_x = app->font.size_px * 0.75f; if (pad_x < 8.0f) pad_x = 8.0f; + float pad_y = app->font.size_px * 0.35f; if (pad_y < 4.0f) pad_y = 4.0f; + size_t row = py > wy + pad_y ? (size_t)((py - wy - pad_y) / app->font.line_height) : 0; + size_t col = px > wx + pad_x ? (size_t)((px - wx - pad_x) / app_mono_cell_width(app)) : 0; + size_t line = buf->scroll_line + row; + size_t start = app_offset_for_line(buf, line); + size_t end = buffer_line_end_at(buf, start); + buffer_set_point(buf, start + ECEX_MIN(col + buf->scroll_col, end - start)); + app->dirty = 1; +} + +static void mouse_button_callback(GLFWwindow *window, int button, int action, int mods) { + (void)mods; + if (button != GLFW_MOUSE_BUTTON_LEFT || action != GLFW_PRESS) return; + app_t *app = glfwGetWindowUserPointer(window); + if (!app) return; + glfwGetFramebufferSize(window, &app->width, &app->height); + double x = 0.0, y = 0.0; + glfwGetCursorPos(window, &x, &y); + app_move_point_to_pixel(app, x, y); +} + +static void scroll_callback(GLFWwindow *window, double xoffset, double yoffset) { + (void)xoffset; + app_t *app = glfwGetWindowUserPointer(window); + if (!app || !app->ed) return; + buffer_t *buf = ecex_current_buffer(app->ed); + if (!buf) return; + if (yoffset < 0.0) buf->scroll_line += 3; + else if (yoffset > 0.0) buf->scroll_line = buf->scroll_line > 3 ? buf->scroll_line - 3 : 0; + app->dirty = 1; +} + +static void mark_dirty(GLFWwindow *window) { + app_t *app = glfwGetWindowUserPointer(window); + if (app) { + app->dirty = 1; + } +} + +static void framebuffer_size_callback(GLFWwindow *window, int width, int height) { + (void)width; + (void)height; + + mark_dirty(window); +} + +static void window_refresh_callback(GLFWwindow *window) { + mark_dirty(window); +} + +static const char *key_name_for_special(int key) { + switch (key) { + case GLFW_KEY_F1: return "F1"; + case GLFW_KEY_F2: return "F2"; + case GLFW_KEY_F3: return "F3"; + case GLFW_KEY_F4: return "F4"; + case GLFW_KEY_F5: return "F5"; + case GLFW_KEY_LEFT: return "LEFT"; + case GLFW_KEY_RIGHT: return "RIGHT"; + case GLFW_KEY_UP: return "UP"; + case GLFW_KEY_DOWN: return "DOWN"; + case GLFW_KEY_ENTER: return "ENTER"; + case GLFW_KEY_BACKSPACE: return "BACKSPACE"; + case GLFW_KEY_DELETE: return "DELETE"; + case GLFW_KEY_TAB: return "TAB"; + case GLFW_KEY_SPACE: return "SPC"; + case GLFW_KEY_ESCAPE: return "ESC"; + case GLFW_KEY_HOME: return "HOME"; + case GLFW_KEY_END: return "END"; + case GLFW_KEY_PAGE_UP: return "PAGEUP"; + case GLFW_KEY_PAGE_DOWN: return "PAGEDOWN"; + default: return NULL; + } +} + +static int layout_key_name(int key, + int scancode, + char *out, + size_t out_size) { + if (!out || out_size == 0) return -1; + + out[0] = '\0'; + + const char *special = key_name_for_special(key); + if (special) { + snprintf(out, out_size, "%s", special); + return 0; + } + + const char *name = glfwGetKeyName(key, scancode); + if (!name || !name[0]) return -1; + + if (name[1] != '\0') return -1; + + char c = name[0]; + if (c >= 'A' && c <= 'Z') { + c = (char)(c - 'A' + 'a'); + } + + out[0] = c; + out[1] = '\0'; + return 0; +} + +static int key_event_to_string(int key, + int scancode, + int mods, + char *out, + size_t out_size) { + if (!out || out_size == 0) return -1; + + out[0] = '\0'; + + char base[32]; + if (layout_key_name(key, scancode, base, sizeof(base)) != 0) { + return -1; + } + + char prefix[32]; + prefix[0] = '\0'; + + if (mods & GLFW_MOD_CONTROL) { + strncat(prefix, "C-", sizeof(prefix) - strlen(prefix) - 1); + } + + if (mods & GLFW_MOD_ALT) { + strncat(prefix, "M-", sizeof(prefix) - strlen(prefix) - 1); + } + + if (mods & GLFW_MOD_SUPER) { + strncat(prefix, "S-", sizeof(prefix) - strlen(prefix) - 1); + } + + snprintf(out, out_size, "%s%s", prefix, base); + return 0; +} + +static int is_layout_char_key(int key, + int scancode, + char wanted) { + char name[32]; + + if (layout_key_name(key, scancode, name, sizeof(name)) != 0) { + return 0; + } + + if (wanted >= 'A' && wanted <= 'Z') { + wanted = (char)(wanted - 'A' + 'a'); + } + + return name[0] == wanted && name[1] == '\0'; +} + +static int key_produces_text(int key, int scancode) { + if (key_name_for_special(key)) { + return 0; + } + + const char *name = glfwGetKeyName(key, scancode); + return name && name[0] && name[1] == '\0'; +} + +static void try_execute_keybind(app_t *app, const char *key_name) { + const char *command = ecex_lookup_key_for_buffer(app->ed, ecex_current_buffer(app->ed), key_name); + if (!command) return; + + if (app_execute_command(app, command) == 0) { + app->dirty = 1; + } else { + char msg[ECEX_MINIBUFFER_SIZE]; + snprintf(msg, sizeof(msg), "Bad keybind: %s -> %s", key_name, command); + app_message(app, msg); + } + + if (app->ed->should_quit) { + glfwSetWindowShouldClose(app->window, GLFW_TRUE); + glfwPostEmptyEvent(); + } +} + +static void char_callback(GLFWwindow *window, unsigned int codepoint) { + app_t *app = glfwGetWindowUserPointer(window); + if (!app || !app->ed) return; + + if (app->suppress_next_char) { + app->suppress_next_char = 0; + return; + } + + if (app->mode == APP_MODE_EDIT) { + if ((app->current_mods & GLFW_MOD_ALT) && codepoint == 'x') { + app_enter_mx(app); + return; + } + } + + if (app->mode == APP_MODE_MX) { + if (codepoint >= 32 && codepoint <= 126) { + if (app->minibuffer_len + 1 < sizeof(app->minibuffer)) { + app_reset_completion(app); + app->minibuffer[app->minibuffer_len++] = (char)codepoint; + app->minibuffer[app->minibuffer_len] = '\0'; + app->dirty = 1; + } + } + return; + } + + if (app->mode == APP_MODE_ISEARCH) { + if (codepoint >= 32 && codepoint <= 126) { + if (app->isearch_len + 1 < sizeof(app->isearch_query)) { + app->isearch_query[app->isearch_len++] = (char)codepoint; + app->isearch_query[app->isearch_len] = '\0'; + app_update_isearch(app); + } + } + return; + } + + if (app->mode == APP_MODE_PROMPT) { + if (codepoint >= 32 && codepoint <= 126) { + if (app->prompt_input_len + 1 < sizeof(app->prompt_input)) { + app->prompt_input[app->prompt_input_len++] = (char)codepoint; + app->prompt_input[app->prompt_input_len] = '\0'; + app->dirty = 1; + } + } + return; + } + + if (app->mode == APP_MODE_PREFIX) { + return; + } + + buffer_t *buf = ecex_current_buffer(app->ed); + if (!buf) return; + + if (buffer_is_interactive(buf)) { + return; + } + + if (codepoint >= 32 && codepoint <= 126) { + buffer_insert_char(buf, (char)codepoint); + app->message[0] = '\0'; + app->dirty = 1; + } +} + +static void key_callback(GLFWwindow *window, + int key, + int scancode, + int action, + int mods) { + if (action != GLFW_PRESS && action != GLFW_REPEAT) { + return; + } + + app_t *app = glfwGetWindowUserPointer(window); + if (!app || !app->ed) return; + + app->current_mods = mods; + + if (app->mode == APP_MODE_EDIT && key == GLFW_KEY_F1) { + app_enter_mx(app); + return; + } + + if (app->mode == APP_MODE_EDIT && + (mods & GLFW_MOD_ALT) && + is_layout_char_key(key, scancode, 'g')) { + app_enter_prefix(app, "M-g"); + return; + } + + if (app->mode == APP_MODE_EDIT && + (mods & GLFW_MOD_CONTROL) && + is_layout_char_key(key, scancode, 'x')) { + app_enter_prefix(app, "C-x"); + return; + } + + if (app->mode == APP_MODE_MX) { + switch (key) { + case GLFW_KEY_ESCAPE: + app_cancel_mx(app); + return; + + case GLFW_KEY_ENTER: + app_execute_mx(app); + return; + + case GLFW_KEY_TAB: + app_complete_mx(app); + return; + + case GLFW_KEY_DOWN: + app_cycle_completion(app, 1); + return; + + case GLFW_KEY_UP: + app_cycle_completion(app, -1); + return; + + case GLFW_KEY_BACKSPACE: + if (app->minibuffer_len > 0) { + app_reset_completion(app); + app->minibuffer_len--; + app->minibuffer[app->minibuffer_len] = '\0'; + app->dirty = 1; + } + return; + + default: + return; + } + } + + if (app->mode == APP_MODE_ISEARCH) { + switch (key) { + case GLFW_KEY_ESCAPE: + app_cancel_isearch(app); + return; + case GLFW_KEY_ENTER: + app_finish_isearch(app); + return; + case GLFW_KEY_BACKSPACE: + if (app->isearch_len > 0) { + app->isearch_len--; + app->isearch_query[app->isearch_len] = '\0'; + buffer_t *buf = ecex_current_buffer(app->ed); + if (buf) { + buffer_set_point(buf, app->isearch_origin); + buffer_clear_mark(buf); + } + app_update_isearch(app); + } + return; + default: + if ((mods & GLFW_MOD_CONTROL) && is_layout_char_key(key, scancode, 's')) { + app->isearch_backward = 0; + app_update_isearch(app); + return; + } + if ((mods & GLFW_MOD_CONTROL) && is_layout_char_key(key, scancode, 'r')) { + app->isearch_backward = 1; + app_update_isearch(app); + return; + } + return; + } + } + + if (app->mode == APP_MODE_PROMPT) { + switch (key) { + case GLFW_KEY_ESCAPE: + app_cancel_prompt(app); + return; + + case GLFW_KEY_ENTER: + app_submit_prompt(app); + return; + + case GLFW_KEY_TAB: + app_cycle_prompt_completion(app, 1); + return; + + case GLFW_KEY_DOWN: + app_cycle_prompt_completion(app, 1); + return; + + case GLFW_KEY_UP: + app_cycle_prompt_completion(app, -1); + return; + + case GLFW_KEY_BACKSPACE: + if (app->prompt_input_len > 0) { + app_reset_prompt_completion(app); + app->prompt_input_len--; + app->prompt_input[app->prompt_input_len] = '\0'; + app->dirty = 1; + } + return; + + default: + return; + } + } + + if (app->mode == APP_MODE_PREFIX) { + if (key == GLFW_KEY_ESCAPE) { + app_cancel_prefix(app); + return; + } + + char key_name[64]; + + if (key_event_to_string(key, scancode, mods, key_name, sizeof(key_name)) == 0) { + if (key_produces_text(key, scancode)) { + app->suppress_next_char = 1; + } + + if (app_append_prefix_key(app, key_name) == 0) { + app_finish_prefix(app); + } + return; + } + + app_cancel_prefix(app); + return; + } + + char key_name[64]; + if (key_event_to_string(key, scancode, mods, key_name, sizeof(key_name)) == 0) { + const char *command = ecex_lookup_key_for_buffer(app->ed, ecex_current_buffer(app->ed), key_name); + if (command) { + if (key_produces_text(key, scancode) && + !(mods & GLFW_MOD_CONTROL) && + !(mods & GLFW_MOD_SUPER)) { + app->suppress_next_char = 1; + } + + try_execute_keybind(app, key_name); + return; + } + } + + if (key == GLFW_KEY_ESCAPE) { + glfwSetWindowShouldClose(window, GLFW_TRUE); + glfwPostEmptyEvent(); + return; + } +} + +void app_init(app_t *app, ecex_t *ed) { + if (!app) return; + + memset(app, 0, sizeof(*app)); + app->ed = ed; + app->dirty = 1; + app->mode = APP_MODE_EDIT; + app_reset_completion(app); + app_reset_prompt_completion(app); +} + +void app_set_window(app_t *app, GLFWwindow *window) { + if (!app) return; + + app->window = window; + if (app->ed) { + ecex_set_clipboard_callbacks(app->ed, + window ? app_clipboard_get : NULL, + window ? app_clipboard_set : NULL, + app); + } + if (window) { + glfwSetWindowUserPointer(window, app); + } +} + +void app_install_callbacks(app_t *app) { + if (!app || !app->window) return; + + glfwSetCharCallback(app->window, char_callback); + glfwSetKeyCallback(app->window, key_callback); + glfwSetFramebufferSizeCallback(app->window, framebuffer_size_callback); + glfwSetWindowRefreshCallback(app->window, window_refresh_callback); + glfwSetMouseButtonCallback(app->window, mouse_button_callback); + glfwSetScrollCallback(app->window, scroll_callback); +} diff --git a/src/buffers.c b/src/buffers.c new file mode 100644 index 0000000..e8c1d23 --- /dev/null +++ b/src/buffers.c @@ -0,0 +1,701 @@ +#include "buffers.h" + +#include "common.h" +#include "util.h" + +#include <assert.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#define BUFFER_INITIAL_CAP 64 + +static int buffer_is_word_char(char c) { + return (c >= 'a' && c <= 'z') || + (c >= 'A' && c <= 'Z') || + (c >= '0' && c <= '9') || + c == '_'; +} + +static int buffer_require_editable(buffer_t *buffer) { + if (!buffer || buffer->read_only) return ECEX_ERR; + return ECEX_OK; +} + +static void buffer_undo_entry_free(ecex_undo_entry_t *entry) { + if (!entry) return; + free(entry->data); + entry->data = NULL; + entry->len = 0; + entry->point = 0; + entry->mark = 0; + entry->mark_active = 0; +} + +static void buffer_undo_stack_clear(ecex_undo_entry_t *stack, size_t count) { + if (!stack) return; + for (size_t i = 0; i < count; i++) buffer_undo_entry_free(&stack[i]); +} + +static int buffer_push_snapshot_to(ecex_undo_entry_t **stack, + size_t *count, + size_t *cap, + buffer_t *buffer) { + if (!stack || !count || !cap || !buffer) return ECEX_ERR; + if (ECEX_GROW_ARRAY(*stack, *count, *cap, 64) != ECEX_OK) return ECEX_ERR; + ecex_undo_entry_t *entry = &(*stack)[(*count)++]; + memset(entry, 0, sizeof(*entry)); + entry->data = malloc(buffer->len + 1); + if (!entry->data) { (*count)--; return ECEX_ERR; } + memcpy(entry->data, buffer->data, buffer->len + 1); + entry->len = buffer->len; + entry->point = buffer->point; + entry->mark = buffer->mark; + entry->mark_active = buffer->mark_active; + return ECEX_OK; +} + +static void buffer_clear_redo(buffer_t *buffer) { + if (!buffer) return; + buffer_undo_stack_clear(buffer->redo_stack, buffer->redo_count); + buffer->redo_count = 0; +} + +static int buffer_record_undo(buffer_t *buffer) { + if (!buffer || buffer->undo_disabled) return ECEX_OK; + if (buffer_push_snapshot_to(&buffer->undo_stack, + &buffer->undo_count, + &buffer->undo_cap, + buffer) != ECEX_OK) { + return ECEX_ERR; + } + buffer_clear_redo(buffer); + return ECEX_OK; +} + +static int buffer_restore_snapshot(buffer_t *buffer, ecex_undo_entry_t *entry) { + if (!buffer || !entry || !entry->data) return ECEX_ERR; + char *copy = malloc(entry->len + 1); + if (!copy) return ECEX_ERR; + memcpy(copy, entry->data, entry->len + 1); + free(buffer->data); + buffer->data = copy; + buffer->len = entry->len; + buffer->cap = entry->len + 1; + buffer->point = ECEX_MIN(entry->point, buffer->len); + buffer->mark = ECEX_MIN(entry->mark, buffer->len); + buffer->mark_active = entry->mark_active; + buffer->modified = 1; + return ECEX_OK; +} + +buffer_t *buffer_new(const char *name, const char *path, int read_only) { + assert(name && "buffer name cannot be NULL"); + + buffer_t *buffer = calloc(1, sizeof(*buffer)); + if (!buffer) return NULL; + + buffer->name = ecex_strdup(name); + buffer->path = ecex_strdup(path); + buffer->data = malloc(1); + + if (!buffer->name || (path && !buffer->path) || !buffer->data) { + buffer_free(buffer); + return NULL; + } + + buffer->data[0] = '\0'; + buffer->len = 0; + buffer->cap = 1; + buffer->read_only = read_only; + + return buffer; +} + +void buffer_free(buffer_t *buffer) { + if (!buffer) return; + + buffer_clear_interactive_actions(buffer); + buffer_undo_stack_clear(buffer->undo_stack, buffer->undo_count); + buffer_undo_stack_clear(buffer->redo_stack, buffer->redo_count); + free(buffer->undo_stack); + free(buffer->redo_stack); + free(buffer->interactive_actions); + free(buffer->name); + free(buffer->path); + free(buffer->data); + free(buffer); +} + +int buffer_reserve(buffer_t *buffer, size_t needed) { + ECEX_RETURN_ERR_IF_NULL(buffer); + if (needed <= buffer->cap) return ECEX_OK; + + size_t new_cap = buffer->cap ? buffer->cap : BUFFER_INITIAL_CAP; + while (new_cap < needed) { + new_cap *= 2; + } + + char *new_data = realloc(buffer->data, new_cap); + if (!new_data) return ECEX_ERR; + + buffer->data = new_data; + buffer->cap = new_cap; + return ECEX_OK; +} + +int buffer_clear(buffer_t *buffer) { + if (buffer_require_editable(buffer) != ECEX_OK) return ECEX_ERR; + if (buffer_record_undo(buffer) != ECEX_OK) return ECEX_ERR; + + if (buffer_reserve(buffer, 1) != ECEX_OK) return ECEX_ERR; + + buffer->data[0] = '\0'; + buffer->len = 0; + buffer->point = 0; + buffer->mark = 0; + buffer->mark_active = 0; + buffer->scroll_line = 0; + buffer->scroll_col = 0; + buffer_clear_interactive_actions(buffer); + buffer->modified = 1; + return ECEX_OK; +} + +int buffer_set_text(buffer_t *buffer, const char *text) { + if (buffer_require_editable(buffer) != ECEX_OK || !text) return ECEX_ERR; + if (buffer_record_undo(buffer) != ECEX_OK) return ECEX_ERR; + + size_t len = strlen(text); + if (buffer_reserve(buffer, len + 1) != ECEX_OK) return ECEX_ERR; + + memcpy(buffer->data, text, len + 1); + buffer->len = len; + buffer->point = len; + buffer->mark = 0; + buffer->mark_active = 0; + buffer->scroll_line = 0; + buffer->scroll_col = 0; + buffer_clear_interactive_actions(buffer); + buffer->modified = 1; + return ECEX_OK; +} + +int buffer_insert_at(buffer_t *buffer, size_t pos, const char *text) { + if (buffer_require_editable(buffer) != ECEX_OK || !text) return ECEX_ERR; + if (pos > buffer->len) return ECEX_ERR; + + size_t text_len = strlen(text); + if (text_len == 0) return ECEX_OK; + if (buffer_record_undo(buffer) != ECEX_OK) return ECEX_ERR; + size_t needed = buffer->len + text_len + 1; + + if (buffer_reserve(buffer, needed) != ECEX_OK) return ECEX_ERR; + + memmove(buffer->data + pos + text_len, + buffer->data + pos, + buffer->len - pos + 1); + memcpy(buffer->data + pos, text, text_len); + + buffer->len += text_len; + buffer->point = pos + text_len; + buffer->modified = 1; + return ECEX_OK; +} + +int buffer_insert(buffer_t *buffer, const char *text) { + ECEX_RETURN_ERR_IF_NULL(buffer); + return buffer_insert_at(buffer, buffer->point, text); +} + +int buffer_append(buffer_t *buffer, const char *text) { + ECEX_RETURN_ERR_IF_NULL(buffer); + return buffer_insert_at(buffer, buffer->len, text); +} + +int buffer_prepend(buffer_t *buffer, const char *text) { + return buffer_insert_at(buffer, 0, text); +} + +int buffer_insert_char_at(buffer_t *buffer, size_t pos, char c) { + if (buffer_require_editable(buffer) != ECEX_OK) return ECEX_ERR; + if (pos > buffer->len) return ECEX_ERR; + if (buffer_record_undo(buffer) != ECEX_OK) return ECEX_ERR; + + if (buffer_reserve(buffer, buffer->len + 2) != ECEX_OK) return ECEX_ERR; + + memmove(buffer->data + pos + 1, + buffer->data + pos, + buffer->len - pos + 1); + + buffer->data[pos] = c; + buffer->len++; + buffer->point = pos + 1; + buffer->modified = 1; + return ECEX_OK; +} + +int buffer_insert_char(buffer_t *buffer, char c) { + ECEX_RETURN_ERR_IF_NULL(buffer); + return buffer_insert_char_at(buffer, buffer->point, c); +} + +int buffer_delete_range(buffer_t *buffer, size_t start, size_t end) { + if (buffer_require_editable(buffer) != ECEX_OK) return ECEX_ERR; + if (start > end || end > buffer->len) return ECEX_ERR; + if (start == end) return ECEX_OK; + if (buffer_record_undo(buffer) != ECEX_OK) return ECEX_ERR; + + size_t deleted = end - start; + + memmove(buffer->data + start, + buffer->data + end, + buffer->len - end + 1); + + buffer->len -= deleted; + + if (buffer->point > end) { + buffer->point -= deleted; + } else if (buffer->point > start) { + buffer->point = start; + } + + if (buffer->mark > end) { + buffer->mark -= deleted; + } else if (buffer->mark > start) { + buffer->mark = start; + } + + if (buffer->mark_active && buffer->mark == buffer->point) { + buffer->mark_active = 0; + } + + buffer->modified = 1; + return ECEX_OK; +} + +int buffer_delete_selection(buffer_t *buffer) { + if (!buffer_has_selection(buffer)) return ECEX_OK; + + size_t start = 0; + size_t end = 0; + buffer_selection_range(buffer, &start, &end); + + int result = buffer_delete_range(buffer, start, end); + if (result == ECEX_OK) buffer_clear_mark(buffer); + return result; +} + +int buffer_replace_selection(buffer_t *buffer, const char *text) { + if (!buffer || !text) return ECEX_ERR; + if (!buffer_has_selection(buffer)) return buffer_insert(buffer, text); + + size_t start = 0; + size_t end = 0; + buffer_selection_range(buffer, &start, &end); + + if (buffer_delete_range(buffer, start, end) != ECEX_OK) return ECEX_ERR; + buffer->point = start; + buffer_clear_mark(buffer); + return buffer_insert(buffer, text); +} + +int buffer_backspace(buffer_t *buffer) { + if (!buffer) return ECEX_ERR; + if (buffer_has_selection(buffer)) return buffer_delete_selection(buffer); + if (buffer->point == 0) return ECEX_OK; + return buffer_delete_range(buffer, buffer->point - 1, buffer->point); +} + +int buffer_delete_forward(buffer_t *buffer) { + if (!buffer) return ECEX_ERR; + if (buffer_has_selection(buffer)) return buffer_delete_selection(buffer); + if (buffer->point >= buffer->len) return ECEX_OK; + return buffer_delete_range(buffer, buffer->point, buffer->point + 1); +} + +int buffer_kill_line(buffer_t *buffer) { + if (!buffer) return ECEX_ERR; + + size_t end = buffer_line_end_at(buffer, buffer->point); + if (end == buffer->point && end < buffer->len && buffer->data[end] == '\n') { + end++; + } + + return buffer_delete_range(buffer, buffer->point, end); +} + +void buffer_set_point(buffer_t *buffer, size_t point) { + if (!buffer) return; + buffer->point = ECEX_MIN(point, buffer->len); +} + +void buffer_move_left(buffer_t *buffer) { + if (!buffer || buffer->point == 0) return; + buffer->point--; +} + +void buffer_move_right(buffer_t *buffer) { + if (!buffer || buffer->point >= buffer->len) return; + buffer->point++; +} + +void buffer_move_up(buffer_t *buffer) { + if (!buffer) return; + + size_t current_start = buffer_line_start_at(buffer, buffer->point); + if (current_start == 0) { + buffer->point = 0; + return; + } + + size_t wanted_col = buffer->point - current_start; + size_t prev_end = current_start - 1; + size_t prev_start = buffer_line_start_at(buffer, prev_end); + size_t prev_len = prev_end - prev_start; + + buffer->point = prev_start + ECEX_MIN(wanted_col, prev_len); +} + +void buffer_move_down(buffer_t *buffer) { + if (!buffer) return; + + size_t current_start = buffer_line_start_at(buffer, buffer->point); + size_t current_end = buffer_line_end_at(buffer, buffer->point); + if (current_end >= buffer->len) { + buffer->point = buffer->len; + return; + } + + size_t wanted_col = buffer->point - current_start; + size_t next_start = current_end + 1; + size_t next_end = buffer_line_end_at(buffer, next_start); + size_t next_len = next_end - next_start; + + buffer->point = next_start + ECEX_MIN(wanted_col, next_len); +} + +void buffer_move_word_left(buffer_t *buffer) { + if (!buffer) return; + + size_t pos = buffer->point; + while (pos > 0 && !buffer_is_word_char(buffer->data[pos - 1])) pos--; + while (pos > 0 && buffer_is_word_char(buffer->data[pos - 1])) pos--; + buffer->point = pos; +} + +void buffer_move_word_right(buffer_t *buffer) { + if (!buffer) return; + + size_t pos = buffer->point; + while (pos < buffer->len && !buffer_is_word_char(buffer->data[pos])) pos++; + while (pos < buffer->len && buffer_is_word_char(buffer->data[pos])) pos++; + buffer->point = pos; +} + +void buffer_move_beginning_of_line(buffer_t *buffer) { + if (!buffer) return; + buffer->point = buffer_line_start_at(buffer, buffer->point); +} + +void buffer_move_end_of_line(buffer_t *buffer) { + if (!buffer) return; + buffer->point = buffer_line_end_at(buffer, buffer->point); +} + +void buffer_move_beginning_of_buffer(buffer_t *buffer) { + if (!buffer) return; + buffer->point = 0; +} + +void buffer_move_end_of_buffer(buffer_t *buffer) { + if (!buffer) return; + buffer->point = buffer->len; +} + +void buffer_set_mark(buffer_t *buffer, size_t mark) { + if (!buffer) return; + buffer->mark = ECEX_MIN(mark, buffer->len); + buffer->mark_active = 1; +} + +void buffer_clear_mark(buffer_t *buffer) { + if (!buffer) return; + buffer->mark_active = 0; +} + +int buffer_has_selection(buffer_t *buffer) { + return buffer && buffer->mark_active && buffer->mark != buffer->point; +} + +void buffer_selection_range(buffer_t *buffer, size_t *out_start, size_t *out_end) { + size_t start = 0; + size_t end = 0; + + if (buffer && buffer_has_selection(buffer)) { + start = ECEX_MIN(buffer->point, buffer->mark); + end = ECEX_MAX(buffer->point, buffer->mark); + } + + if (out_start) *out_start = start; + if (out_end) *out_end = end; +} + +size_t buffer_line_start_at(buffer_t *buffer, size_t pos) { + if (!buffer) return 0; + pos = ECEX_MIN(pos, buffer->len); + + while (pos > 0 && buffer->data[pos - 1] != '\n') { + pos--; + } + + return pos; +} + +size_t buffer_line_end_at(buffer_t *buffer, size_t pos) { + if (!buffer) return 0; + pos = ECEX_MIN(pos, buffer->len); + + while (pos < buffer->len && buffer->data[pos] != '\n') { + pos++; + } + + return pos; +} + +size_t buffer_current_line_start(buffer_t *buffer) { + if (!buffer) return 0; + return buffer_line_start_at(buffer, buffer->point); +} + +size_t buffer_current_line_end(buffer_t *buffer) { + if (!buffer) return 0; + return buffer_line_end_at(buffer, buffer->point); +} + +size_t buffer_current_column(buffer_t *buffer) { + if (!buffer) return 0; + return buffer->point - buffer_line_start_at(buffer, buffer->point); +} + +size_t buffer_current_line_number(buffer_t *buffer) { + if (!buffer) return 0; + + size_t line = 1; + for (size_t i = 0; i < buffer->point && i < buffer->len; i++) { + if (buffer->data[i] == '\n') line++; + } + + return line; +} + +size_t buffer_line_count(buffer_t *buffer) { + if (!buffer || buffer->len == 0) return 1; + + size_t lines = 1; + for (size_t i = 0; i < buffer->len; i++) { + if (buffer->data[i] == '\n') lines++; + } + + return lines; +} + +char *buffer_substring(buffer_t *buffer, size_t start, size_t end) { + if (!buffer || start > end || end > buffer->len) return NULL; + + size_t len = end - start; + char *copy = malloc(len + 1); + if (!copy) return NULL; + + memcpy(copy, buffer->data + start, len); + copy[len] = '\0'; + return copy; +} + +char *buffer_current_line_copy(buffer_t *buffer) { + if (!buffer) return NULL; + return buffer_substring(buffer, + buffer_current_line_start(buffer), + buffer_current_line_end(buffer)); +} + +int buffer_load_file(buffer_t *buffer, const char *path) { + if (buffer_require_editable(buffer) != ECEX_OK || !path) return ECEX_ERR; + + size_t size = 0; + char *new_data = ecex_read_entire_file(path, &size); + if (!new_data) return ECEX_ERR; + + char *new_path = ecex_strdup(path); + if (!new_path) { + free(new_data); + return ECEX_ERR; + } + + free(buffer->data); + free(buffer->path); + + buffer->data = new_data; + buffer->path = new_path; + buffer->len = size; + buffer->cap = size + 1; + buffer->point = 0; + buffer->mark = 0; + buffer->mark_active = 0; + buffer->scroll_line = 0; + buffer->scroll_col = 0; + buffer->modified = 0; + buffer_clear_undo(buffer); + return ECEX_OK; +} + +int buffer_save(buffer_t *buffer) { + if (!buffer || buffer->read_only || !buffer->path) return ECEX_ERR; + + FILE *file = fopen(buffer->path, "wb"); + if (!file) return ECEX_ERR; + + size_t written = fwrite(buffer->data, 1, buffer->len, file); + int close_result = fclose(file); + + if (close_result != 0 || written != buffer->len) return ECEX_ERR; + + buffer->modified = 0; + return ECEX_OK; +} + +int buffer_save_as(buffer_t *buffer, const char *path) { + if (buffer_require_editable(buffer) != ECEX_OK || !path) return ECEX_ERR; + + char *new_path = ecex_strdup(path); + if (!new_path) return ECEX_ERR; + + free(buffer->path); + buffer->path = new_path; + return buffer_save(buffer); +} + + + +int buffer_undo(buffer_t *buffer) { + if (buffer_require_editable(buffer) != ECEX_OK) return ECEX_ERR; + if (buffer->undo_count == 0) return ECEX_OK; + if (buffer_push_snapshot_to(&buffer->redo_stack, &buffer->redo_count, &buffer->redo_cap, buffer) != ECEX_OK) return ECEX_ERR; + ecex_undo_entry_t entry = buffer->undo_stack[--buffer->undo_count]; + int result = buffer_restore_snapshot(buffer, &entry); + buffer_undo_entry_free(&entry); + return result; +} + +int buffer_redo(buffer_t *buffer) { + if (buffer_require_editable(buffer) != ECEX_OK) return ECEX_ERR; + if (buffer->redo_count == 0) return ECEX_OK; + if (buffer_push_snapshot_to(&buffer->undo_stack, &buffer->undo_count, &buffer->undo_cap, buffer) != ECEX_OK) return ECEX_ERR; + ecex_undo_entry_t entry = buffer->redo_stack[--buffer->redo_count]; + int result = buffer_restore_snapshot(buffer, &entry); + buffer_undo_entry_free(&entry); + return result; +} + +void buffer_clear_undo(buffer_t *buffer) { + if (!buffer) return; + buffer_undo_stack_clear(buffer->undo_stack, buffer->undo_count); + buffer_undo_stack_clear(buffer->redo_stack, buffer->redo_count); + buffer->undo_count = 0; + buffer->redo_count = 0; +} + +int buffer_search_forward(buffer_t *buffer, const char *query, size_t start, size_t *out_pos) { + if (!buffer || !query || !query[0]) return ECEX_ERR; + if (start > buffer->len) start = buffer->len; + char *hit = strstr(buffer->data + start, query); + if (!hit && start > 0) hit = strstr(buffer->data, query); + if (!hit) return ECEX_ERR; + if (out_pos) *out_pos = (size_t)(hit - buffer->data); + return ECEX_OK; +} + +int buffer_search_backward(buffer_t *buffer, const char *query, size_t start, size_t *out_pos) { + if (!buffer || !query || !query[0]) return ECEX_ERR; + size_t qlen = strlen(query); + if (qlen > buffer->len) return ECEX_ERR; + if (start > buffer->len) start = buffer->len; + size_t best = (size_t)-1; + for (size_t i = 0; i + qlen <= start; i++) { + if (memcmp(buffer->data + i, query, qlen) == 0) best = i; + } + if (best == (size_t)-1) { + for (size_t i = start; i + qlen <= buffer->len; i++) { + if (memcmp(buffer->data + i, query, qlen) == 0) best = i; + } + } + if (best == (size_t)-1) return ECEX_ERR; + if (out_pos) *out_pos = best; + return ECEX_OK; +} + +void buffer_set_interactive(buffer_t *buffer, int interactive) { + if (!buffer) return; + buffer->interactive = interactive ? 1 : 0; +} + +int buffer_is_interactive(buffer_t *buffer) { + return buffer && buffer->interactive; +} + +int buffer_clear_interactive_actions(buffer_t *buffer) { + if (!buffer) return ECEX_ERR; + + for (size_t i = 0; i < buffer->interactive_action_count; i++) { + free(buffer->interactive_actions[i].payload); + buffer->interactive_actions[i].payload = NULL; + buffer->interactive_actions[i].fn = NULL; + buffer->interactive_actions[i].userdata = NULL; + buffer->interactive_actions[i].line = 0; + } + + buffer->interactive_action_count = 0; + return ECEX_OK; +} + +int buffer_add_interactive_action(buffer_t *buffer, + size_t line, + ecex_interactive_line_fn fn, + const char *payload, + void *userdata) { + if (!buffer || !fn) return ECEX_ERR; + + if (ECEX_GROW_ARRAY(buffer->interactive_actions, + buffer->interactive_action_count, + buffer->interactive_action_cap, + 16) != ECEX_OK) { + return ECEX_ERR; + } + + char *payload_copy = ecex_strdup(payload); + if (payload && !payload_copy) return ECEX_ERR; + + ecex_interactive_line_action_t *action = + &buffer->interactive_actions[buffer->interactive_action_count++]; + + action->line = line; + action->fn = fn; + action->payload = payload_copy; + action->userdata = userdata; + + buffer->interactive = 1; + return ECEX_OK; +} + +ecex_interactive_line_action_t *buffer_interactive_action_at_line(buffer_t *buffer, + size_t line) { + if (!buffer || !buffer->interactive) return NULL; + + for (size_t i = 0; i < buffer->interactive_action_count; i++) { + if (buffer->interactive_actions[i].line == line) { + return &buffer->interactive_actions[i]; + } + } + + return NULL; +} diff --git a/src/config.c b/src/config.c new file mode 100644 index 0000000..b416d7a --- /dev/null +++ b/src/config.c @@ -0,0 +1,293 @@ +#include "config.h" + +#include "buffers.h" +#include "ccdjit.h" +#include "common.h" +#include "ecex.h" +#include "eval.h" +#include "util.h" + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +typedef int (*ecex_config_init_fn)(ecex_t *ed); + +typedef struct host_symbol { + const char *name; + void *addr; +} host_symbol_t; + +void ecex_print_ccdjit_error(ccdjit_context *ctx) { + const ccdjit_diagnostic *diag = ccdjit_context_last_error(ctx); + + if (!diag) { + fprintf(stderr, "ccdjit: unknown error\n"); + return; + } + + fprintf(stderr, + "ccdjit error [%s] %s:%d:%d: %s\n", + diag->phase ? diag->phase : "?", + diag->filename ? diag->filename : "<input>", + diag->line, + diag->column, + diag->message ? diag->message : "(no message)"); + + if (diag->source_line) fprintf(stderr, "%s\n", diag->source_line); + if (diag->caret_line) fprintf(stderr, "%s\n", diag->caret_line); +} + +#define HOST_SYMBOL(fn) { #fn, (void *)(fn) } + +static const host_symbol_t host_symbols[] = { + HOST_SYMBOL(ecex_current_buffer), + HOST_SYMBOL(ecex_create_buffer), + HOST_SYMBOL(ecex_find_buffer), + HOST_SYMBOL(ecex_switch_buffer), + HOST_SYMBOL(ecex_next_buffer), + HOST_SYMBOL(ecex_previous_buffer), + HOST_SYMBOL(ecex_current_window), + HOST_SYMBOL(ecex_window_count), + HOST_SYMBOL(ecex_split_window_vertically), + HOST_SYMBOL(ecex_split_window_horizontally), + HOST_SYMBOL(ecex_other_window), + HOST_SYMBOL(ecex_previous_window), + HOST_SYMBOL(ecex_delete_window), + HOST_SYMBOL(ecex_delete_other_windows), + HOST_SYMBOL(ecex_kill_buffer), + + HOST_SYMBOL(ecex_register_command), + HOST_SYMBOL(ecex_execute_command), + HOST_SYMBOL(ecex_bind_key), + HOST_SYMBOL(ecex_lookup_key), + HOST_SYMBOL(ecex_define_major_mode), + HOST_SYMBOL(ecex_major_mode_by_name), + HOST_SYMBOL(ecex_major_mode_name), + HOST_SYMBOL(ecex_buffer_set_major_mode), + HOST_SYMBOL(ecex_buffer_set_major_mode_by_name), + HOST_SYMBOL(ecex_buffer_major_mode_name), + HOST_SYMBOL(ecex_bind_mode_key), + HOST_SYMBOL(ecex_lookup_key_for_buffer), + HOST_SYMBOL(ecex_key_sequence_has_prefix_for_buffer), + HOST_SYMBOL(ecex_auto_set_major_mode), + HOST_SYMBOL(ecex_list_commands), + HOST_SYMBOL(ecex_list_buffers), + HOST_SYMBOL(ecex_create_interactive_buffer), + HOST_SYMBOL(ecex_interactive_append_line), + HOST_SYMBOL(ecex_interactive_activate_current_line), + HOST_SYMBOL(ecex_find_file), + HOST_SYMBOL(ecex_save_current_buffer), + HOST_SYMBOL(ecex_write_current_buffer), + HOST_SYMBOL(ecex_request_prompt), + HOST_SYMBOL(ecex_clear_prompt_request), + HOST_SYMBOL(ecex_complete_command), + HOST_SYMBOL(ecex_eval_source), + HOST_SYMBOL(ecex_eval_current_buffer), + HOST_SYMBOL(ecex_eval_current_line), + HOST_SYMBOL(ecex_eval_current_region), + HOST_SYMBOL(ecex_eval_file), + HOST_SYMBOL(ecex_eval_rerun_last), + + HOST_SYMBOL(ecex_set_font), + HOST_SYMBOL(ecex_get_font_size), + HOST_SYMBOL(ecex_set_font_size), + HOST_SYMBOL(ecex_adjust_font_size), + HOST_SYMBOL(ecex_set_bg_color), + HOST_SYMBOL(ecex_set_fg_color), + HOST_SYMBOL(ecex_set_status_bg_color), + HOST_SYMBOL(ecex_set_status_fg_color), + HOST_SYMBOL(ecex_set_status_border_color), + HOST_SYMBOL(ecex_set_cursor_color), + HOST_SYMBOL(ecex_set_region_bg_color), + HOST_SYMBOL(ecex_set_minibuffer_bg_color), + HOST_SYMBOL(ecex_set_minibuffer_fg_color), + HOST_SYMBOL(ecex_set_completion_fg_color), + HOST_SYMBOL(ecex_set_completion_enabled), + HOST_SYMBOL(ecex_set_interactive_highlight_bg_color), + HOST_SYMBOL(ecex_set_interactive_highlight_fg_color), + + HOST_SYMBOL(buffer_clear), + HOST_SYMBOL(buffer_set_text), + HOST_SYMBOL(buffer_insert), + HOST_SYMBOL(buffer_insert_at), + HOST_SYMBOL(buffer_append), + HOST_SYMBOL(buffer_prepend), + HOST_SYMBOL(buffer_insert_char), + HOST_SYMBOL(buffer_insert_char_at), + HOST_SYMBOL(buffer_delete_range), + HOST_SYMBOL(buffer_delete_selection), + HOST_SYMBOL(buffer_replace_selection), + HOST_SYMBOL(buffer_backspace), + HOST_SYMBOL(buffer_delete_forward), + HOST_SYMBOL(buffer_kill_line), + + HOST_SYMBOL(buffer_set_point), + HOST_SYMBOL(buffer_move_left), + HOST_SYMBOL(buffer_move_right), + HOST_SYMBOL(buffer_move_up), + HOST_SYMBOL(buffer_move_down), + HOST_SYMBOL(buffer_move_word_left), + HOST_SYMBOL(buffer_move_word_right), + HOST_SYMBOL(buffer_move_beginning_of_line), + HOST_SYMBOL(buffer_move_end_of_line), + HOST_SYMBOL(buffer_move_beginning_of_buffer), + HOST_SYMBOL(buffer_move_end_of_buffer), + + HOST_SYMBOL(buffer_set_mark), + HOST_SYMBOL(buffer_clear_mark), + HOST_SYMBOL(buffer_has_selection), + HOST_SYMBOL(buffer_selection_range), + + HOST_SYMBOL(buffer_line_start_at), + HOST_SYMBOL(buffer_line_end_at), + HOST_SYMBOL(buffer_current_line_start), + HOST_SYMBOL(buffer_current_line_end), + HOST_SYMBOL(buffer_current_column), + HOST_SYMBOL(buffer_current_line_number), + HOST_SYMBOL(buffer_line_count), + HOST_SYMBOL(buffer_substring), + HOST_SYMBOL(buffer_current_line_copy), + + HOST_SYMBOL(buffer_load_file), + HOST_SYMBOL(buffer_save), + HOST_SYMBOL(buffer_save_as), + HOST_SYMBOL(buffer_set_interactive), + HOST_SYMBOL(buffer_is_interactive), + HOST_SYMBOL(buffer_clear_interactive_actions), + HOST_SYMBOL(buffer_add_interactive_action), + HOST_SYMBOL(buffer_interactive_action_at_line), +}; + +#undef HOST_SYMBOL + +int ecex_register_host_symbols(ccdjit_context *ctx) { + for (size_t i = 0; i < ECEX_ARRAY_LEN(host_symbols); i++) { + if (ccdjit_context_register_symbol(ctx, + host_symbols[i].name, + host_symbols[i].addr) != 0) { + fprintf(stderr, "ecex: failed to register symbol: %s\n", host_symbols[i].name); + ecex_print_ccdjit_error(ctx); + return ECEX_ERR; + } + } + + return ECEX_OK; +} + +static int add_include_path(ccdjit_context *ctx, const char *path) { + if (ccdjit_context_add_include_path(ctx, path) == 0) return ECEX_OK; + + fprintf(stderr, "ecex: failed to add include path: %s\n", path); + ecex_print_ccdjit_error(ctx); + return ECEX_ERR; +} + +int ecex_add_ccdjit_include_paths(ccdjit_context *ctx) { + if (add_include_path(ctx, "include") != ECEX_OK) return ECEX_ERR; + if (add_include_path(ctx, "../include") != ECEX_OK) return ECEX_ERR; + + const char *env_include = getenv("ECEX_INCLUDE"); + if (env_include && env_include[0]) { + if (add_include_path(ctx, env_include) != ECEX_OK) return ECEX_ERR; + } + + return ECEX_OK; +} + +static char *make_config_source_with_forced_main(const char *path) { + size_t source_size = 0; + char *source = ecex_read_entire_file(path, &source_size); + if (!source) return NULL; + + const char *forced_main = + "\n" + "\n" + "int main(int argc, char **argv) {\n" + " (void)argc;\n" + " (void)argv;\n" + " return ecex_config_init((ecex_t *)0);\n" + "}\n"; + + size_t forced_main_len = strlen(forced_main); + char *combined = malloc(source_size + forced_main_len + 1); + if (!combined) { + free(source); + return NULL; + } + + memcpy(combined, source, source_size); + memcpy(combined + source_size, forced_main, forced_main_len + 1); + + free(source); + return combined; +} + +int ecex_load_c_config(ecex_t *ed, const char *path) { + if (!ed || !path) return ECEX_ERR; + + ccdjit_context *ctx = ccdjit_context_new(NULL); + if (!ctx) { + fprintf(stderr, "ecex: failed to create ccdjit context\n"); + return ECEX_ERR; + } + + if (ecex_add_ccdjit_include_paths(ctx) != ECEX_OK || ecex_register_host_symbols(ctx) != ECEX_OK) { + ccdjit_context_free(ctx); + return ECEX_ERR; + } + + char *source = make_config_source_with_forced_main(path); + if (!source) { + fprintf(stderr, "ecex: failed to read or prepare config: %s\n", path); + ccdjit_context_free(ctx); + return ECEX_ERR; + } + + ccdjit_module *module = NULL; + if (ccdjit_compile_string(ctx, source, path, &module) != 0) { + fprintf(stderr, "ecex: failed to compile config: %s\n", path); + ecex_print_ccdjit_error(ctx); + free(source); + ccdjit_context_free(ctx); + return ECEX_ERR; + } + + free(source); + + ecex_config_init_fn init = + (ecex_config_init_fn)ccdjit_module_symbol(module, "ecex_config_init"); + + if (!init) { + fprintf(stderr, "ecex: config missing function: ecex_config_init\n"); + ecex_print_ccdjit_error(ctx); + ccdjit_module_free(module); + ccdjit_context_free(ctx); + return ECEX_ERR; + } + + int result = init(ed); + if (result != 0) { + fprintf(stderr, "ecex: config init failed with code: %d\n", result); + ccdjit_module_free(module); + ccdjit_context_free(ctx); + return ECEX_ERR; + } + + if (ecex_keep_jit_module(ed, module) != ECEX_OK) { + fprintf(stderr, "ecex: failed to retain config module\n"); + ccdjit_module_free(module); + ccdjit_context_free(ctx); + return ECEX_ERR; + } + + if (ecex_set_config_path(ed, path) != ECEX_OK) { + fprintf(stderr, "ecex: failed to remember config path: %s\n", path); + ccdjit_context_free(ctx); + return ECEX_ERR; + } + + ccdjit_context_free(ctx); + fprintf(stderr, "ecex: loaded config: %s\n", path); + return ECEX_OK; +} diff --git a/src/ecex.c b/src/ecex.c new file mode 100644 index 0000000..2f4c962 --- /dev/null +++ b/src/ecex.c @@ -0,0 +1,1630 @@ +#include "ecex.h" + +#include "ccdjit.h" +#include "common.h" +#include "config.h" +#include "util.h" + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +extern FILE *popen(const char *command, const char *type); +extern int pclose(FILE *stream); + +#define ECEX_INITIAL_BUFFER_CAP 8 +#define ECEX_INITIAL_COMMAND_CAP 32 +#define ECEX_INITIAL_KEYBIND_CAP 32 +#define ECEX_INITIAL_WINDOW_CAP 4 +#define ECEX_INITIAL_MODE_CAP 8 +#define ECEX_INITIAL_MODE_KEYBIND_CAP 16 + +ecex_window_t *ecex_current_window(ecex_t *ed); + +static ecex_color_t ecex_color(float r, float g, float b) { + ecex_color_t c = {r, g, b}; + return c; +} + +static void ecex_theme_set_defaults(ecex_t *ed) { + if (!ed) return; + + ed->theme.font_path = NULL; + ed->theme.font_size = 22.0f; + + ed->theme.bg = ecex_color(0.08f, 0.09f, 0.11f); + ed->theme.fg = ecex_color(0.88f, 0.88f, 0.86f); + + ed->theme.status_bg = ecex_color(0.15f, 0.15f, 0.18f); + ed->theme.status_fg = ecex_color(0.86f, 0.86f, 0.84f); + ed->theme.status_border = ecex_color(0.28f, 0.28f, 0.32f); + + ed->theme.cursor = ecex_color(1.0f, 1.0f, 1.0f); + ed->theme.region_bg = ecex_color(0.22f, 0.34f, 0.48f); + + ed->theme.minibuffer_bg = ecex_color(0.10f, 0.11f, 0.14f); + ed->theme.minibuffer_fg = ecex_color(0.95f, 0.95f, 0.90f); + + ed->theme.completion_fg = ecex_color(0.45f, 0.45f, 0.45f); + ed->theme.completion_enabled = 1; + + ed->theme.interactive_highlight_bg = ecex_color(0.18f, 0.20f, 0.24f); + ed->theme.interactive_highlight_fg = ecex_color(1.0f, 1.0f, 1.0f); + ed->theme.current_line_bg = ecex_color(0.12f, 0.13f, 0.16f); + ed->theme.search_bg = ecex_color(0.55f, 0.42f, 0.12f); + ed->theme.line_numbers_enabled = 1; + ed->theme.current_line_enabled = 1; +} + +#define ECEX_COMMAND(name, fn) \ + do { \ + if (ecex_register_command(ed, (name), (fn)) != ECEX_OK) return ECEX_ERR; \ + } while (0) + +#define ECEX_BIND(key, command) \ + do { \ + if (ecex_bind_key(ed, (key), (command)) != ECEX_OK) return ECEX_ERR; \ + } while (0) + +#define CURRENT_BUFFER_OR_ERR(ed) \ + buffer_t *buf = ecex_current_buffer(ed); \ + if (!buf) return ECEX_ERR + +static int cmd_quit(ecex_t *ed) { + if (!ed) return ECEX_ERR; + ed->should_quit = 1; + return ECEX_OK; +} + +static int cmd_next_buffer(ecex_t *ed) { return ecex_next_buffer(ed); } +static int cmd_previous_buffer(ecex_t *ed) { return ecex_previous_buffer(ed); } +static int cmd_split_window_right(ecex_t *ed) { return ecex_split_window_vertically(ed); } +static int cmd_split_window_below(ecex_t *ed) { return ecex_split_window_horizontally(ed); } +static int cmd_other_window(ecex_t *ed) { return ecex_other_window(ed); } +static int cmd_previous_window(ecex_t *ed) { return ecex_previous_window(ed); } +static int cmd_delete_window(ecex_t *ed) { return ecex_delete_window(ed); } +static int cmd_delete_other_windows(ecex_t *ed) { return ecex_delete_other_windows(ed); } +static int cmd_balance_windows(ecex_t *ed) { return ecex_balance_windows(ed); } + +static int cmd_move_left(ecex_t *ed) { CURRENT_BUFFER_OR_ERR(ed); buffer_move_left(buf); return ECEX_OK; } +static int cmd_move_right(ecex_t *ed) { CURRENT_BUFFER_OR_ERR(ed); buffer_move_right(buf); return ECEX_OK; } +static int cmd_move_up(ecex_t *ed) { CURRENT_BUFFER_OR_ERR(ed); buffer_move_up(buf); return ECEX_OK; } +static int cmd_move_down(ecex_t *ed) { CURRENT_BUFFER_OR_ERR(ed); buffer_move_down(buf); return ECEX_OK; } +static int cmd_move_word_left(ecex_t *ed) { CURRENT_BUFFER_OR_ERR(ed); buffer_move_word_left(buf); return ECEX_OK; } +static int cmd_move_word_right(ecex_t *ed) { CURRENT_BUFFER_OR_ERR(ed); buffer_move_word_right(buf); return ECEX_OK; } +static int cmd_beginning_of_line(ecex_t *ed) { CURRENT_BUFFER_OR_ERR(ed); buffer_move_beginning_of_line(buf); return ECEX_OK; } +static int cmd_end_of_line(ecex_t *ed) { CURRENT_BUFFER_OR_ERR(ed); buffer_move_end_of_line(buf); return ECEX_OK; } +static int cmd_beginning_of_buffer(ecex_t *ed) { CURRENT_BUFFER_OR_ERR(ed); buffer_move_beginning_of_buffer(buf); return ECEX_OK; } +static int cmd_end_of_buffer(ecex_t *ed) { CURRENT_BUFFER_OR_ERR(ed); buffer_move_end_of_buffer(buf); return ECEX_OK; } + +static int cmd_undo(ecex_t *ed) { CURRENT_BUFFER_OR_ERR(ed); return buffer_undo(buf); } +static int cmd_redo(ecex_t *ed) { CURRENT_BUFFER_OR_ERR(ed); return buffer_redo(buf); } +static int cmd_backspace(ecex_t *ed) { CURRENT_BUFFER_OR_ERR(ed); return buffer_backspace(buf); } +static int cmd_delete_forward(ecex_t *ed) { CURRENT_BUFFER_OR_ERR(ed); return buffer_delete_forward(buf); } +static int cmd_newline(ecex_t *ed) { + CURRENT_BUFFER_OR_ERR(ed); + if (buffer_is_interactive(buf)) { + return ecex_interactive_activate_current_line(ed); + } + return buffer_insert_char(buf, '\n'); +} +static int cmd_kill_line(ecex_t *ed) { CURRENT_BUFFER_OR_ERR(ed); return buffer_kill_line(buf); } +static int cmd_clear_buffer(ecex_t *ed) { CURRENT_BUFFER_OR_ERR(ed); return buffer_clear(buf); } +static int cmd_set_mark(ecex_t *ed) { CURRENT_BUFFER_OR_ERR(ed); buffer_set_mark(buf, buf->point); return ECEX_OK; } +static int cmd_clear_mark(ecex_t *ed) { CURRENT_BUFFER_OR_ERR(ed); buffer_clear_mark(buf); return ECEX_OK; } + + +static int cmd_yank(ecex_t *ed) { + CURRENT_BUFFER_OR_ERR(ed); + const char *text = ecex_clipboard_get(ed); + if (!text || !text[0]) return ECEX_OK; + return buffer_replace_selection(buf, text); +} + +static int cmd_copy_region(ecex_t *ed) { + CURRENT_BUFFER_OR_ERR(ed); + if (!buffer_has_selection(buf)) return ECEX_OK; + + size_t start = 0; + size_t end = 0; + buffer_selection_range(buf, &start, &end); + + char *text = buffer_substring(buf, start, end); + if (!text) return ECEX_ERR; + + int result = ecex_clipboard_set(ed, text); + free(text); + return result; +} + +static int cmd_kill_region(ecex_t *ed) { + CURRENT_BUFFER_OR_ERR(ed); + if (!buffer_has_selection(buf)) return ECEX_OK; + + size_t start = 0; + size_t end = 0; + buffer_selection_range(buf, &start, &end); + + char *text = buffer_substring(buf, start, end); + if (!text) return ECEX_ERR; + + int result = ecex_clipboard_set(ed, text); + free(text); + if (result != ECEX_OK) return result; + + return buffer_delete_selection(buf); +} + +static int cmd_list_commands(ecex_t *ed) { return ecex_list_commands(ed); } +static int cmd_list_buffers(ecex_t *ed) { return ecex_list_buffers(ed); } +static int cmd_switch_buffer(ecex_t *ed) { ecex_request_prompt(ed, ECEX_PROMPT_SWITCH_BUFFER, "Switch buffer: "); return ECEX_OK; } +static int cmd_kill_buffer_command(ecex_t *ed) { ecex_request_prompt(ed, ECEX_PROMPT_KILL_BUFFER, "Kill buffer: "); return ECEX_OK; } +static int cmd_compile(ecex_t *ed) { ecex_request_prompt(ed, ECEX_PROMPT_COMPILE, "Compile: "); return ECEX_OK; } +static int cmd_grep(ecex_t *ed) { ecex_request_prompt(ed, ECEX_PROMPT_GREP, "Grep: "); return ECEX_OK; } +static int cmd_recompile(ecex_t *ed) { return ecex_rerun_compile(ed); } +static int cmd_regrep(ecex_t *ed) { return ecex_rerun_grep(ed); } +static int cmd_next_error(ecex_t *ed) { return ecex_next_interactive_action(ed); } +static int cmd_previous_error(ecex_t *ed) { return ecex_previous_interactive_action(ed); } +static int cmd_comment_region(ecex_t *ed) { return ecex_comment_region(ed); } +static int cmd_uncomment_region(ecex_t *ed) { return ecex_uncomment_region(ed); } +static int cmd_toggle_line_numbers(ecex_t *ed) { if (!ed) return ECEX_ERR; ed->theme.line_numbers_enabled = !ed->theme.line_numbers_enabled; return ECEX_OK; } +static int cmd_toggle_current_line(ecex_t *ed) { if (!ed) return ECEX_ERR; ed->theme.current_line_enabled = !ed->theme.current_line_enabled; return ECEX_OK; } +static int cmd_isearch_forward(ecex_t *ed) { ecex_request_prompt(ed, ECEX_PROMPT_ISEARCH_FORWARD, "I-search: "); return ECEX_OK; } +static int cmd_isearch_backward(ecex_t *ed) { ecex_request_prompt(ed, ECEX_PROMPT_ISEARCH_BACKWARD, "I-search backward: "); return ECEX_OK; } + +static int cmd_find_file(ecex_t *ed) { + ecex_request_prompt(ed, ECEX_PROMPT_FIND_FILE, "Find file: "); + return ECEX_OK; +} + +static int cmd_write_file(ecex_t *ed) { + ecex_request_prompt(ed, ECEX_PROMPT_WRITE_FILE, "Write file: "); + return ECEX_OK; +} + +static int cmd_save_buffer(ecex_t *ed) { + if (!ed) return ECEX_ERR; + + buffer_t *buf = ecex_current_buffer(ed); + if (!buf) return ECEX_ERR; + + if (!buf->path) { + ecex_request_prompt(ed, ECEX_PROMPT_WRITE_FILE, "Write file: "); + return ECEX_OK; + } + + return ecex_save_current_buffer(ed); +} + +static int cmd_eval_buffer(ecex_t *ed) { + return ecex_eval_current_buffer(ed); +} + +static int cmd_eval_line(ecex_t *ed) { + return ecex_eval_current_line(ed); +} + +static int cmd_eval_region(ecex_t *ed) { + return ecex_eval_current_region(ed); +} + +static int cmd_eval_file(ecex_t *ed) { + ecex_request_prompt(ed, ECEX_PROMPT_EVAL_FILE, "Eval file: "); + return ECEX_OK; +} + +static int cmd_eval_rerun_last(ecex_t *ed) { + return ecex_eval_rerun_last(ed); +} + +static int cmd_quit_window(ecex_t *ed) { + if (!ed) return ECEX_ERR; + if (ecex_window_count(ed) > 1) return ecex_delete_window(ed); + return ecex_previous_buffer(ed); +} + +static int cmd_reload_config(ecex_t *ed) { + return ecex_reload_config(ed); +} + +static int ecex_register_builtins(ecex_t *ed) { + ECEX_COMMAND("quit", cmd_quit); + ECEX_COMMAND("find-file", cmd_find_file); + ECEX_COMMAND("save-buffer", cmd_save_buffer); + ECEX_COMMAND("write-file", cmd_write_file); + ECEX_COMMAND("eval-buffer", cmd_eval_buffer); + ECEX_COMMAND("eval-line", cmd_eval_line); + ECEX_COMMAND("eval-region", cmd_eval_region); + ECEX_COMMAND("eval-selection", cmd_eval_region); + ECEX_COMMAND("eval-file", cmd_eval_file); + ECEX_COMMAND("eval-rerun-last", cmd_eval_rerun_last); + ECEX_COMMAND("revert-eval-buffer", cmd_eval_rerun_last); + ECEX_COMMAND("quit-window", cmd_quit_window); + ECEX_COMMAND("reload-config", cmd_reload_config); + ECEX_COMMAND("list-commands", cmd_list_commands); + ECEX_COMMAND("list-buffers", cmd_list_buffers); + ECEX_COMMAND("switch-buffer", cmd_switch_buffer); + ECEX_COMMAND("kill-buffer", cmd_kill_buffer_command); + ECEX_COMMAND("compile", cmd_compile); + ECEX_COMMAND("recompile", cmd_recompile); + ECEX_COMMAND("grep", cmd_grep); + ECEX_COMMAND("regrep", cmd_regrep); + ECEX_COMMAND("next-error", cmd_next_error); + ECEX_COMMAND("previous-error", cmd_previous_error); + ECEX_COMMAND("comment-region", cmd_comment_region); + ECEX_COMMAND("uncomment-region", cmd_uncomment_region); + ECEX_COMMAND("toggle-line-numbers", cmd_toggle_line_numbers); + ECEX_COMMAND("toggle-current-line", cmd_toggle_current_line); + ECEX_COMMAND("isearch-forward", cmd_isearch_forward); + ECEX_COMMAND("isearch-backward", cmd_isearch_backward); + + ECEX_COMMAND("next-buffer", cmd_next_buffer); + ECEX_COMMAND("previous-buffer", cmd_previous_buffer); + ECEX_COMMAND("split-window-right", cmd_split_window_right); + ECEX_COMMAND("split-window-vertically", cmd_split_window_right); + ECEX_COMMAND("split-window-below", cmd_split_window_below); + ECEX_COMMAND("split-window-horizontally", cmd_split_window_below); + ECEX_COMMAND("other-window", cmd_other_window); + ECEX_COMMAND("previous-window", cmd_previous_window); + ECEX_COMMAND("delete-window", cmd_delete_window); + ECEX_COMMAND("delete-other-windows", cmd_delete_other_windows); + ECEX_COMMAND("balance-windows", cmd_balance_windows); + + ECEX_COMMAND("move-left", cmd_move_left); + ECEX_COMMAND("move-right", cmd_move_right); + ECEX_COMMAND("move-up", cmd_move_up); + ECEX_COMMAND("move-down", cmd_move_down); + ECEX_COMMAND("move-word-left", cmd_move_word_left); + ECEX_COMMAND("move-word-right", cmd_move_word_right); + ECEX_COMMAND("beginning-of-line", cmd_beginning_of_line); + ECEX_COMMAND("end-of-line", cmd_end_of_line); + ECEX_COMMAND("beginning-of-buffer", cmd_beginning_of_buffer); + ECEX_COMMAND("end-of-buffer", cmd_end_of_buffer); + + ECEX_COMMAND("undo", cmd_undo); + ECEX_COMMAND("redo", cmd_redo); + ECEX_COMMAND("backspace", cmd_backspace); + ECEX_COMMAND("delete-forward", cmd_delete_forward); + ECEX_COMMAND("newline", cmd_newline); + ECEX_COMMAND("kill-line", cmd_kill_line); + ECEX_COMMAND("clear-buffer", cmd_clear_buffer); + ECEX_COMMAND("set-mark", cmd_set_mark); + ECEX_COMMAND("clear-mark", cmd_clear_mark); + ECEX_COMMAND("yank", cmd_yank); + ECEX_COMMAND("paste", cmd_yank); + ECEX_COMMAND("copy-region", cmd_copy_region); + ECEX_COMMAND("copy-region-as-kill", cmd_copy_region); + ECEX_COMMAND("kill-region", cmd_kill_region); + + ECEX_BIND("LEFT", "move-left"); + ECEX_BIND("RIGHT", "move-right"); + ECEX_BIND("UP", "move-up"); + ECEX_BIND("DOWN", "move-down"); + + ECEX_BIND("C-b", "move-left"); + ECEX_BIND("C-f", "move-right"); + ECEX_BIND("C-p", "move-up"); + ECEX_BIND("C-n", "move-down"); + ECEX_BIND("C-a", "beginning-of-line"); + ECEX_BIND("C-e", "end-of-line"); + ECEX_BIND("C-k", "kill-line"); + ECEX_BIND("C-SPC", "set-mark"); + ECEX_BIND("C-y", "yank"); + ECEX_BIND("C-v", "paste"); + ECEX_BIND("M-w", "copy-region-as-kill"); + ECEX_BIND("C-w", "kill-region"); + ECEX_BIND("C-s", "isearch-forward"); + ECEX_BIND("C-r", "isearch-backward"); + ECEX_BIND("C-/", "undo"); + ECEX_BIND("C-z", "undo"); + ECEX_BIND("C-S-z", "redo"); + + ECEX_BIND("C-x C-f", "find-file"); + ECEX_BIND("C-x C-s", "save-buffer"); + ECEX_BIND("C-x C-w", "write-file"); + ECEX_BIND("C-x C-b", "list-buffers"); + ECEX_BIND("C-x b", "switch-buffer"); + ECEX_BIND("C-x k", "kill-buffer"); + ECEX_BIND("C-x 2", "split-window-below"); + ECEX_BIND("C-x 3", "split-window-right"); + ECEX_BIND("C-x o", "other-window"); + ECEX_BIND("C-x O", "previous-window"); + ECEX_BIND("C-x 0", "delete-window"); + ECEX_BIND("C-x 1", "delete-other-windows"); + ECEX_BIND("C-x +", "balance-windows"); + ECEX_BIND("C-x e b", "eval-buffer"); + ECEX_BIND("C-x e l", "eval-line"); + ECEX_BIND("C-x C-e", "eval-line"); + ECEX_BIND("C-x e r", "eval-region"); + ECEX_BIND("C-x e f", "eval-file"); + ECEX_BIND("C-x C-r", "reload-config"); + ECEX_BIND("F5", "reload-config"); + ECEX_BIND("M-g n", "next-error"); + ECEX_BIND("M-g p", "previous-error"); + ECEX_BIND("M-;", "comment-region"); + + ECEX_BIND("BACKSPACE", "backspace"); + ECEX_BIND("DELETE", "delete-forward"); + ECEX_BIND("ENTER", "newline"); + + ecex_define_major_mode(ed, "fundamental-mode"); + ecex_define_major_mode(ed, "c-mode"); + ecex_define_major_mode(ed, "eval-output-mode"); + ecex_define_major_mode(ed, "special-mode"); + ecex_bind_mode_key(ed, "eval-output-mode", "g", "eval-rerun-last"); + ecex_bind_mode_key(ed, "eval-output-mode", "q", "quit-window"); + ecex_bind_mode_key(ed, "eval-output-mode", "r", "eval-rerun-last"); + ecex_bind_mode_key(ed, "special-mode", "q", "quit-window"); + ecex_bind_mode_key(ed, "special-mode", "g", "recompile"); + ecex_bind_mode_key(ed, "special-mode", "n", "next-error"); + ecex_bind_mode_key(ed, "special-mode", "p", "previous-error"); + + return ECEX_OK; +} + +#undef ECEX_COMMAND +#undef ECEX_BIND +#undef CURRENT_BUFFER_OR_ERR + +ecex_t *ecex_new(void) { + ecex_t *ed = calloc(1, sizeof(*ed)); + if (!ed) return NULL; + + ecex_theme_set_defaults(ed); + + buffer_t *scratch = buffer_new("*scratch*", NULL, 0); + if (!scratch || ecex_add_buffer(ed, scratch) != ECEX_OK) { + buffer_free(scratch); + ecex_free(ed); + return NULL; + } + + ed->current_buffer_index = 0; + ed->current_buffer = scratch; + ed->next_major_mode_id = 1; + + ed->window_cap = ECEX_INITIAL_WINDOW_CAP; + ed->windows = calloc(ed->window_cap, sizeof(*ed->windows)); + if (!ed->windows) { + ecex_free(ed); + return NULL; + } + ed->window_count = 1; + ed->current_window_index = 0; + ed->windows[0].buffer = scratch; + ed->windows[0].x = 0.0f; + ed->windows[0].y = 0.0f; + ed->windows[0].w = 1.0f; + ed->windows[0].h = 1.0f; + + if (ecex_register_builtins(ed) != ECEX_OK) { + ecex_free(ed); + return NULL; + } + + ecex_buffer_set_major_mode_by_name(ed, scratch, "fundamental-mode"); + + return ed; +} + +void ecex_free(ecex_t *ed) { + if (!ed) return; + + for (size_t i = 0; i < ed->jit_module_count; i++) { + ccdjit_module_free((ccdjit_module *)ed->jit_modules[i]); + } + + for (size_t i = 0; i < ed->buffer_count; i++) { + buffer_free(ed->buffers[i]); + } + + for (size_t i = 0; i < ed->command_count; i++) { + free(ed->commands[i].name); + } + + for (size_t i = 0; i < ed->keybind_count; i++) { + free(ed->keybinds[i].key); + free(ed->keybinds[i].command); + } + + for (size_t i = 0; i < ed->mode_keybind_count; i++) { + free(ed->mode_keybinds[i].key); + free(ed->mode_keybinds[i].command); + } + + for (size_t i = 0; i < ed->major_mode_count; i++) { + free(ed->major_modes[i].name); + } + + free(ed->jit_modules); + free(ed->windows); + free(ed->buffers); + free(ed->commands); + free(ed->keybinds); + free(ed->mode_keybinds); + free(ed->major_modes); + free(ed->last_eval_source); + free(ed->last_eval_filename); + free(ed->last_compile_command); + free(ed->last_grep_command); + free(ed->config_path); + free(ed->theme.font_path); + free(ed); +} + +int ecex_reserve_buffers(ecex_t *ed, size_t needed) { + ECEX_RETURN_ERR_IF_NULL(ed); + if (needed <= ed->buffer_cap) return ECEX_OK; + + while (ed->buffer_cap < needed) { + if (ECEX_GROW_ARRAY(ed->buffers, + ed->buffer_count, + ed->buffer_cap, + ECEX_INITIAL_BUFFER_CAP) != ECEX_OK) { + return ECEX_ERR; + } + } + + return ECEX_OK; +} + +int ecex_add_buffer(ecex_t *ed, buffer_t *buffer) { + if (!ed || !buffer) return ECEX_ERR; + + if (ecex_reserve_buffers(ed, ed->buffer_count + 1) != ECEX_OK) return ECEX_ERR; + + ed->buffers[ed->buffer_count++] = buffer; + + if (!ed->current_buffer) { + ed->current_buffer_index = 0; + ed->current_buffer = buffer; + } + + return ECEX_OK; +} + +buffer_t *ecex_create_buffer(ecex_t *ed, + const char *name, + const char *path, + int read_only) { + if (!ed || !name) return NULL; + + buffer_t *buffer = buffer_new(name, path, read_only); + if (!buffer) return NULL; + + if (ecex_add_buffer(ed, buffer) != ECEX_OK) { + buffer_free(buffer); + return NULL; + } + + return buffer; +} + +buffer_t *ecex_find_buffer(ecex_t *ed, const char *name) { + if (!ed || !name) return NULL; + + for (size_t i = 0; i < ed->buffer_count; i++) { + if (strcmp(ed->buffers[i]->name, name) == 0) { + return ed->buffers[i]; + } + } + + return NULL; +} + + +static int ecex_set_current_buffer_index(ecex_t *ed, size_t index) { + if (!ed || index >= ed->buffer_count) return ECEX_ERR; + ed->current_buffer_index = index; + ed->current_buffer = ed->buffers[index]; + ecex_window_t *win = ecex_current_window(ed); + if (win) win->buffer = ed->current_buffer; + return ECEX_OK; +} + +int ecex_sync_current_buffer(ecex_t *ed) { + if (!ed) return ECEX_ERR; + ecex_window_t *win = ecex_current_window(ed); + if (!win || !win->buffer) return ECEX_ERR; + + ed->current_buffer = win->buffer; + for (size_t i = 0; i < ed->buffer_count; i++) { + if (ed->buffers[i] == win->buffer) { + ed->current_buffer_index = i; + return ECEX_OK; + } + } + return ECEX_ERR; +} + +int ecex_switch_buffer(ecex_t *ed, const char *name) { + if (!ed || !name) return ECEX_ERR; + + for (size_t i = 0; i < ed->buffer_count; i++) { + if (strcmp(ed->buffers[i]->name, name) == 0) { + return ecex_set_current_buffer_index(ed, i); + } + } + + return ECEX_ERR; +} + +buffer_t *ecex_current_buffer(ecex_t *ed) { + if (!ed) return NULL; + ecex_window_t *win = ecex_current_window(ed); + if (win && win->buffer) return win->buffer; + return ed->current_buffer; +} + +ecex_window_t *ecex_current_window(ecex_t *ed) { + if (!ed || ed->window_count == 0 || ed->current_window_index >= ed->window_count) return NULL; + return &ed->windows[ed->current_window_index]; +} + +size_t ecex_window_count(ecex_t *ed) { + return ed ? ed->window_count : 0; +} + +static int ecex_reserve_windows(ecex_t *ed, size_t needed) { + if (!ed) return ECEX_ERR; + if (needed <= ed->window_cap) return ECEX_OK; + while (ed->window_cap < needed) { + if (ECEX_GROW_ARRAY(ed->windows, + ed->window_count, + ed->window_cap, + ECEX_INITIAL_WINDOW_CAP) != ECEX_OK) { + return ECEX_ERR; + } + } + return ECEX_OK; +} + +static int ecex_add_window(ecex_t *ed, ecex_window_t win) { + if (!ed || !win.buffer) return ECEX_ERR; + if (ecex_reserve_windows(ed, ed->window_count + 1) != ECEX_OK) return ECEX_ERR; + ed->windows[ed->window_count++] = win; + return ECEX_OK; +} + +int ecex_split_window_vertically(ecex_t *ed) { + ecex_window_t *active = ecex_current_window(ed); + if (!active || !active->buffer || active->w < 0.08f) return ECEX_ERR; + + ecex_window_t new_win = *active; + float half = active->w * 0.5f; + active->w = half; + new_win.x = active->x + half; + new_win.w = half; + + if (ecex_add_window(ed, new_win) != ECEX_OK) return ECEX_ERR; + ed->current_window_index = ed->window_count - 1; + return ecex_sync_current_buffer(ed); +} + +int ecex_split_window_horizontally(ecex_t *ed) { + ecex_window_t *active = ecex_current_window(ed); + if (!active || !active->buffer || active->h < 0.08f) return ECEX_ERR; + + ecex_window_t new_win = *active; + float half = active->h * 0.5f; + active->h = half; + new_win.y = active->y + half; + new_win.h = half; + + if (ecex_add_window(ed, new_win) != ECEX_OK) return ECEX_ERR; + ed->current_window_index = ed->window_count - 1; + return ecex_sync_current_buffer(ed); +} + +int ecex_other_window(ecex_t *ed) { + if (!ed || ed->window_count == 0) return ECEX_ERR; + ed->current_window_index = (ed->current_window_index + 1) % ed->window_count; + return ecex_sync_current_buffer(ed); +} + +int ecex_previous_window(ecex_t *ed) { + if (!ed || ed->window_count == 0) return ECEX_ERR; + if (ed->current_window_index == 0) ed->current_window_index = ed->window_count - 1; + else ed->current_window_index--; + return ecex_sync_current_buffer(ed); +} + +int ecex_delete_window(ecex_t *ed) { + if (!ed || ed->window_count <= 1 || ed->current_window_index >= ed->window_count) return ECEX_ERR; + + size_t index = ed->current_window_index; + for (size_t i = index; i + 1 < ed->window_count; i++) { + ed->windows[i] = ed->windows[i + 1]; + } + ed->window_count--; + if (ed->current_window_index >= ed->window_count) ed->current_window_index = ed->window_count - 1; + return ecex_sync_current_buffer(ed); +} + +int ecex_delete_other_windows(ecex_t *ed) { + ecex_window_t *active = ecex_current_window(ed); + if (!ed || !active) return ECEX_ERR; + ecex_window_t keep = *active; + keep.x = 0.0f; keep.y = 0.0f; keep.w = 1.0f; keep.h = 1.0f; + ed->windows[0] = keep; + ed->window_count = 1; + ed->current_window_index = 0; + return ecex_sync_current_buffer(ed); +} + +int ecex_balance_windows(ecex_t *ed) { + if (!ed || ed->window_count == 0) return ECEX_ERR; + size_t n = ed->window_count; + size_t cols = 1; + while (cols * cols < n) cols++; + size_t rows = (n + cols - 1) / cols; + for (size_t i = 0; i < n; i++) { + size_t row = i / cols; + size_t col = i % cols; + ed->windows[i].x = (float)col / (float)cols; + ed->windows[i].y = (float)row / (float)rows; + ed->windows[i].w = 1.0f / (float)cols; + ed->windows[i].h = 1.0f / (float)rows; + } + return ecex_sync_current_buffer(ed); +} + +int ecex_next_buffer(ecex_t *ed) { + if (!ed || ed->buffer_count == 0) return ECEX_ERR; + ecex_sync_current_buffer(ed); + return ecex_set_current_buffer_index(ed, (ed->current_buffer_index + 1) % ed->buffer_count); +} + +int ecex_previous_buffer(ecex_t *ed) { + if (!ed || ed->buffer_count == 0) return ECEX_ERR; + ecex_sync_current_buffer(ed); + + if (ed->current_buffer_index == 0) { + ed->current_buffer_index = ed->buffer_count - 1; + } else { + ed->current_buffer_index--; + } + + return ecex_set_current_buffer_index(ed, ed->current_buffer_index); +} + +int ecex_kill_buffer(ecex_t *ed, const char *name) { + if (!ed || !name || ed->buffer_count == 0) return ECEX_ERR; + + size_t index = ed->buffer_count; + for (size_t i = 0; i < ed->buffer_count; i++) { + if (strcmp(ed->buffers[i]->name, name) == 0) { + index = i; + break; + } + } + + if (index == ed->buffer_count) return ECEX_ERR; + + buffer_t *victim = ed->buffers[index]; + + for (size_t i = index; i + 1 < ed->buffer_count; i++) { + ed->buffers[i] = ed->buffers[i + 1]; + } + + ed->buffer_count--; + + buffer_t *fallback = ed->buffer_count > 0 ? ed->buffers[0] : NULL; + for (size_t i = 0; i < ed->window_count; i++) { + if (ed->windows[i].buffer == victim) { + ed->windows[i].buffer = fallback; + } + } + + buffer_free(victim); + + if (ed->buffer_count == 0) { + ed->current_buffer = NULL; + ed->current_buffer_index = 0; + ed->window_count = 0; + ed->current_window_index = 0; + return ECEX_OK; + } + + if (ed->current_window_index >= ed->window_count) { + ed->current_window_index = ed->window_count ? ed->window_count - 1 : 0; + } + + return ecex_sync_current_buffer(ed); +} + +int ecex_keep_jit_module(ecex_t *ed, void *module) { + if (!ed || !module) return ECEX_ERR; + + if (ECEX_GROW_ARRAY(ed->jit_modules, + ed->jit_module_count, + ed->jit_module_cap, + 8) != ECEX_OK) { + return ECEX_ERR; + } + + ed->jit_modules[ed->jit_module_count++] = module; + return ECEX_OK; +} + +int ecex_set_config_path(ecex_t *ed, const char *path) { + if (!ed) return ECEX_ERR; + + char *copy = NULL; + if (path && path[0]) { + copy = ecex_strdup(path); + if (!copy) return ECEX_ERR; + } + + free(ed->config_path); + ed->config_path = copy; + return ECEX_OK; +} + +const char *ecex_config_path(ecex_t *ed) { + if (!ed) return NULL; + return ed->config_path; +} + +static void ecex_clear_commands(ecex_t *ed) { + if (!ed) return; + + for (size_t i = 0; i < ed->command_count; i++) { + free(ed->commands[i].name); + } + ed->command_count = 0; +} + +static void ecex_clear_keybinds(ecex_t *ed) { + if (!ed) return; + + for (size_t i = 0; i < ed->keybind_count; i++) { + free(ed->keybinds[i].key); + free(ed->keybinds[i].command); + } + ed->keybind_count = 0; +} + +static void ecex_clear_mode_keybinds(ecex_t *ed) { + if (!ed) return; + + for (size_t i = 0; i < ed->mode_keybind_count; i++) { + free(ed->mode_keybinds[i].key); + free(ed->mode_keybinds[i].command); + } + ed->mode_keybind_count = 0; +} + +int ecex_reload_config(ecex_t *ed) { + if (!ed || !ed->config_path || !ed->config_path[0]) { + fprintf(stderr, "ecex: no config file to reload; start with --config path/to/ecexrc.c\n"); + return ECEX_ERR; + } + + char *path = ecex_strdup(ed->config_path); + if (!path) return ECEX_ERR; + + ecex_clear_commands(ed); + ecex_clear_keybinds(ed); + ecex_clear_mode_keybinds(ed); + + if (ecex_register_builtins(ed) != ECEX_OK) { + free(path); + return ECEX_ERR; + } + + int result = ecex_load_c_config(ed, path); + free(path); + return result; +} + +int ecex_register_command(ecex_t *ed, const char *name, ecex_command_fn fn) { + if (!ed || !name || !fn) return ECEX_ERR; + + for (size_t i = 0; i < ed->command_count; i++) { + if (strcmp(ed->commands[i].name, name) == 0) { + ed->commands[i].fn = fn; + return ECEX_OK; + } + } + + if (ECEX_GROW_ARRAY(ed->commands, + ed->command_count, + ed->command_cap, + ECEX_INITIAL_COMMAND_CAP) != ECEX_OK) { + return ECEX_ERR; + } + + char *copy = ecex_strdup(name); + if (!copy) return ECEX_ERR; + + ed->commands[ed->command_count].name = copy; + ed->commands[ed->command_count].fn = fn; + ed->command_count++; + return ECEX_OK; +} + +int ecex_execute_command(ecex_t *ed, const char *name) { + if (!ed || !name) return ECEX_ERR; + + for (size_t i = 0; i < ed->command_count; i++) { + if (strcmp(ed->commands[i].name, name) == 0) { + return ed->commands[i].fn(ed); + } + } + + return ECEX_ERR; +} + +void ecex_set_clipboard_callbacks(ecex_t *ed, + ecex_clipboard_get_fn get_fn, + ecex_clipboard_set_fn set_fn, + void *userdata) { + if (!ed) return; + ed->clipboard_get = get_fn; + ed->clipboard_set = set_fn; + ed->clipboard_userdata = userdata; +} + +const char *ecex_clipboard_get(ecex_t *ed) { + if (!ed || !ed->clipboard_get) return NULL; + return ed->clipboard_get(ed->clipboard_userdata); +} + +int ecex_clipboard_set(ecex_t *ed, const char *text) { + if (!ed || !ed->clipboard_set || !text) return ECEX_ERR; + ed->clipboard_set(ed->clipboard_userdata, text); + return ECEX_OK; +} + +int ecex_bind_key(ecex_t *ed, const char *key, const char *command) { + if (!ed || !key || !command) return ECEX_ERR; + + for (size_t i = 0; i < ed->keybind_count; i++) { + if (strcmp(ed->keybinds[i].key, key) == 0) { + char *new_command = ecex_strdup(command); + if (!new_command) return ECEX_ERR; + + free(ed->keybinds[i].command); + ed->keybinds[i].command = new_command; + return ECEX_OK; + } + } + + if (ECEX_GROW_ARRAY(ed->keybinds, + ed->keybind_count, + ed->keybind_cap, + ECEX_INITIAL_KEYBIND_CAP) != ECEX_OK) { + return ECEX_ERR; + } + + char *key_copy = ecex_strdup(key); + char *command_copy = ecex_strdup(command); + if (!key_copy || !command_copy) { + free(key_copy); + free(command_copy); + return ECEX_ERR; + } + + ed->keybinds[ed->keybind_count].key = key_copy; + ed->keybinds[ed->keybind_count].command = command_copy; + ed->keybind_count++; + return ECEX_OK; +} + +const char *ecex_lookup_key(ecex_t *ed, const char *key) { + if (!ed || !key) return NULL; + + for (size_t i = 0; i < ed->keybind_count; i++) { + if (strcmp(ed->keybinds[i].key, key) == 0) { + return ed->keybinds[i].command; + } + } + + return NULL; +} + +int ecex_define_major_mode(ecex_t *ed, const char *name) { + if (!ed || !name || !name[0]) return 0; + + for (size_t i = 0; i < ed->major_mode_count; i++) { + if (strcmp(ed->major_modes[i].name, name) == 0) { + return ed->major_modes[i].id; + } + } + + if (ECEX_GROW_ARRAY(ed->major_modes, + ed->major_mode_count, + ed->major_mode_cap, + ECEX_INITIAL_MODE_CAP) != ECEX_OK) { + return 0; + } + + char *copy = ecex_strdup(name); + if (!copy) return 0; + + int id = ed->next_major_mode_id++; + ed->major_modes[ed->major_mode_count].id = id; + ed->major_modes[ed->major_mode_count].name = copy; + ed->major_mode_count++; + return id; +} + +int ecex_major_mode_by_name(ecex_t *ed, const char *name) { + if (!ed || !name) return 0; + for (size_t i = 0; i < ed->major_mode_count; i++) { + if (strcmp(ed->major_modes[i].name, name) == 0) return ed->major_modes[i].id; + } + return 0; +} + +const char *ecex_major_mode_name(ecex_t *ed, int mode) { + if (!ed || mode == 0) return "fundamental-mode"; + for (size_t i = 0; i < ed->major_mode_count; i++) { + if (ed->major_modes[i].id == mode) return ed->major_modes[i].name; + } + return "unknown-mode"; +} + +int ecex_buffer_set_major_mode(buffer_t *buffer, int mode) { + if (!buffer) return ECEX_ERR; + buffer->major_mode = mode; + return ECEX_OK; +} + +int ecex_buffer_set_major_mode_by_name(ecex_t *ed, buffer_t *buffer, const char *name) { + if (!ed || !buffer || !name) return ECEX_ERR; + int mode = ecex_define_major_mode(ed, name); + if (!mode) return ECEX_ERR; + return ecex_buffer_set_major_mode(buffer, mode); +} + +const char *ecex_buffer_major_mode_name(ecex_t *ed, buffer_t *buffer) { + if (!buffer) return "fundamental-mode"; + return ecex_major_mode_name(ed, buffer->major_mode); +} + +int ecex_bind_mode_key(ecex_t *ed, const char *mode_name, const char *key, const char *command) { + if (!ed || !mode_name || !key || !command) return ECEX_ERR; + + int mode = ecex_define_major_mode(ed, mode_name); + if (!mode) return ECEX_ERR; + + for (size_t i = 0; i < ed->mode_keybind_count; i++) { + if (ed->mode_keybinds[i].mode == mode && strcmp(ed->mode_keybinds[i].key, key) == 0) { + char *new_command = ecex_strdup(command); + if (!new_command) return ECEX_ERR; + free(ed->mode_keybinds[i].command); + ed->mode_keybinds[i].command = new_command; + return ECEX_OK; + } + } + + if (ECEX_GROW_ARRAY(ed->mode_keybinds, + ed->mode_keybind_count, + ed->mode_keybind_cap, + ECEX_INITIAL_MODE_KEYBIND_CAP) != ECEX_OK) { + return ECEX_ERR; + } + + char *key_copy = ecex_strdup(key); + char *command_copy = ecex_strdup(command); + if (!key_copy || !command_copy) { + free(key_copy); + free(command_copy); + return ECEX_ERR; + } + + ed->mode_keybinds[ed->mode_keybind_count].mode = mode; + ed->mode_keybinds[ed->mode_keybind_count].key = key_copy; + ed->mode_keybinds[ed->mode_keybind_count].command = command_copy; + ed->mode_keybind_count++; + return ECEX_OK; +} + +const char *ecex_lookup_key_for_buffer(ecex_t *ed, buffer_t *buffer, const char *key) { + if (!ed || !key) return NULL; + + int mode = buffer ? buffer->major_mode : 0; + if (mode) { + for (size_t i = 0; i < ed->mode_keybind_count; i++) { + if (ed->mode_keybinds[i].mode == mode && strcmp(ed->mode_keybinds[i].key, key) == 0) { + return ed->mode_keybinds[i].command; + } + } + } + + return ecex_lookup_key(ed, key); +} + +int ecex_key_sequence_has_prefix_for_buffer(ecex_t *ed, buffer_t *buffer, const char *prefix) { + if (!ed || !prefix) return 0; + size_t prefix_len = strlen(prefix); + int mode = buffer ? buffer->major_mode : 0; + + if (mode) { + for (size_t i = 0; i < ed->mode_keybind_count; i++) { + const char *key = ed->mode_keybinds[i].key; + if (ed->mode_keybinds[i].mode == mode && + strncmp(key, prefix, prefix_len) == 0 && key[prefix_len] == ' ') { + return 1; + } + } + } + + for (size_t i = 0; i < ed->keybind_count; i++) { + const char *key = ed->keybinds[i].key; + if (strncmp(key, prefix, prefix_len) == 0 && key[prefix_len] == ' ') return 1; + } + + return 0; +} + +int ecex_auto_set_major_mode(ecex_t *ed, buffer_t *buffer) { + if (!ed || !buffer) return ECEX_ERR; + + const char *name = "fundamental-mode"; + const char *path = buffer->path ? buffer->path : buffer->name; + const char *dot = path ? strrchr(path, '.') : NULL; + + if (dot && (strcmp(dot, ".c") == 0 || strcmp(dot, ".h") == 0 || + strcmp(dot, ".cc") == 0 || strcmp(dot, ".cpp") == 0 || + strcmp(dot, ".hpp") == 0)) { + name = "c-mode"; + } + + if (buffer_is_interactive(buffer) && buffer->name && buffer->name[0] == '*') { + name = "special-mode"; + } + + return ecex_buffer_set_major_mode_by_name(ed, buffer, name); +} + +int ecex_list_commands(ecex_t *ed) { + if (!ed) return ECEX_ERR; + + buffer_t *buf = ecex_find_buffer(ed, "*commands*"); + if (!buf) { + buf = ecex_create_buffer(ed, "*commands*", NULL, 0); + if (!buf) return ECEX_ERR; + } + + if (buffer_clear(buf) != ECEX_OK) return ECEX_ERR; + buffer_append(buf, "Commands:\n\n"); + + for (size_t i = 0; i < ed->command_count; i++) { + const char *command_name = ed->commands[i].name; + int first_key = 1; + + buffer_append(buf, " "); + buffer_append(buf, command_name); + + for (size_t j = 0; j < ed->keybind_count; j++) { + if (strcmp(ed->keybinds[j].command, command_name) == 0) { + buffer_append(buf, first_key ? " [" : ", "); + buffer_append(buf, ed->keybinds[j].key); + first_key = 0; + } + } + + for (size_t j = 0; j < ed->mode_keybind_count; j++) { + if (strcmp(ed->mode_keybinds[j].command, command_name) == 0) { + buffer_append(buf, first_key ? " [" : ", "); + buffer_append(buf, ecex_major_mode_name(ed, ed->mode_keybinds[j].mode)); + buffer_append(buf, ":"); + buffer_append(buf, ed->mode_keybinds[j].key); + first_key = 0; + } + } + + if (!first_key) buffer_append(buf, "]"); + buffer_append(buf, "\n"); + } + + buf->point = 0; + buf->modified = 0; + return ecex_switch_buffer(ed, "*commands*"); +} + + + +static int ecex_interactive_switch_buffer_action(ecex_t *ed, + buffer_t *buffer, + size_t line, + const char *payload, + void *userdata) { + (void)buffer; + (void)line; + (void)userdata; + + if (!ed || !payload) return ECEX_ERR; + return ecex_switch_buffer(ed, payload); +} + +int ecex_list_buffers(ecex_t *ed) { + if (!ed) return ECEX_ERR; + + buffer_t *buf = ecex_find_buffer(ed, "*buffers*"); + if (!buf) { + buf = ecex_create_interactive_buffer(ed, "*buffers*"); + if (!buf) return ECEX_ERR; + } + + buffer_set_interactive(buf, 1); + if (buffer_clear(buf) != ECEX_OK) return ECEX_ERR; + buffer_set_interactive(buf, 1); + + buffer_append(buf, "Buffers:\n"); + buffer_append(buf, "Press ENTER on a buffer to switch to it.\n\n"); + + for (size_t i = 0; i < ed->buffer_count; i++) { + buffer_t *b = ed->buffers[i]; + char line[1024]; + + snprintf(line, + sizeof(line), + "%s %s %-24s %-18s size:%zu%s%s", + b == ed->current_buffer ? "*" : " ", + b->modified ? "+" : " ", + b->name ? b->name : "(unnamed)", + ecex_buffer_major_mode_name(ed, b), + b->len, + b->path ? " " : "", + b->path ? b->path : ""); + + if (ecex_interactive_append_line(ed, + buf, + line, + ecex_interactive_switch_buffer_action, + b->name, + NULL) != ECEX_OK) { + return ECEX_ERR; + } + } + + buf->point = 0; + buf->modified = 0; + return ecex_switch_buffer(ed, "*buffers*"); +} + +buffer_t *ecex_create_interactive_buffer(ecex_t *ed, const char *name) { + if (!ed || !name) return NULL; + + buffer_t *buffer = ecex_find_buffer(ed, name); + if (!buffer) { + buffer = ecex_create_buffer(ed, name, NULL, 0); + if (!buffer) return NULL; + } + + buffer_set_interactive(buffer, 1); + if (buffer->major_mode == 0) ecex_buffer_set_major_mode_by_name(ed, buffer, "special-mode"); + return buffer; +} + +int ecex_interactive_append_line(ecex_t *ed, + buffer_t *buffer, + const char *text, + ecex_interactive_line_fn fn, + const char *payload, + void *userdata) { + (void)ed; + + if (!buffer || !text) return ECEX_ERR; + + size_t line = buffer_line_count(buffer); + if (line > 0) line--; + + if (fn) { + if (buffer_add_interactive_action(buffer, line, fn, payload, userdata) != ECEX_OK) { + return ECEX_ERR; + } + } + + if (buffer_append(buffer, text) != ECEX_OK) return ECEX_ERR; + if (buffer_append(buffer, "\n") != ECEX_OK) return ECEX_ERR; + + buffer_set_interactive(buffer, 1); + return ECEX_OK; +} + +int ecex_interactive_activate_current_line(ecex_t *ed) { + if (!ed) return ECEX_ERR; + + buffer_t *buffer = ecex_current_buffer(ed); + if (!buffer || !buffer_is_interactive(buffer)) return ECEX_ERR; + + size_t line = buffer_current_line_number(buffer); + if (line > 0) line--; + + ecex_interactive_line_action_t *action = + buffer_interactive_action_at_line(buffer, line); + + if (!action || !action->fn) return ECEX_ERR; + return action->fn(ed, buffer, line, action->payload, action->userdata); +} + +static const char *ecex_basename(const char *path) { + if (!path || !path[0]) return "untitled"; + + const char *last_slash = strrchr(path, '/'); + if (last_slash && last_slash[1]) return last_slash + 1; + if (last_slash && last_slash == path) return "/"; + return path; +} + +static int ecex_buffer_path_equal(buffer_t *buffer, const char *path) { + return buffer && buffer->path && path && strcmp(buffer->path, path) == 0; +} + +int ecex_find_file(ecex_t *ed, const char *path) { + if (!ed || !path || !path[0]) return ECEX_ERR; + + for (size_t i = 0; i < ed->buffer_count; i++) { + if (ecex_buffer_path_equal(ed->buffers[i], path)) { + return ecex_set_current_buffer_index(ed, i); + } + } + + const char *name = ecex_basename(path); + buffer_t *buf = ecex_create_buffer(ed, name, NULL, 0); + if (!buf) return ECEX_ERR; + + if (ecex_file_exists(path)) { + if (buffer_load_file(buf, path) != ECEX_OK) { + ecex_kill_buffer(ed, buf->name); + return ECEX_ERR; + } + } else { + char *new_path = ecex_strdup(path); + if (!new_path) { + ecex_kill_buffer(ed, buf->name); + return ECEX_ERR; + } + + free(buf->path); + buf->path = new_path; + buf->modified = 0; + } + + ecex_auto_set_major_mode(ed, buf); + return ecex_set_current_buffer_index(ed, ed->buffer_count ? ed->buffer_count - 1 : 0); +} + +int ecex_save_current_buffer(ecex_t *ed) { + buffer_t *buf = ecex_current_buffer(ed); + if (!buf) return ECEX_ERR; + return buffer_save(buf); +} + +int ecex_write_current_buffer(ecex_t *ed, const char *path) { + buffer_t *buf = ecex_current_buffer(ed); + if (!buf || !path || !path[0]) return ECEX_ERR; + int result = buffer_save_as(buf, path); + if (result == ECEX_OK) ecex_auto_set_major_mode(ed, buf); + return result; +} + +void ecex_request_prompt(ecex_t *ed, + ecex_prompt_request_t request, + const char *message) { + if (!ed) return; + + ed->prompt_request = request; + snprintf(ed->prompt_message, + sizeof(ed->prompt_message), + "%s", + message ? message : ""); +} + +void ecex_clear_prompt_request(ecex_t *ed) { + if (!ed) return; + ed->prompt_request = ECEX_PROMPT_NONE; + ed->prompt_message[0] = '\0'; +} + +static int ecex_fuzzy_score(const char *candidate, const char *query) { + if (!candidate || !query) return -1; + if (query[0] == '\0') return 0; + + int score = 0; + int consecutive = 0; + int last_match = -1; + size_t ci = 0; + size_t qi = 0; + + while (candidate[ci] && query[qi]) { + char c = candidate[ci]; + char q = query[qi]; + + if (c >= 'A' && c <= 'Z') c = (char)(c - 'A' + 'a'); + if (q >= 'A' && q <= 'Z') q = (char)(q - 'A' + 'a'); + + if (c == q) { + score += 10; + + if ((int)ci == last_match + 1) { + consecutive++; + score += 5 * consecutive; + } else { + consecutive = 0; + } + + if (ci == 0) score += 20; + if (ci > 0 && (candidate[ci - 1] == '-' || + candidate[ci - 1] == '_' || + candidate[ci - 1] == ' ')) { + score += 15; + } + + last_match = (int)ci; + qi++; + } + + ci++; + } + + if (query[qi] != '\0') return -1; + + score -= (int)strlen(candidate); + if (strncmp(candidate, query, strlen(query)) == 0) score += 100; + return score; +} + +const char *ecex_complete_command(ecex_t *ed, const char *query) { + if (!ed || !query || !ed->theme.completion_enabled) return NULL; + + const char *best = NULL; + int best_score = -1; + + for (size_t i = 0; i < ed->command_count; i++) { + const char *name = ed->commands[i].name; + int score = ecex_fuzzy_score(name, query); + + if (score > best_score) { + best_score = score; + best = name; + } + } + + return best; +} + + +static int ecex_set_owned_string(char **slot, const char *value) { + if (!slot) return ECEX_ERR; + char *copy = NULL; + if (value && value[0]) { + copy = ecex_strdup(value); + if (!copy) return ECEX_ERR; + } + free(*slot); + *slot = copy; + return ECEX_OK; +} + +static int ecex_parse_file_line(const char *text, char *path, size_t path_size, size_t *out_line) { + if (!text || !path || path_size == 0 || !out_line) return ECEX_ERR; + const char *colon = strchr(text, ':'); + if (!colon || colon == text) return ECEX_ERR; + char *end = NULL; + long line = strtol(colon + 1, &end, 10); + if (line <= 0 || end == colon + 1) return ECEX_ERR; + size_t len = (size_t)(colon - text); + if (len >= path_size) len = path_size - 1; + memcpy(path, text, len); + path[len] = '\0'; + *out_line = (size_t)line; + return ECEX_OK; +} + +static int ecex_goto_file_line_action(ecex_t *ed, buffer_t *buffer, size_t line, const char *payload, void *userdata) { + (void)buffer; + (void)line; + (void)userdata; + if (!ed || !payload) return ECEX_ERR; + char path[1024]; + size_t target_line = 1; + if (ecex_parse_file_line(payload, path, sizeof(path), &target_line) != ECEX_OK) return ECEX_ERR; + if (ecex_find_file(ed, path) != ECEX_OK) return ECEX_ERR; + buffer_t *buf = ecex_current_buffer(ed); + if (!buf) return ECEX_ERR; + size_t pos = 0; + for (size_t l = 1; l < target_line && pos < buf->len; pos++) { + if (buf->data[pos] == '\n') l++; + } + buffer_set_point(buf, pos); + return ECEX_OK; +} + +static int ecex_append_shell_output(ecex_t *ed, const char *name, const char *command) { + if (!ed || !name || !command || !command[0]) return ECEX_ERR; + buffer_t *buf = ecex_create_interactive_buffer(ed, name); + if (!buf) return ECEX_ERR; + buffer_set_interactive(buf, 1); + if (buffer_clear(buf) != ECEX_OK) return ECEX_ERR; + buffer_set_interactive(buf, 1); + ecex_buffer_set_major_mode_by_name(ed, buf, "special-mode"); + + char header[2048]; + snprintf(header, sizeof(header), "%s\n\nKeys: g/r rerun, n/p next/previous result, RET jump, q quit.\n\n", command); + buffer_append(buf, header); + + char shell_command[4096]; + snprintf(shell_command, sizeof(shell_command), "%s 2>&1", command); + FILE *pipe = popen(shell_command, "r"); + if (!pipe) { + buffer_append(buf, "Failed to start command.\n"); + return ecex_switch_buffer(ed, name); + } + + char line[4096]; + while (fgets(line, sizeof(line), pipe)) { + size_t len = strlen(line); + while (len > 0 && (line[len - 1] == '\n' || line[len - 1] == '\r')) line[--len] = '\0'; + char path[1024]; + size_t target = 0; + ecex_interactive_line_fn fn = NULL; + char payload[1200]; + payload[0] = '\0'; + if (ecex_parse_file_line(line, path, sizeof(path), &target) == ECEX_OK) { + snprintf(payload, sizeof(payload), "%s:%zu", path, target); + fn = ecex_goto_file_line_action; + } + ecex_interactive_append_line(ed, buf, line, fn, payload[0] ? payload : NULL, NULL); + } + + int status = pclose(pipe); + char footer[128]; + snprintf(footer, sizeof(footer), "\n[process exited: %d]\n", status); + buffer_append(buf, footer); + buf->point = 0; + buf->modified = 0; + return ecex_switch_buffer(ed, name); +} + +int ecex_compile(ecex_t *ed, const char *command) { + if (!ed || !command || !command[0]) return ECEX_ERR; + if (ecex_set_owned_string(&ed->last_compile_command, command) != ECEX_OK) return ECEX_ERR; + return ecex_append_shell_output(ed, "*compilation*", command); +} + +int ecex_grep(ecex_t *ed, const char *command) { + if (!ed || !command || !command[0]) return ECEX_ERR; + if (ecex_set_owned_string(&ed->last_grep_command, command) != ECEX_OK) return ECEX_ERR; + return ecex_append_shell_output(ed, "*grep*", command); +} + +int ecex_rerun_compile(ecex_t *ed) { + if (!ed || !ed->last_compile_command) return ECEX_ERR; + return ecex_append_shell_output(ed, "*compilation*", ed->last_compile_command); +} + +int ecex_rerun_grep(ecex_t *ed) { + if (!ed || !ed->last_grep_command) return ECEX_ERR; + return ecex_append_shell_output(ed, "*grep*", ed->last_grep_command); +} + +int ecex_next_interactive_action(ecex_t *ed) { + buffer_t *buf = ecex_current_buffer(ed); + if (!buf || !buffer_is_interactive(buf) || buf->interactive_action_count == 0) return ECEX_ERR; + size_t current = buffer_current_line_number(buf); + if (current > 0) current--; + size_t best = (size_t)-1; + for (size_t i = 0; i < buf->interactive_action_count; i++) { + size_t line = buf->interactive_actions[i].line; + if (line > current && (best == (size_t)-1 || line < best)) best = line; + } + if (best == (size_t)-1) best = buf->interactive_actions[0].line; + size_t pos = 0; + for (size_t l = 0; l < best && pos < buf->len; pos++) if (buf->data[pos] == '\n') l++; + buffer_set_point(buf, pos); + return ECEX_OK; +} + +int ecex_previous_interactive_action(ecex_t *ed) { + buffer_t *buf = ecex_current_buffer(ed); + if (!buf || !buffer_is_interactive(buf) || buf->interactive_action_count == 0) return ECEX_ERR; + size_t current = buffer_current_line_number(buf); + if (current > 0) current--; + size_t best = (size_t)-1; + for (size_t i = 0; i < buf->interactive_action_count; i++) { + size_t line = buf->interactive_actions[i].line; + if (line < current && (best == (size_t)-1 || line > best)) best = line; + } + if (best == (size_t)-1) best = buf->interactive_actions[buf->interactive_action_count - 1].line; + size_t pos = 0; + for (size_t l = 0; l < best && pos < buf->len; pos++) if (buf->data[pos] == '\n') l++; + buffer_set_point(buf, pos); + return ECEX_OK; +} + +static int ecex_region_lines(buffer_t *buf, size_t *out_start, size_t *out_end) { + if (!buf || !buffer_has_selection(buf)) return ECEX_ERR; + size_t start = 0, end = 0; + buffer_selection_range(buf, &start, &end); + start = buffer_line_start_at(buf, start); + end = buffer_line_end_at(buf, end); + if (end < buf->len) end++; + if (out_start) *out_start = start; + if (out_end) *out_end = end; + return ECEX_OK; +} + +int ecex_comment_region(ecex_t *ed) { + buffer_t *buf = ecex_current_buffer(ed); + size_t start = 0, end = 0; + if (!buf || ecex_region_lines(buf, &start, &end) != ECEX_OK) return ECEX_ERR; + size_t pos = start; + while (pos <= end && pos <= buf->len) { + if (buffer_insert_at(buf, pos, "// ") != ECEX_OK) return ECEX_ERR; + pos += 3; + end += 3; + size_t eol = buffer_line_end_at(buf, pos); + if (eol >= end || eol >= buf->len) break; + pos = eol + 1; + } + return ECEX_OK; +} + +int ecex_uncomment_region(ecex_t *ed) { + buffer_t *buf = ecex_current_buffer(ed); + size_t start = 0, end = 0; + if (!buf || ecex_region_lines(buf, &start, &end) != ECEX_OK) return ECEX_ERR; + size_t pos = start; + while (pos < end && pos < buf->len) { + if (pos + 2 <= buf->len && memcmp(buf->data + pos, "//", 2) == 0) { + size_t del = (pos + 3 <= buf->len && buf->data[pos + 2] == ' ') ? 3 : 2; + if (buffer_delete_range(buf, pos, pos + del) != ECEX_OK) return ECEX_ERR; + end = end > del ? end - del : 0; + } + size_t eol = buffer_line_end_at(buf, pos); + if (eol >= end || eol >= buf->len) break; + pos = eol + 1; + } + return ECEX_OK; +} + +int ecex_set_font(ecex_t *ed, const char *path) { + if (!ed || !path) return ECEX_ERR; + + char *copy = ecex_strdup(path); + if (!copy) return ECEX_ERR; + + free(ed->theme.font_path); + ed->theme.font_path = copy; + return ECEX_OK; +} + +float ecex_get_font_size(ecex_t *ed) { + if (!ed) return 0.0f; + return ed->theme.font_size; +} + +int ecex_set_font_size(ecex_t *ed, float size) { + if (!ed) return ECEX_ERR; + ed->theme.font_size = ECEX_CLAMP(size, 8.0f, 96.0f); + return ECEX_OK; +} + +int ecex_adjust_font_size(ecex_t *ed, float delta) { + if (!ed) return ECEX_ERR; + return ecex_set_font_size(ed, ed->theme.font_size + delta); +} + +void ecex_set_bg_color(ecex_t *ed, float r, float g, float b) { if (ed) ed->theme.bg = ecex_color(r, g, b); } +void ecex_set_fg_color(ecex_t *ed, float r, float g, float b) { if (ed) ed->theme.fg = ecex_color(r, g, b); } +void ecex_set_status_bg_color(ecex_t *ed, float r, float g, float b) { if (ed) ed->theme.status_bg = ecex_color(r, g, b); } +void ecex_set_status_fg_color(ecex_t *ed, float r, float g, float b) { if (ed) ed->theme.status_fg = ecex_color(r, g, b); } +void ecex_set_status_border_color(ecex_t *ed, float r, float g, float b) { if (ed) ed->theme.status_border = ecex_color(r, g, b); } +void ecex_set_cursor_color(ecex_t *ed, float r, float g, float b) { if (ed) ed->theme.cursor = ecex_color(r, g, b); } +void ecex_set_region_bg_color(ecex_t *ed, float r, float g, float b) { if (ed) ed->theme.region_bg = ecex_color(r, g, b); } +void ecex_set_minibuffer_bg_color(ecex_t *ed, float r, float g, float b) { if (ed) ed->theme.minibuffer_bg = ecex_color(r, g, b); } +void ecex_set_minibuffer_fg_color(ecex_t *ed, float r, float g, float b) { if (ed) ed->theme.minibuffer_fg = ecex_color(r, g, b); } +void ecex_set_completion_fg_color(ecex_t *ed, float r, float g, float b) { if (ed) ed->theme.completion_fg = ecex_color(r, g, b); } +void ecex_set_completion_enabled(ecex_t *ed, int enabled) { if (ed) ed->theme.completion_enabled = enabled ? 1 : 0; } +void ecex_set_interactive_highlight_bg_color(ecex_t *ed, float r, float g, float b) { if (ed) ed->theme.interactive_highlight_bg = ecex_color(r, g, b); } +void ecex_set_interactive_highlight_fg_color(ecex_t *ed, float r, float g, float b) { if (ed) ed->theme.interactive_highlight_fg = ecex_color(r, g, b); } +void ecex_set_current_line_bg_color(ecex_t *ed, float r, float g, float b) { if (ed) ed->theme.current_line_bg = ecex_color(r, g, b); } +void ecex_set_search_bg_color(ecex_t *ed, float r, float g, float b) { if (ed) ed->theme.search_bg = ecex_color(r, g, b); } +void ecex_set_line_numbers_enabled(ecex_t *ed, int enabled) { if (ed) ed->theme.line_numbers_enabled = enabled ? 1 : 0; } +void ecex_set_current_line_enabled(ecex_t *ed, int enabled) { if (ed) ed->theme.current_line_enabled = enabled ? 1 : 0; } diff --git a/src/eval.c b/src/eval.c new file mode 100644 index 0000000..316d6d8 --- /dev/null +++ b/src/eval.c @@ -0,0 +1,482 @@ +#define _POSIX_C_SOURCE 200809L + +#include "eval.h" + +#include "buffers.h" +#include "ccdjit.h" +#include "common.h" +#include "config.h" +#include "ecex.h" +#include "util.h" + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> + +static ecex_t *g_eval_editor = NULL; + +static buffer_t *eval_output_buffer(ecex_t *ed) { + if (!ed) return NULL; + + buffer_t *out = ecex_create_interactive_buffer(ed, "*eval-output*"); + if (out) { + ecex_buffer_set_major_mode_by_name(ed, out, "eval-output-mode"); + } + + return out; +} + +static void eval_append_diag(buffer_t *out, ccdjit_context *ctx) { + if (!out || !ctx) return; + + const ccdjit_diagnostic *diag = ccdjit_context_last_error(ctx); + if (!diag) { + buffer_append(out, "ccdjit: unknown error\n"); + return; + } + + char line[1024]; + snprintf(line, + sizeof(line), + "ccdjit error [%s] %s:%d:%d: %s\n", + diag->phase ? diag->phase : "?", + diag->filename ? diag->filename : "<input>", + diag->line, + diag->column, + diag->message ? diag->message : "(no message)"); + buffer_append(out, line); + + if (diag->source_line) { + buffer_append(out, diag->source_line); + buffer_append(out, "\n"); + } + + if (diag->caret_line) { + buffer_append(out, diag->caret_line); + buffer_append(out, "\n"); + } +} + +typedef struct eval_capture { + FILE *file; + int saved_stdout; + int saved_stderr; + int active; +} eval_capture_t; + +static void eval_capture_init(eval_capture_t *capture) { + if (!capture) return; + + capture->file = NULL; + capture->saved_stdout = -1; + capture->saved_stderr = -1; + capture->active = 0; +} + +static int eval_capture_begin(eval_capture_t *capture, buffer_t *out) { + if (!capture) return ECEX_ERR; + + eval_capture_init(capture); + + capture->file = tmpfile(); + if (!capture->file) { + if (out) buffer_append(out, "warning: failed to create stdout capture file\n"); + return ECEX_ERR; + } + + int capture_fd = fileno(capture->file); + if (capture_fd < 0) { + if (out) buffer_append(out, "warning: failed to get stdout capture fd\n"); + fclose(capture->file); + eval_capture_init(capture); + return ECEX_ERR; + } + + fflush(NULL); + + capture->saved_stdout = dup(STDOUT_FILENO); + capture->saved_stderr = dup(STDERR_FILENO); + + if (capture->saved_stdout < 0 || capture->saved_stderr < 0) { + if (out) buffer_append(out, "warning: failed to save stdout/stderr\n"); + + if (capture->saved_stdout >= 0) close(capture->saved_stdout); + if (capture->saved_stderr >= 0) close(capture->saved_stderr); + fclose(capture->file); + eval_capture_init(capture); + return ECEX_ERR; + } + + if (dup2(capture_fd, STDOUT_FILENO) < 0 || + dup2(capture_fd, STDERR_FILENO) < 0) { + if (out) buffer_append(out, "warning: failed to redirect stdout/stderr\n"); + + dup2(capture->saved_stdout, STDOUT_FILENO); + dup2(capture->saved_stderr, STDERR_FILENO); + close(capture->saved_stdout); + close(capture->saved_stderr); + fclose(capture->file); + eval_capture_init(capture); + return ECEX_ERR; + } + + capture->active = 1; + return ECEX_OK; +} + +static void eval_capture_restore(eval_capture_t *capture) { + if (!capture || !capture->active) return; + + fflush(NULL); + + if (capture->saved_stdout >= 0) { + dup2(capture->saved_stdout, STDOUT_FILENO); + close(capture->saved_stdout); + capture->saved_stdout = -1; + } + + if (capture->saved_stderr >= 0) { + dup2(capture->saved_stderr, STDERR_FILENO); + close(capture->saved_stderr); + capture->saved_stderr = -1; + } + + capture->active = 0; +} + +static void eval_capture_append_output(eval_capture_t *capture, buffer_t *out) { + if (!capture || !capture->file || !out) return; + + if (fseek(capture->file, 0, SEEK_END) != 0) { + return; + } + + long size = ftell(capture->file); + if (size <= 0) { + return; + } + + if (fseek(capture->file, 0, SEEK_SET) != 0) { + return; + } + + buffer_append(out, "stdout/stderr:\n"); + + char chunk[4096]; + size_t n = 0; + + while ((n = fread(chunk, 1, sizeof(chunk), capture->file)) > 0) { + size_t old_len = out->len; + + if (buffer_reserve(out, out->len + n + 1) != ECEX_OK) { + buffer_append(out, "\n[output truncated: allocation failed]\n"); + return; + } + + memcpy(out->data + old_len, chunk, n); + out->len += n; + out->data[out->len] = '\0'; + out->point = out->len; + } + + if (out->len > 0 && out->data[out->len - 1] != '\n') { + buffer_append(out, "\n"); + } + + buffer_append(out, "\n"); +} + +static void eval_capture_finish(eval_capture_t *capture, buffer_t *out) { + if (!capture) return; + + eval_capture_restore(capture); + eval_capture_append_output(capture, out); + + if (capture->file) { + fclose(capture->file); + } + + eval_capture_init(capture); +} + +static int source_has_main(const char *source) { + if (!source) return 0; + + return strstr(source, "main(") != NULL || + strstr(source, "main (") != NULL; +} + +static char *make_eval_source(const char *source, int wrap_as_statements) { + if (!source) return NULL; + + const char *prefix = + "#include \"ecex.h\"\n" + "#include \"buffers.h\"\n" + "extern ecex_t *__ecex_eval_editor;\n" + "#define ECEX_ED (__ecex_eval_editor)\n" + "\n"; + + const char *wrapper_open = + "int main(int argc, char **argv) {\n" + " (void)argc;\n" + " (void)argv;\n" + " ecex_t *ed = __ecex_eval_editor;\n" + " (void)ed;\n"; + + const char *wrapper_close = + "\n" + " return 0;\n" + "}\n"; + + int do_wrap = wrap_as_statements || !source_has_main(source); + + size_t prefix_len = strlen(prefix); + size_t source_len = strlen(source); + size_t open_len = do_wrap ? strlen(wrapper_open) : 0; + size_t close_len = do_wrap ? strlen(wrapper_close) : 0; + + char *combined = malloc(prefix_len + open_len + source_len + close_len + 2); + if (!combined) return NULL; + + char *p = combined; + memcpy(p, prefix, prefix_len); + p += prefix_len; + + if (do_wrap) { + memcpy(p, wrapper_open, open_len); + p += open_len; + } + + memcpy(p, source, source_len); + p += source_len; + + if (do_wrap) { + if (source_len == 0 || source[source_len - 1] != '\n') { + *p++ = '\n'; + } + memcpy(p, wrapper_close, close_len); + p += close_len; + } + + *p = '\0'; + return combined; +} + +static int remember_last_eval(ecex_t *ed, + const char *source, + const char *filename, + int wrap_as_statements) { + if (!ed || !source) return ECEX_ERR; + + char *source_copy = ecex_strdup(source); + char *filename_copy = ecex_strdup(filename ? filename : "<eval>"); + if (!source_copy || !filename_copy) { + free(source_copy); + free(filename_copy); + return ECEX_ERR; + } + + free(ed->last_eval_source); + free(ed->last_eval_filename); + ed->last_eval_source = source_copy; + ed->last_eval_filename = filename_copy; + ed->last_eval_wrap_as_statements = wrap_as_statements; + return ECEX_OK; +} + +int ecex_eval_source(ecex_t *ed, + const char *source, + const char *filename, + int wrap_as_statements) { + if (!ed || !source) return ECEX_ERR; + + remember_last_eval(ed, source, filename, wrap_as_statements); + + buffer_t *out = eval_output_buffer(ed); + if (!out) return ECEX_ERR; + + buffer_clear(out); + buffer_set_interactive(out, 1); + ecex_buffer_set_major_mode_by_name(ed, out, "eval-output-mode"); + buffer_append(out, "Eval output (g: re-eval, q: quit window, ENTER: follow line if available)\n"); + buffer_append(out, "────────────────────────────────────────────────────────────────\n\n"); + buffer_append(out, "Eval: "); + buffer_append(out, filename ? filename : "<eval>"); + buffer_append(out, "\n\n"); + + char *eval_source = make_eval_source(source, wrap_as_statements); + if (!eval_source) { + buffer_append(out, "failed to allocate eval source\n"); + ecex_switch_buffer(ed, "*eval-output*"); + return ECEX_ERR; + } + + ccdjit_context *ctx = ccdjit_context_new(NULL); + if (!ctx) { + buffer_append(out, "failed to create ccdjit context\n"); + free(eval_source); + ecex_switch_buffer(ed, "*eval-output*"); + return ECEX_ERR; + } + + if (ecex_add_ccdjit_include_paths(ctx) != ECEX_OK || + ecex_register_host_symbols(ctx) != ECEX_OK || + ccdjit_context_register_symbol(ctx, + "__ecex_eval_editor", + (void *)&g_eval_editor) != 0) { + buffer_append(out, "failed to prepare eval context\n"); + eval_append_diag(out, ctx); + ccdjit_context_free(ctx); + free(eval_source); + ecex_switch_buffer(ed, "*eval-output*"); + return ECEX_ERR; + } + + g_eval_editor = ed; + + ccdjit_module *module = NULL; + if (ccdjit_compile_string(ctx, + eval_source, + filename ? filename : "<eval>", + &module) != 0) { + buffer_append(out, "compile failed\n\n"); + eval_append_diag(out, ctx); + g_eval_editor = NULL; + ccdjit_context_free(ctx); + free(eval_source); + ecex_switch_buffer(ed, "*eval-output*"); + return ECEX_ERR; + } + + int result = 0; + eval_capture_t capture; + int capture_enabled = (eval_capture_begin(&capture, out) == ECEX_OK); + int runtime_status = ccdjit_module_call_main(module, 0, NULL, &result); + + if (capture_enabled) { + eval_capture_finish(&capture, out); + } + + if (runtime_status != 0) { + buffer_append(out, "runtime failed\n\n"); + eval_append_diag(out, ctx); + ccdjit_module_free(module); + g_eval_editor = NULL; + ccdjit_context_free(ctx); + free(eval_source); + ecex_switch_buffer(ed, "*eval-output*"); + return ECEX_ERR; + } + + char line[128]; + snprintf(line, sizeof(line), "ok, result = %d\n", result); + buffer_append(out, line); + + /* + * Keep successful eval modules alive. This makes eval useful for live + * customization: code evaluated from a buffer may register commands whose + * function pointers remain valid after eval returns. + */ + if (ecex_keep_jit_module(ed, module) != ECEX_OK) { + buffer_append(out, "failed to keep eval module alive\n"); + ccdjit_module_free(module); + g_eval_editor = NULL; + ccdjit_context_free(ctx); + free(eval_source); + ecex_switch_buffer(ed, "*eval-output*"); + return ECEX_ERR; + } + + g_eval_editor = NULL; + ccdjit_context_free(ctx); + free(eval_source); + + out->modified = 0; + out->point = 0; + ecex_switch_buffer(ed, "*eval-output*"); + return ECEX_OK; +} + +int ecex_eval_current_buffer(ecex_t *ed) { + buffer_t *buf = ecex_current_buffer(ed); + if (!buf || !buf->data) return ECEX_ERR; + + return ecex_eval_source(ed, + buf->data, + buf->path ? buf->path : buf->name, + 0); +} + +int ecex_eval_current_line(ecex_t *ed) { + buffer_t *buf = ecex_current_buffer(ed); + if (!buf) return ECEX_ERR; + + char *line = buffer_current_line_copy(buf); + if (!line) return ECEX_ERR; + + int result = ecex_eval_source(ed, line, "<current-line>", 1); + free(line); + return result; +} + + +int ecex_eval_current_region(ecex_t *ed) { + buffer_t *buf = ecex_current_buffer(ed); + if (!buf || !buffer_has_selection(buf)) return ECEX_ERR; + + size_t start = 0; + size_t end = 0; + buffer_selection_range(buf, &start, &end); + + char *region = buffer_substring(buf, start, end); + if (!region) return ECEX_ERR; + + int result = ecex_eval_source(ed, region, "<region>", 1); + free(region); + return result; +} + +int ecex_eval_file(ecex_t *ed, const char *path) { + if (!ed || !path || !path[0]) return ECEX_ERR; + + size_t size = 0; + char *source = ecex_read_entire_file(path, &size); + (void)size; + + if (!source) { + buffer_t *out = eval_output_buffer(ed); + if (out) { + buffer_clear(out); + buffer_append(out, "failed to read eval file: "); + buffer_append(out, path); + buffer_append(out, "\n"); + out->modified = 0; + ecex_switch_buffer(ed, "*eval-output*"); + } + return ECEX_ERR; + } + + int result = ecex_eval_source(ed, source, path, 0); + free(source); + return result; +} + +int ecex_eval_rerun_last(ecex_t *ed) { + if (!ed || !ed->last_eval_source) return ECEX_ERR; + + char *source = ecex_strdup(ed->last_eval_source); + char *filename = ecex_strdup(ed->last_eval_filename ? ed->last_eval_filename : "<eval>"); + int wrap = ed->last_eval_wrap_as_statements; + + if (!source || !filename) { + free(source); + free(filename); + return ECEX_ERR; + } + + int result = ecex_eval_source(ed, source, filename, wrap); + free(source); + free(filename); + return result; +} diff --git a/src/font.c b/src/font.c new file mode 100644 index 0000000..62985e4 --- /dev/null +++ b/src/font.c @@ -0,0 +1,258 @@ +#include "font.h" +#include "util.h" + +#define STB_TRUETYPE_IMPLEMENTATION +#include "stb_truetype.h" + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +const char *font_choose_path(const char *explicit_font_path) { + static char candidate[4096]; + + if (explicit_font_path && explicit_font_path[0]) { + return explicit_font_path; + } + + const char *env_font = getenv("ECEX_FONT"); + if (env_font && env_font[0]) { + return env_font; + } + + const char *guix_env = getenv("GUIX_ENVIRONMENT"); + if (guix_env && guix_env[0]) { + snprintf(candidate, sizeof(candidate), + "%s/share/fonts/truetype/DejaVuSansMono.ttf", guix_env); + if (ecex_file_exists(candidate)) return candidate; + + snprintf(candidate, sizeof(candidate), + "%s/share/fonts/truetype/dejavu/DejaVuSansMono.ttf", guix_env); + if (ecex_file_exists(candidate)) return candidate; + + snprintf(candidate, sizeof(candidate), + "%s/share/fonts/dejavu/DejaVuSansMono.ttf", guix_env); + if (ecex_file_exists(candidate)) return candidate; + } + + const char *home = getenv("HOME"); + if (home && home[0]) { + snprintf(candidate, sizeof(candidate), + "%s/.guix-profile/share/fonts/truetype/DejaVuSansMono.ttf", home); + if (ecex_file_exists(candidate)) return candidate; + + snprintf(candidate, sizeof(candidate), + "%s/.guix-profile/share/fonts/truetype/dejavu/DejaVuSansMono.ttf", home); + if (ecex_file_exists(candidate)) return candidate; + + snprintf(candidate, sizeof(candidate), + "%s/.guix-profile/share/fonts/dejavu/DejaVuSansMono.ttf", home); + if (ecex_file_exists(candidate)) return candidate; + } + + if (ecex_file_exists("/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf")) { + return "/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf"; + } + + if (ecex_file_exists("/usr/share/fonts/TTF/DejaVuSansMono.ttf")) { + return "/usr/share/fonts/TTF/DejaVuSansMono.ttf"; + } + + return NULL; +} + +int font_load(font_t *font, const char *path, float size_px) { + if (!font || !path) return -1; + + memset(font, 0, sizeof(*font)); + + size_t ttf_size = 0; + char *ttf_data = ecex_read_entire_file(path, &ttf_size); + if (!ttf_data) { + fprintf(stderr, "failed to read font: %s\n", path); + return -1; + } + + unsigned char *bitmap = calloc(1, ECEX_FONT_BITMAP_W * ECEX_FONT_BITMAP_H); + if (!bitmap) { + free(ttf_data); + return -1; + } + + stbtt_fontinfo info; + int ascent = 0; + int descent = 0; + int line_gap = 0; + + if (stbtt_InitFont(&info, (const unsigned char *)ttf_data, 0)) { + float scale = stbtt_ScaleForPixelHeight(&info, size_px); + stbtt_GetFontVMetrics(&info, &ascent, &descent, &line_gap); + + font->ascent_px = (float)ascent * scale; + font->descent_px = (float)(-descent) * scale; + font->line_gap_px = (float)line_gap * scale; + } + + if (font->ascent_px <= 0.0f) { + font->ascent_px = size_px * 0.80f; + } + + if (font->descent_px <= 0.0f) { + font->descent_px = size_px * 0.20f; + } + + if (font->line_gap_px < 0.0f) { + font->line_gap_px = 0.0f; + } + + int bake_result = stbtt_BakeFontBitmap( + (const unsigned char *)ttf_data, + 0, + size_px, + bitmap, + ECEX_FONT_BITMAP_W, + ECEX_FONT_BITMAP_H, + ECEX_FONT_FIRST_CHAR, + ECEX_FONT_CHAR_COUNT, + font->chars + ); + + free(ttf_data); + + if (bake_result <= 0) { + fprintf(stderr, "failed to bake font atlas from: %s\n", path); + free(bitmap); + return -1; + } + + glGenTextures(1, &font->texture); + glBindTexture(GL_TEXTURE_2D, font->texture); + + glTexImage2D(GL_TEXTURE_2D, + 0, + GL_ALPHA, + ECEX_FONT_BITMAP_W, + ECEX_FONT_BITMAP_H, + 0, + GL_ALPHA, + GL_UNSIGNED_BYTE, + bitmap); + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + + free(bitmap); + + font->size_px = size_px; + font->line_height = font->ascent_px + font->descent_px + font->line_gap_px; + + if (font->line_height < size_px * 1.15f) { + font->line_height = size_px * 1.15f; + } + + fprintf(stderr, "ecex: loaded font: %s\n", path); + return 0; +} + +void font_free(font_t *font) { + if (!font) return; + + if (font->texture) { + glDeleteTextures(1, &font->texture); + font->texture = 0; + } +} + +void draw_text(font_t *font, float x, float y, const char *text) { + if (!font || !font->texture || !text) return; + + glEnable(GL_TEXTURE_2D); + glBindTexture(GL_TEXTURE_2D, font->texture); + + glBegin(GL_QUADS); + + float start_x = x; + + for (const char *p = text; *p; p++) { + unsigned char c = (unsigned char)*p; + + if (c == '\n') { + x = start_x; + y += font->line_height; + continue; + } + + if (c == '\t') { + x += font->size_px * 4.0f; + continue; + } + + if (c < ECEX_FONT_FIRST_CHAR || + c >= ECEX_FONT_FIRST_CHAR + ECEX_FONT_CHAR_COUNT) { + c = '?'; + } + + stbtt_aligned_quad q; + + stbtt_GetBakedQuad(font->chars, + ECEX_FONT_BITMAP_W, + ECEX_FONT_BITMAP_H, + c - ECEX_FONT_FIRST_CHAR, + &x, + &y, + &q, + 1); + + glTexCoord2f(q.s0, q.t0); + glVertex2f(q.x0, q.y0); + + glTexCoord2f(q.s1, q.t0); + glVertex2f(q.x1, q.y0); + + glTexCoord2f(q.s1, q.t1); + glVertex2f(q.x1, q.y1); + + glTexCoord2f(q.s0, q.t1); + glVertex2f(q.x0, q.y1); + } + + glEnd(); + + glDisable(GL_TEXTURE_2D); +} + +float text_width(font_t *font, const char *text) { + if (!font || !text) return 0.0f; + + float x = 0.0f; + float y = 0.0f; + + for (const char *p = text; *p; p++) { + unsigned char c = (unsigned char)*p; + + if (c == '\n') break; + + if (c == '\t') { + x += font->size_px * 4.0f; + continue; + } + + if (c < ECEX_FONT_FIRST_CHAR || + c >= ECEX_FONT_FIRST_CHAR + ECEX_FONT_CHAR_COUNT) { + c = '?'; + } + + stbtt_aligned_quad q; + + stbtt_GetBakedQuad(font->chars, + ECEX_FONT_BITMAP_W, + ECEX_FONT_BITMAP_H, + c - ECEX_FONT_FIRST_CHAR, + &x, + &y, + &q, + 1); + } + + return x; +} diff --git a/src/main.c b/src/main.c new file mode 100644 index 0000000..9f388a0 --- /dev/null +++ b/src/main.c @@ -0,0 +1,164 @@ +#include "app.h" +#include "config.h" +#include "font.h" +#include "render.h" + +#include <GLFW/glfw3.h> + +#include <stdio.h> +#include <string.h> + +#define WINDOW_WIDTH 1000 +#define WINDOW_HEIGHT 700 + +static void print_usage(const char *argv0) { + fprintf(stderr, "usage:\n"); + fprintf(stderr, " %s [--config path/to/ecexrc.c] [--font path/to/font.ttf]\n", argv0); + fprintf(stderr, "\n"); + fprintf(stderr, "keys:\n"); + fprintf(stderr, " F1 opens M-x\n"); + fprintf(stderr, " Tab completes M-x command names\n"); + fprintf(stderr, " Alt+x opens M-x when the OS/window-manager allows it\n"); + fprintf(stderr, " C-x is reserved for prefix maps\n"); + fprintf(stderr, "\n"); + fprintf(stderr, "env:\n"); + fprintf(stderr, " ECEX_FONT=/path/to/font.ttf\n"); + fprintf(stderr, " ECEX_INCLUDE=/path/to/ecex/include\n"); +} + +static int parse_args(int argc, + char **argv, + const char **config_path, + const char **font_path_arg) { + *config_path = NULL; + *font_path_arg = NULL; + + for (int i = 1; i < argc; i++) { + if (strcmp(argv[i], "--config") == 0) { + if (i + 1 >= argc) { + print_usage(argv[0]); + return -1; + } + + *config_path = argv[++i]; + } else if (strcmp(argv[i], "--font") == 0) { + if (i + 1 >= argc) { + print_usage(argv[0]); + return -1; + } + + *font_path_arg = argv[++i]; + } else if (strcmp(argv[i], "--help") == 0 || + strcmp(argv[i], "-h") == 0) { + print_usage(argv[0]); + return 1; + } else { + *font_path_arg = argv[i]; + } + } + + return 0; +} + +static const char *select_font_path(ecex_t *ed, const char *font_path_arg) { + if (font_path_arg) return font_path_arg; + if (ed && ed->theme.font_path) return ed->theme.font_path; + return font_choose_path(NULL); +} + +int main(int argc, char **argv) { + const char *config_path = NULL; + const char *font_path_arg = NULL; + + int args_result = parse_args(argc, argv, &config_path, &font_path_arg); + if (args_result != 0) { + return args_result < 0 ? 1 : 0; + } + + ecex_t *ed = ecex_new(); + if (!ed) { + fprintf(stderr, "failed to create editor\n"); + return 1; + } + + if (config_path) { + if (ecex_load_c_config(ed, config_path) != 0) { + fprintf(stderr, "ecex: continuing without config\n"); + } + } + + if (!glfwInit()) { + fprintf(stderr, "failed to initialize GLFW\n"); + ecex_free(ed); + return 1; + } + + GLFWwindow *window = glfwCreateWindow( + WINDOW_WIDTH, + WINDOW_HEIGHT, + "ecex", + NULL, + NULL + ); + + if (!window) { + fprintf(stderr, "failed to create GLFW window\n"); + glfwTerminate(); + ecex_free(ed); + return 1; + } + + glfwMakeContextCurrent(window); + glfwSwapInterval(1); + + app_t app; + app_init(&app, ed); + app_set_window(&app, window); + + const char *font_path = select_font_path(ed, font_path_arg); + if (!font_path) { + fprintf(stderr, "ecex: could not find a font automatically\n"); + fprintf(stderr, "try:\n"); + fprintf(stderr, " export ECEX_FONT=/path/to/font.ttf\n"); + fprintf(stderr, " %s --font /path/to/font.ttf\n", argv[0]); + + glfwDestroyWindow(window); + glfwTerminate(); + ecex_free(ed); + return 1; + } + + if (font_load(&app.font, font_path, ed->theme.font_size) != 0) { + fprintf(stderr, "ecex: could not load font\n"); + fprintf(stderr, "try an explicit font path:\n"); + fprintf(stderr, " %s --font /path/to/font.ttf\n", argv[0]); + + glfwDestroyWindow(window); + glfwTerminate(); + ecex_free(ed); + return 1; + } + + snprintf(app.font_path, sizeof(app.font_path), "%s", font_path); + + app_install_callbacks(&app); + app_message(&app, "F1 for M-x. Tab completes commands."); + + while (!glfwWindowShouldClose(window) && !ed->should_quit) { + if (app.dirty) { + render(&app); + glfwSwapBuffers(window); + app.dirty = 0; + } + + glfwWaitEvents(); + } + + font_free(&app.font); + + glfwDestroyWindow(window); + glfwTerminate(); + + ecex_free(ed); + return 0; +} diff --git a/src/render.c b/src/render.c new file mode 100644 index 0000000..64a85f1 --- /dev/null +++ b/src/render.c @@ -0,0 +1,613 @@ +#include "render.h" + +#include "common.h" + +#include <GLFW/glfw3.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +/* + * All UI measurements are derived from the active font. draw_text() uses a + * baseline y coordinate, so render.c keeps both line-top and baseline values + * explicit. This avoids the old fixed 24/28/34 pixel constants drifting when + * font size changes. + */ +typedef struct view_rect { + float x; + float y; + float w; + float h; +} view_rect_t; + +typedef struct ui_metrics { + float pad_x; + float pad_y; + + float content_x; + float content_top; + float content_bottom_pad; + + float status_h; + float minibuffer_h; + + float cursor_w; + float cursor_h; +} ui_metrics_t; + +static float ecex_maxf(float a, float b) { + return a > b ? a : b; +} + +static ui_metrics_t ui_metrics(app_t *app) { + float size = app && app->font.size_px > 1.0f ? app->font.size_px : 16.0f; + float line_h = app && app->font.line_height > 1.0f + ? app->font.line_height + : size * 1.20f; + + ui_metrics_t m; + + m.pad_x = ecex_maxf(8.0f, size * 0.75f); + m.pad_y = ecex_maxf(4.0f, size * 0.35f); + + m.content_x = m.pad_x; + m.content_top = m.pad_y; + m.content_bottom_pad = m.pad_y; + + m.status_h = line_h + m.pad_y * 2.0f; + m.minibuffer_h = line_h + m.pad_y * 2.0f; + + m.cursor_w = ecex_maxf(2.0f, size * 0.10f); + m.cursor_h = ecex_maxf(1.0f, app ? app->font.ascent_px + app->font.descent_px : size); + + return m; +} + +static float line_baseline(app_t *app, float line_top) { + float ascent = app->font.ascent_px > 1.0f + ? app->font.ascent_px + : app->font.size_px * 0.80f; + + return line_top + ascent; +} + +static void setup_2d(int width, int height) { + glViewport(0, 0, width, height); + + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + glOrtho(0, width, height, 0, -1, 1); + + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); +} + +static void draw_rect(float x, float y, float w, float h) { + glBegin(GL_QUADS); + glVertex2f(x, y); + glVertex2f(x + w, y); + glVertex2f(x + w, y + h); + glVertex2f(x, y + h); + glEnd(); +} + +static float mono_cell_width(app_t *app) { + float w = text_width(&app->font, "M"); + return w > 1.0f ? w : app->font.size_px * 0.6f; +} + +static int minibuffer_visible(app_t *app) { + return app->mode == APP_MODE_MX || + app->mode == APP_MODE_PREFIX || + app->mode == APP_MODE_PROMPT || + app->mode == APP_MODE_ISEARCH || + app->message[0] != '\0'; +} + +static size_t visible_row_count_for_rect(app_t *app, view_rect_t r) { + ui_metrics_t m = ui_metrics(app); + float usable = r.h - m.content_top - m.content_bottom_pad; + + if (usable <= app->font.line_height || app->font.line_height <= 1.0f) { + return 1; + } + + size_t rows = (size_t)(usable / app->font.line_height); + return rows ? rows : 1; +} + +static float gutter_width(app_t *app, buffer_t *buf) { + if (!app || !app->ed || !buf || !app->ed->theme.line_numbers_enabled) return 0.0f; + char tmp[32]; + snprintf(tmp, sizeof(tmp), "%zu ", buffer_line_count(buf)); + return text_width(&app->font, tmp) + ui_metrics(app).pad_x * 0.5f; +} + +static size_t visible_col_count_for_rect(app_t *app, view_rect_t r) { + ui_metrics_t m = ui_metrics(app); + float cell = mono_cell_width(app); + buffer_t *buf = ecex_current_buffer(app->ed); + float width = r.w - m.content_x * 2.0f - gutter_width(app, buf); + + if (width <= cell) return 1; + return (size_t)(width / cell); +} + +static size_t offset_for_line(buffer_t *buf, size_t target_line) { + if (!buf || target_line == 0) return 0; + + size_t line = 0; + for (size_t i = 0; i < buf->len; i++) { + if (buf->data[i] == '\n') { + line++; + if (line == target_line) { + return i + 1; + } + } + } + + return buf->len; +} + +static void ensure_cursor_visible(app_t *app, buffer_t *buf, view_rect_t rect) { + if (!app || !buf) return; + + size_t rows = visible_row_count_for_rect(app, rect); + size_t cols = visible_col_count_for_rect(app, rect); + + size_t cursor_line = buffer_current_line_number(buf); + if (cursor_line > 0) cursor_line--; + + size_t cursor_col = buffer_current_column(buf); + + if (cursor_line < buf->scroll_line) { + buf->scroll_line = cursor_line; + } else if (cursor_line >= buf->scroll_line + rows) { + buf->scroll_line = cursor_line - rows + 1; + } + + if (cursor_col < buf->scroll_col) { + buf->scroll_col = cursor_col; + } else if (cursor_col >= buf->scroll_col + cols) { + buf->scroll_col = cursor_col - cols + 1; + } +} + +static void render_status_bar(app_t *app) { + buffer_t *buf = ecex_current_buffer(app->ed); + if (!buf) return; + + ui_metrics_t m = ui_metrics(app); + float y = (float)app->height - m.status_h; + float text_x = m.pad_x; + float text_y = line_baseline(app, y + m.pad_y); + + glDisable(GL_TEXTURE_2D); + + glColor3f(app->ed->theme.status_bg.r, + app->ed->theme.status_bg.g, + app->ed->theme.status_bg.b); + draw_rect(0.0f, y, (float)app->width, m.status_h); + + glColor3f(app->ed->theme.status_border.r, + app->ed->theme.status_border.g, + app->ed->theme.status_border.b); + draw_rect(0.0f, y, (float)app->width, 1.0f); + + char status[768]; + snprintf(status, + sizeof(status), + " %s%s %s line:%zu col:%zu top:%zu size:%zu buffers:%zu windows:%zu commands:%zu%s%s", + buf->name ? buf->name : "(unnamed)", + buf->modified ? " *" : "", + ecex_buffer_major_mode_name(app->ed, buf), + buffer_current_line_number(buf), + buffer_current_column(buf), + buf->scroll_line + 1, + buf->len, + app->ed->buffer_count, + ecex_window_count(app->ed), + app->ed->command_count, + buf->path ? " " : "", + buf->path ? buf->path : ""); + + glColor3f(app->ed->theme.status_fg.r, + app->ed->theme.status_fg.g, + app->ed->theme.status_fg.b); + draw_text(&app->font, text_x, text_y, status); +} + +static void render_command_completion(app_t *app, + const char *line, + float x, + float y) { + const char *completion = ecex_complete_command(app->ed, app->minibuffer); + if (!completion || !completion[0]) return; + + size_t input_len = strlen(app->minibuffer); + if (input_len == 0) return; + + float ghost_x = x + text_width(&app->font, line); + + glColor3f(app->ed->theme.completion_fg.r, + app->ed->theme.completion_fg.g, + app->ed->theme.completion_fg.b); + + if (strncmp(completion, app->minibuffer, input_len) == 0 && + completion[input_len] != '\0') { + draw_text(&app->font, ghost_x, y, completion + input_len); + } else if (strcmp(completion, app->minibuffer) != 0) { + char hint[ECEX_MINIBUFFER_SIZE + 16]; + snprintf(hint, sizeof(hint), " -> %s", completion); + draw_text(&app->font, ghost_x, y, hint); + } +} + +static void render_minibuffer(app_t *app) { + if (!minibuffer_visible(app)) { + return; + } + + ui_metrics_t m = ui_metrics(app); + float h = m.minibuffer_h; + float y = (float)app->height - m.status_h - h; + float text_x = m.pad_x; + float text_y = line_baseline(app, y + m.pad_y); + + glDisable(GL_TEXTURE_2D); + + glColor3f(app->ed->theme.minibuffer_bg.r, + app->ed->theme.minibuffer_bg.g, + app->ed->theme.minibuffer_bg.b); + draw_rect(0.0f, y, (float)app->width, h); + + glColor3f(app->ed->theme.minibuffer_fg.r, + app->ed->theme.minibuffer_fg.g, + app->ed->theme.minibuffer_fg.b); + + if (app->mode == APP_MODE_ISEARCH) { + char line[ECEX_MINIBUFFER_SIZE + 64]; + snprintf(line, + sizeof(line), + "%s%s%s", + app->isearch_backward ? "I-search backward: " : "I-search: ", + app->isearch_query, + app->isearch_has_match || app->isearch_len == 0 ? "" : " [failing]"); + draw_text(&app->font, text_x, text_y, line); + } else if (app->mode == APP_MODE_MX) { + char line[ECEX_MINIBUFFER_SIZE + 8]; + snprintf(line, sizeof(line), "M-x %s", app->minibuffer); + + draw_text(&app->font, text_x, text_y, line); + render_command_completion(app, line, text_x, text_y); + } else if (app->mode == APP_MODE_PROMPT) { + char line[1200]; + snprintf(line, + sizeof(line), + "%s%s", + app->prompt_label, + app->prompt_input); + draw_text(&app->font, text_x, text_y, line); + + if (app->prompt_completion_active && app->prompt_completion_count > 0) { + char hint[128]; + snprintf(hint, + sizeof(hint), + " [%zu/%zu]", + app->prompt_completion_index + 1, + app->prompt_completion_count); + + glColor3f(app->ed->theme.completion_fg.r, + app->ed->theme.completion_fg.g, + app->ed->theme.completion_fg.b); + draw_text(&app->font, + text_x + text_width(&app->font, line), + text_y, + hint); + + if (app->prompt_completion_preview_count > 0) { + float row_h = app->font.line_height; + float popup_pad = m.pad_y; + float popup_h = row_h * (float)app->prompt_completion_preview_count + popup_pad * 2.0f; + float popup_y = y - popup_h; + + glDisable(GL_TEXTURE_2D); + glColor3f(app->ed->theme.minibuffer_bg.r, + app->ed->theme.minibuffer_bg.g, + app->ed->theme.minibuffer_bg.b); + draw_rect(0.0f, popup_y, (float)app->width, popup_h); + + for (size_t i = 0; i < app->prompt_completion_preview_count; i++) { + size_t absolute = app->prompt_completion_preview_start + i; + char row[1100]; + snprintf(row, + sizeof(row), + "%c %s", + absolute == app->prompt_completion_index ? '>' : ' ', + app->prompt_completion_preview[i]); + + if (absolute == app->prompt_completion_index) { + glColor3f(app->ed->theme.minibuffer_fg.r, + app->ed->theme.minibuffer_fg.g, + app->ed->theme.minibuffer_fg.b); + } else { + glColor3f(app->ed->theme.completion_fg.r, + app->ed->theme.completion_fg.g, + app->ed->theme.completion_fg.b); + } + + draw_text(&app->font, + text_x, + line_baseline(app, popup_y + popup_pad + row_h * (float)i), + row); + } + } + } + } else if (app->mode == APP_MODE_PREFIX) { + char line[ECEX_PREFIX_SIZE + 8]; + snprintf(line, sizeof(line), "%s-", app->prefix); + draw_text(&app->font, text_x, text_y, line); + } else { + draw_text(&app->font, text_x, text_y, app->message); + } +} + +static int should_highlight_interactive_line(buffer_t *buf, size_t zero_based_line) { + if (!buf || !buffer_is_interactive(buf)) return 0; + + size_t current_line = buffer_current_line_number(buf); + if (current_line > 0) current_line--; + + return current_line == zero_based_line; +} + +static void set_editor_text_color(app_t *app, int highlighted) { + if (highlighted) { + glColor3f(app->ed->theme.interactive_highlight_fg.r, + app->ed->theme.interactive_highlight_fg.g, + app->ed->theme.interactive_highlight_fg.b); + } else { + glColor3f(app->ed->theme.fg.r, + app->ed->theme.fg.g, + app->ed->theme.fg.b); + } +} + +static float text_width_range(app_t *app, buffer_t *buf, size_t start, size_t end) { + char *text = buffer_substring(buf, start, end); + if (!text) return 0.0f; + + float width = text_width(&app->font, text); + free(text); + return width; +} + +static void draw_selection_for_line(app_t *app, + buffer_t *buf, + view_rect_t rect, + size_t visible_start, + size_t line_end, + float line_top) { + if (!buffer_has_selection(buf)) return; + + size_t sel_start = 0; + size_t sel_end = 0; + buffer_selection_range(buf, &sel_start, &sel_end); + + if (sel_end <= visible_start || sel_start > line_end) return; + + size_t draw_start = ECEX_MAX(sel_start, visible_start); + size_t draw_end = ECEX_MIN(sel_end, line_end); + + float x = rect.x + ui_metrics(app).content_x + gutter_width(app, buf) + text_width_range(app, buf, visible_start, draw_start); + float w = text_width_range(app, buf, draw_start, draw_end); + + /* If the selection contains only this line's newline, show a visible sliver + * at end-of-line instead of making the active region appear to vanish. */ + if (w < 1.0f && sel_end > line_end && draw_start == line_end) { + w = mono_cell_width(app) * 0.5f; + } + + if (w < 1.0f) return; + + glDisable(GL_TEXTURE_2D); + glColor3f(app->ed->theme.region_bg.r, + app->ed->theme.region_bg.g, + app->ed->theme.region_bg.b); + draw_rect(x, line_top, w, app->font.line_height); +} + +static void draw_buffer_line(app_t *app, + buffer_t *buf, + view_rect_t rect, + size_t zero_based_line, + size_t line_start, + size_t line_end, + float line_top) { + if (line_start > line_end) return; + + ui_metrics_t m = ui_metrics(app); + int highlighted = should_highlight_interactive_line(buf, zero_based_line); + size_t current_zero = buffer_current_line_number(buf); + if (current_zero > 0) current_zero--; + + if (app->ed->theme.current_line_enabled && current_zero == zero_based_line) { + glDisable(GL_TEXTURE_2D); + glColor3f(app->ed->theme.current_line_bg.r, + app->ed->theme.current_line_bg.g, + app->ed->theme.current_line_bg.b); + draw_rect(rect.x, line_top, rect.w, app->font.line_height); + } + + if (highlighted) { + glDisable(GL_TEXTURE_2D); + glColor3f(app->ed->theme.interactive_highlight_bg.r, + app->ed->theme.interactive_highlight_bg.g, + app->ed->theme.interactive_highlight_bg.b); + draw_rect(rect.x, + line_top, + rect.w, + app->font.line_height); + } + + size_t line_len = line_end - line_start; + size_t col = ECEX_MIN(buf->scroll_col, line_len); + size_t start = line_start + col; + + draw_selection_for_line(app, buf, rect, start, line_end, line_top); + + float gutter = gutter_width(app, buf); + if (gutter > 0.0f) { + char nbuf[32]; + snprintf(nbuf, sizeof(nbuf), "%zu", zero_based_line + 1); + glColor3f(app->ed->theme.completion_fg.r, + app->ed->theme.completion_fg.g, + app->ed->theme.completion_fg.b); + draw_text(&app->font, rect.x + m.pad_x * 0.5f, line_baseline(app, line_top), nbuf); + } + + char *line = buffer_substring(buf, start, line_end); + if (!line) return; + + set_editor_text_color(app, highlighted); + draw_text(&app->font, rect.x + m.content_x + gutter, line_baseline(app, line_top), line); + free(line); +} + +static void render_cursor(app_t *app, buffer_t *buf, view_rect_t rect) { + ui_metrics_t m = ui_metrics(app); + + size_t cursor_line = buffer_current_line_number(buf); + if (cursor_line > 0) cursor_line--; + + if (cursor_line < buf->scroll_line) return; + + size_t visible_row = cursor_line - buf->scroll_line; + if (visible_row >= visible_row_count_for_rect(app, rect)) return; + + size_t line_start = buffer_current_line_start(buf); + size_t cursor_col = buffer_current_column(buf); + + size_t visible_start = line_start + ECEX_MIN(buf->scroll_col, cursor_col); + char *prefix = buffer_substring(buf, visible_start, buf->point); + float x = rect.x + m.content_x + gutter_width(app, buf) + (prefix ? text_width(&app->font, prefix) : 0.0f); + float line_top = rect.y + m.content_top + (float)visible_row * app->font.line_height; + float cursor_top = line_top + (app->font.line_height - m.cursor_h) * 0.5f; + + free(prefix); + + glDisable(GL_TEXTURE_2D); + glColor3f(app->ed->theme.cursor.r, + app->ed->theme.cursor.g, + app->ed->theme.cursor.b); + draw_rect(x, cursor_top, m.cursor_w, m.cursor_h); +} + +static void draw_window_border(app_t *app, view_rect_t rect, int active) { + glDisable(GL_TEXTURE_2D); + + if (active) { + glColor3f(app->ed->theme.cursor.r, + app->ed->theme.cursor.g, + app->ed->theme.cursor.b); + } else { + glColor3f(app->ed->theme.status_border.r, + app->ed->theme.status_border.g, + app->ed->theme.status_border.b); + } + + draw_rect(rect.x, rect.y, rect.w, 1.0f); + draw_rect(rect.x, rect.y + rect.h - 1.0f, rect.w, 1.0f); + draw_rect(rect.x, rect.y, 1.0f, rect.h); + draw_rect(rect.x + rect.w - 1.0f, rect.y, 1.0f, rect.h); +} + +static void render_buffer_window(app_t *app, ecex_window_t *win, size_t index, float editor_h) { + if (!app || !win || !win->buffer) return; + + view_rect_t rect; + rect.x = win->x * (float)app->width; + rect.y = win->y * editor_h; + rect.w = win->w * (float)app->width; + rect.h = win->h * editor_h; + + if (rect.w < 2.0f || rect.h < 2.0f) return; + + buffer_t *buf = win->buffer; + ui_metrics_t m = ui_metrics(app); + + int sx = (int)rect.x; + int sy = app->height - (int)(rect.y + rect.h); + int sw = (int)rect.w; + int sh = (int)rect.h; + if (sw < 1 || sh < 1) return; + + glEnable(GL_SCISSOR_TEST); + glScissor(sx, sy, sw, sh); + + if (index == app->ed->current_window_index) { + ensure_cursor_visible(app, buf, rect); + } + + size_t rows = visible_row_count_for_rect(app, rect); + size_t pos = offset_for_line(buf, buf->scroll_line); + float line_top = rect.y + m.content_top; + + for (size_t row = 0; row < rows; row++) { + size_t line_start = pos; + size_t line_end = buffer_line_end_at(buf, line_start); + + draw_buffer_line(app, + buf, + rect, + buf->scroll_line + row, + line_start, + line_end, + line_top); + + if (line_end >= buf->len) break; + pos = line_end + 1; + line_top += app->font.line_height; + } + + if (index == app->ed->current_window_index) { + render_cursor(app, buf, rect); + } + + glDisable(GL_SCISSOR_TEST); + draw_window_border(app, rect, index == app->ed->current_window_index); +} + +static void render_windows(app_t *app) { + ui_metrics_t m = ui_metrics(app); + float editor_h = (float)app->height - m.status_h; + if (minibuffer_visible(app)) editor_h -= m.minibuffer_h; + if (editor_h < 1.0f) editor_h = 1.0f; + + if (app->ed->window_count == 0) return; + + for (size_t i = 0; i < app->ed->window_count; i++) { + render_buffer_window(app, &app->ed->windows[i], i, editor_h); + } +} + +void render(app_t *app) { + if (!app || !app->window || !app->ed) return; + + glfwGetFramebufferSize(app->window, &app->width, &app->height); + + setup_2d(app->width, app->height); + + glClearColor(app->ed->theme.bg.r, + app->ed->theme.bg.g, + app->ed->theme.bg.b, + 1.0f); + glClear(GL_COLOR_BUFFER_BIT); + + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + + render_windows(app); + render_minibuffer(app); + render_status_bar(app); +} diff --git a/src/util.c b/src/util.c new file mode 100644 index 0000000..feb3c0e --- /dev/null +++ b/src/util.c @@ -0,0 +1,71 @@ +#include "util.h" + +#include <stdio.h> +#include <stdlib.h> + +int ecex_file_exists(const char *path) { + if (!path || !path[0]) return 0; + + FILE *file = fopen(path, "rb"); + if (!file) return 0; + + fclose(file); + return 1; +} + +char *ecex_read_entire_file(const char *path, size_t *out_size) { + FILE *file = fopen(path, "rb"); + if (!file) return NULL; + + if (fseek(file, 0, SEEK_END) != 0) { + fclose(file); + return NULL; + } + + long size = ftell(file); + if (size < 0) { + fclose(file); + return NULL; + } + + rewind(file); + + char *data = malloc((size_t)size + 1); + if (!data) { + fclose(file); + return NULL; + } + + size_t read_count = fread(data, 1, (size_t)size, file); + fclose(file); + + if (read_count != (size_t)size) { + free(data); + return NULL; + } + + data[size] = '\0'; + + if (out_size) { + *out_size = (size_t)size; + } + + return data; +} + + +char *ecex_strdup(const char *s) { + if (!s) return NULL; + + size_t len = 0; + while (s[len]) len++; + + char *out = malloc(len + 1); + if (!out) return NULL; + + for (size_t i = 0; i <= len; i++) { + out[i] = s[i]; + } + + return out; +} |
