3 Commits

Author SHA1 Message Date
arthur 564292b03e linux lib compatibility 2026-06-03 09:20:00 +02:00
arthur cec92cacd1 working for starting screen 2026-06-02 19:06:51 +02:00
arthur 2738bc8042 popup and diagnose ui 2026-06-02 13:00:13 +02:00
27 changed files with 913 additions and 803 deletions
+1
View File
@@ -3,6 +3,7 @@
(define TAB-LENGTH 4)
(define QUIT-TIMES 1)
(define THEME "dark")
(define LSP #t)
;; PACKAGES
+1 -1
View File
@@ -7,6 +7,6 @@
void abAppend(struct abuf *ab, const char *s, int len);
void abFree(struct abuf *ab);
void abFree(const struct abuf *ab);
#endif // APPEND_BUFFER_H_
+8 -11
View File
@@ -7,23 +7,20 @@
#include "data.h"
void createContextBuffer(const int x, const int y, const char * text);
int lspStart(LspClient *lsp, const char *project_root);
void lspShutdown(LspClient *lsp);
int lspStart(LspClient* lsp, const char* project_root);
void lspShutdown(LspClient* lsp);
// Document sync — call these from your buffer open/save/edit hooks
void lspDidOpen(LspClient *lsp, struct buffer_t *buf);
void lspDidChange(LspClient *lsp, struct buffer_t *buf);
void lspDidClose(LspClient *lsp, struct buffer_t *buf);
void lspDidOpen(LspClient* lsp, struct buffer_t* buf);
void lspDidChange(LspClient* lsp, struct buffer_t* buf);
void lspDidClose(LspClient* lsp, struct buffer_t* buf);
// Requests
void lspRequestCompletion(LspClient *lsp, struct buffer_t *buf,
void lspRequestCompletion(LspClient* lsp, struct buffer_t* buf,
int line, int col,
int screen_x, int screen_y);
void lspRequestHover(LspClient *lsp, struct buffer_t *buf, int line, int col);
void lspRequestDefinition(LspClient *lsp, struct buffer_t *buf, int line, int col);
void lspRequestHover(LspClient* lsp, struct buffer_t* buf, int line, int col);
void lspRequestDefinition(LspClient* lsp, struct buffer_t* buf, int line, int col);
#endif //BELUGA_COMPLETION_H
+158 -146
View File
@@ -17,85 +17,94 @@ typedef struct lsp_client_t LspClient;
* \param
* */
typedef struct row {
int size; /**< Size of the line */
int cap; /**< Size of the render line */
char *chars; /**< Characters of the line */
typedef struct row
{
int size; /**< Size of the line */
int cap; /**< Size of the render line */
char* chars; /**< Characters of the line */
} row_t;
typedef struct context_buffer_t
{
int editor_x, editor_y;
int width, height;
row_t *rows;
int editor_x, editor_y;
int width, height;
row_t* rows;
} ContextBuffer;
/**
* @brief Split modes for screen layout
*/
typedef enum {
SPLIT_NONE = 0, // Single buffer fullscreen
SPLIT_VERTICAL, // Left-right split
SPLIT_HORIZONTAL // Top-bottom split
typedef enum
{
SPLIT_NONE = 0, // Single buffer fullscreen
SPLIT_VERTICAL, // Left-right split
SPLIT_HORIZONTAL // Top-bottom split
} SplitMode;
/**
* @brief Represents an editor viewport/pane
*/
typedef struct {
int buffer_id; // Which buffer this pane displays
int height; // Height of this pane
int width; // Width of this pane
typedef struct
{
int buffer_id; // Which buffer this pane displays
int height; // Height of this pane
int width; // Width of this pane
int origin_x, origin_y;
int cursor_x; // Local cursor x in this pane
int cursor_y; // Local cursor y in this pane
int cursor_x; // Local cursor x in this pane
int cursor_y; // Local cursor y in this pane
int x_offset, y_offset;
int is_active; // Is this pane currently active
int is_active; // Is this pane currently active
} EditorPane;
/**
* @brief Screen layout manager
*/
typedef struct {
typedef struct
{
SplitMode mode;
EditorPane *panes;
EditorPane* panes;
int num_panes;
int active_pane; // Index of active pane
int active_pane; // Index of active pane
} ScreenLayout;
typedef struct theme {
char *BACKGROUND_COLOR;
char *COLOR_KEYWORD;
char *COLOR_TYPE;
char *COLOR_STRING;
char *COLOR_COMMENT;
char *COLOR_NUMBER;
char *COLOR_DEFAULT;
typedef struct theme
{
char* BACKGROUND_COLOR;
char* COLOR_KEYWORD;
char* COLOR_TYPE;
char* COLOR_STRING;
char* COLOR_COMMENT;
char* COLOR_NUMBER;
char* COLOR_DEFAULT;
} theme_t;
enum bufferStatus_e {
IDLE,
READ_ONLY,
READ_AND_WRITE,
enum bufferStatus_e
{
IDLE,
READ_ONLY,
READ_AND_WRITE,
};
struct const_t {
int TAB_LENGTH;
int QUIT_TIMES;
char *THEME;
struct const_t
{
int TAB_LENGTH;
int QUIT_TIMES;
char* THEME;
int LSP;
};
struct prefix_t {
char prefix_name[64];
int prefix_id;
struct prefix_t
{
char prefix_name[64];
int prefix_id;
};
struct keyBind_t {
char *key_sequence;
int prefix_id;
Lisp command;
struct keyBind_t
{
char* key_sequence;
int prefix_id;
Lisp command;
};
// In data.h — add these
@@ -104,142 +113,144 @@ struct keyBind_t {
#define LSP_MAX_PENDING 64
typedef enum {
LSP_NOT_STARTED = 0,
LSP_INITIALIZING,
LSP_READY,
LSP_SHUTDOWN,
typedef enum
{
LSP_NOT_STARTED = 0,
LSP_INITIALIZING,
LSP_READY,
LSP_SHUTDOWN,
} LspState;
typedef struct {
int id;
void (*callback)(struct lsp_client_t *lsp, const char *json);
typedef struct
{
int id;
void (*callback)(struct lsp_client_t* lsp, const char* json);
} LspPending;
typedef struct lsp_client_t {
// ── Process ───────────────────────────────────────────────────────────────
pid_t pid;
int write_fd;
int read_fd;
int completion_just_arrived;
int completion_requested;
typedef struct lsp_client_t
{
// ── Process ───────────────────────────────────────────────────────────────
pid_t pid;
int write_fd;
int read_fd;
int completion_just_arrived;
int completion_requested;
int wake_pipe[2]; // [0] = read end (main loop), [1] = write end (reader thread)
// ── State ─────────────────────────────────────────────────────────────────
LspState state;
int next_id;
// ── Pending requests ──────────────────────────────────────────────────────
LspPending pending[LSP_MAX_PENDING];
int pending_count;
int wake_pipe[2]; // [0] = read end (main loop), [1] = write end (reader thread)
// ── Threading ─────────────────────────────────────────────────────────────
pthread_t reader_thread;
pthread_mutex_t lock;
pthread_cond_t ready_cond; // signaled when state → LSP_READY
// ── State ─────────────────────────────────────────────────────────────────
LspState state;
int next_id;
// ── Pending requests ──────────────────────────────────────────────────────
LspPending pending[LSP_MAX_PENDING];
int pending_count;
// ── Threading ─────────────────────────────────────────────────────────────
pthread_t reader_thread;
pthread_mutex_t lock;
pthread_cond_t ready_cond; // signaled when state → LSP_READY
// ── Completion context ────────────────────────────────────────────────────
int completion_cursor_x; // screen position when
int completion_cursor_y; // completion was requested
// ── Completion context ────────────────────────────────────────────────────
int completion_cursor_x; // screen position when
int completion_cursor_y; // completion was requested
} LspClient;
typedef struct {
char label[128]; // display text e.g. "printf"
char detail[64]; // type/sig hint e.g. "int (const char *, ...)"
int kind; // LSP CompletionItemKind (1=Text,2=Method,3=Function…)
typedef struct
{
char label[128]; // display text e.g. "printf"
char detail[64]; // type/sig hint e.g. "int (const char *, ...)"
int kind; // LSP CompletionItemKind (1=Text,2=Method,3=Function…)
} CompletionItem;
typedef struct {
CompletionItem items[COMPLETION_MAX_ITEMS];
int count;
int selected; // currently highlighted row
int visible; // is the popup shown?
int origin_x; // screen col where popup appears
int origin_y; // screen row where popup appears
typedef struct
{
CompletionItem items[COMPLETION_MAX_ITEMS];
int count;
int selected; // currently highlighted row
int visible; // is the popup shown?
int origin_x; // screen col where popup appears
int origin_y; // screen row where popup appears
} CompletionPopup;
typedef enum { DIAG_ERROR = 1, DIAG_WARNING, DIAG_HINT } DiagSeverity;
typedef struct {
int buffer_id;
int line; // 0-based
int col_start; // 0-based
int col_end;
DiagSeverity severity;
char message[256];
typedef struct
{
int buffer_id;
int line; // 0-based
int col_start; // 0-based
int col_end;
DiagSeverity severity;
char message[256];
} Diagnostic;
typedef struct {
Diagnostic entries[DIAG_MAX];
int count;
typedef struct
{
Diagnostic entries[DIAG_MAX];
int count;
} DiagnosticList;
enum buffer_type { FILE_BUFF, TERMINAL_BUFF };
struct buffer_t {
enum buffer_type type;
int buffer_id;
int b_lsp_open;
int x, y; /**< Position in the file */
row_t *row;
int numrows;
int b_has_changed;
char *filename;
char *path;
enum bufferStatus_e state;
int dirty; /**< Has this buffer been modified since last save */
struct buffer_t
{
enum buffer_type type;
int buffer_id;
int b_lsp_open;
int x, y; /**< Position in the file */
row_t* row;
int numrows;
int b_has_changed;
char* filename;
char* path;
char * fullname;
enum bufferStatus_e state;
int dirty; /**< Has this buffer been modified since last save */
};
/**
* \struct editorConfig
* \brief Containing our editor state.
*/
struct editorConfig {
int cursor_x, cursor_y; /**< Cursor position */
int screenrows; /**< Terminal height*/
int screencols; /**< Terminal width*/
struct editorConfig
{
int cursor_x, cursor_y; /**< Cursor position */
int screenrows; /**< Terminal height*/
int screencols; /**< Terminal width*/
ScreenLayout layout;
ScreenLayout layout;
row_t *rows; /**< Store all the rows printed */
LspClient* lsp_client;
CompletionPopup lsp_completion;
DiagnosticList lsp_diagnostics;
ContextBuffer* context_buffers;
int dirty;
LspClient *lsp_client;
CompletionPopup lsp_completion;
DiagnosticList lsp_diagnostics;
char* status_msg;
time_t status_msg_time;
struct termios orig_termios; /**< Terminal communication interface */
int dirty;
struct const_t constantes;
int quit_times_buffer;
char *status_msg;
time_t status_msg_time;
struct termios orig_termios; /**< Terminal communication interface */
char* init_file_path;
FILE* fd_init_file;
Lisp env;
LispContext ctx; /** Lisp context */
Lisp ctx_data; /** Lisp data context */
LispError ctx_error; /** Lisp ctx error */
struct const_t constantes;
int quit_times_buffer;
struct keyBind_t* key_binds;
int number_of_keybinds;
char *init_file_path;
FILE *fd_init_file;
Lisp env;
LispContext ctx; /** Lisp context */
Lisp ctx_data; /** Lisp data context */
LispError ctx_error; /** Lisp ctx error */
struct prefix_t* prefix;
int number_of_prefix;
int prefix_state;
struct keyBind_t *key_binds;
int number_of_keybinds;
struct buffer_t buffers[64];
int number_of_buffer;
struct prefix_t *prefix;
int number_of_prefix;
int prefix_state;
struct buffer_t buffers[64];
int number_of_buffer;
theme_t theme;
theme_t theme;
};
/**
@@ -247,9 +258,10 @@ struct editorConfig {
* \brief Contains text to add before writing to screen.
* */
struct abuf {
char *b; /**< Text that will be printed */
int len; /**< Length of the text */
struct abuf
{
char* b; /**< Text that will be printed */
int len; /**< Length of the text */
};
extern struct editorConfig E;
+3
View File
@@ -12,6 +12,8 @@
#define ERASE_END_LINE "\x1b[K"
#define TAB "\t"
#define SPACE "\x20"
/* Uncomment to see debug logs on stderr */
#define APP_DEBUG
#define COMPLETION_MAX_ITEMS 16
@@ -32,6 +34,7 @@ enum editorKey_e {
END_LINE,
PAGE_UP,
PAGE_DOWN,
LSP_WAKE_KEY = 2000
};
#define ABUF_INIT {NULL, 0}
+3
View File
@@ -11,4 +11,7 @@ void initBuiltins();
void initEditor();
void deInitEditor();
#endif // INIT_H_
+2 -2
View File
@@ -1163,7 +1163,7 @@ static Lisp sch_string_ref(Lisp args, LispError* e, LispContext ctx)
return lisp_null();
}
return lisp_make_char((int)lisp_string_ref(str, lisp_int(index)));
return lisp_make_char(lisp_string_ref(str, lisp_int(index)));
}
static Lisp sch_string_set(Lisp args, LispError* e, LispContext ctx)
@@ -1737,7 +1737,7 @@ static Lisp sch_pseudo_rand(Lisp args, LispError* e, LispContext ctx)
static Lisp sch_univeral_time(Lisp args, LispError* e, LispContext ctx)
{
return lisp_make_int((LispInt)time(NULL));
return lisp_make_int(time(NULL));
}
static Lisp sch_is_table(Lisp args, LispError* e, LispContext ctx)
+4
View File
@@ -59,4 +59,8 @@ ScreenLayout *splitScreenGetLayout(void);
*/
EditorPane *splitScreenGetActivePane(void);
void freePane(EditorPane *pane);
void freeScreenLayout(ScreenLayout *layout);
#endif
+1
View File
@@ -11,6 +11,7 @@ int utf8Encode(uint32_t cp, char *buf);
int utf8Seqlen(unsigned char c);
int codepointWidth(uint32_t codepoint);
uint32_t utf8Decode(const char** s);
int is_word_char(const char *s);
#endif //BELUGA_UTF8_H
-16
View File
@@ -1,16 +0,0 @@
//
// Created by Giorgio on 28/05/2026.
//
#ifndef BELUGA_UTILS_H
#define BELUGA_UTILS_H
#include <sys/_types/_size_t.h>
extern int beluga_alloc_counter;
void * bAlloc(size_t size);
void * bRealloc(void * ptr, size_t size);
void * bFree(void * ptr);
#endif //BELUGA_UTILS_H
+20 -25
View File
@@ -9,7 +9,7 @@
#define _BSD_SOURCE
#define _GNU_SOURCE
#include "include/utils.h"
#include <libgen.h>
#include "include/buffer.h"
#include "include/split_screen.h"
@@ -24,51 +24,46 @@
#include "include/completion.h"
#include <signal.h>
#include "include/utils.h"
struct editorConfig E;
int main(int argc, char *argv[]) {
char * splash_screen = bAlloc(sizeof(char) * 512);
char * splash_screen = strdup(getenv("HOME"));
int home_path_len = (int) strlen(splash_screen);
char * splash_screen_relative_path = strdup("/.beluga/assets/beluga.txt");
int splash_screen_relative_path_len = (int) strlen(splash_screen_relative_path);
signal(SIGPIPE, SIG_IGN); // don't die on broken pipe, just get EPIPE from write()
enableRawMode();
initEditor();
EditorPane *active = splitScreenGetActivePane();
struct buffer_t *buf;
splash_screen = realloc(splash_screen, sizeof(char) * (home_path_len + splash_screen_relative_path_len + 1));
strcat(splash_screen, "/.beluga/assets/beluga.txt");
free(splash_screen_relative_path);
appDebug("splash : %s\n", splash_screen);
active->buffer_id = bufferCreate(splash_screen, READ_ONLY);
if (argc >= 2) {
EditorPane *active = splitScreenGetActivePane();
if (E.constantes.LSP) {
}
active->buffer_id = bufferCreate(argv[1], READ_AND_WRITE);
char project_root[512];
realpath(argv[1], project_root);
char *slash = strrchr(project_root, '/');
if (slash) *slash = '\0';
buf = &E.buffers[active->buffer_id];
appDebug("peoject root : %s\n", project_root);
appDebug("peoject root : %s\n", dirname(buf->fullname));
lspStart(E.lsp_client, project_root);
struct buffer_t *buf = &E.buffers[active->buffer_id];
lspDidOpen(E.lsp_client, buf);
} else {
strcat(splash_screen, getenv("HOME"));
strcat(splash_screen, "/.beluga/assets/beluga.txt");
appDebug("splash : %s\n", splash_screen);
EditorPane *active = splitScreenGetActivePane();
active->buffer_id = bufferCreate(splash_screen, READ_ONLY);
struct buffer_t *buf = &E.buffers[active->buffer_id];
lspStart(E.lsp_client, splash_screen);
lspDidOpen(E.lsp_client, buf);
}
free(splash_screen);
editorSetStatusMessage("HELP: Ctrl-x Ctrl-s = save | Ctrl-x Ctrl-c = quit");
appDebug("allocation : %d\n", beluga_alloc_counter);
while (1) {
editorRefreshScreen();
editorProcessKeypress();
+1 -2
View File
@@ -27,8 +27,7 @@ src_files = files(
'src/utf8.c',
'src/completion.c',
'src/lsp_ui.c',
'src/cJSON.c',
'src/utils.c'
'src/cJSON.c'
)
# Executable
+2 -3
View File
@@ -1,8 +1,7 @@
#include "../include/append_buffer.h"
#include "include/utils.h"
void abAppend(struct abuf *ab, const char *s, int len) {
char *new = bRealloc(ab->b, ab->len + len);
char *new = realloc(ab->b, ab->len + len);
if (new == NULL) {
return;
@@ -12,4 +11,4 @@ void abAppend(struct abuf *ab, const char *s, int len) {
ab->len += len;
}
void abFree(struct abuf *ab) { bFree(ab->b); }
void abFree(const struct abuf *ab) { free(ab->b); }
+24 -13
View File
@@ -8,14 +8,15 @@
#include "../include/editor_op.h"
#include "../include/data.h"
#include "include/split_screen.h"
#include <_string.h>
#include <stdio.h>
#include <stdlib.h>
#include <libgen.h>
#include <string.h>
#include <sys/stat.h>
#include "include/completion.h"
#include "include/input.h"
#include "include/utils.h"
/**
@@ -61,10 +62,10 @@ struct buffer_t* bufferFindById(int buffer_id)
*/
int bufferCreate(const char* path, enum bufferStatus_e state)
{
appDebug("Creating new buffer");
char *filename = basename((char *) path);
// Check if file is already open
const int existing_id = bufferFindByFilename(path);
path = dirname((char *) path);
if (existing_id != -1)
{
return bufferSwitch(existing_id);
@@ -80,17 +81,27 @@ int bufferCreate(const char* path, enum bufferStatus_e state)
struct buffer_t* new_buf = &E.buffers[E.number_of_buffer];
new_buf->buffer_id = E.number_of_buffer;
new_buf->filename = strdup(filename);
new_buf->fullname = malloc(1024 * sizeof(char));
realpath(path, new_buf->fullname);
new_buf->path = dirname(new_buf->fullname);
new_buf->type = FILE_BUFF;
new_buf->state = state;
new_buf->x = 0;
new_buf->y = 0;
new_buf->dirty = 0; // New file starts clean
new_buf->path = strdup(path);
new_buf->b_lsp_open = 0;
// Load file content using existing editorOpen
editorOpen(new_buf);
E.number_of_buffer++;
if (new_buf->filename[strlen(new_buf->filename) - 1] == 'c')
{
if (E.lsp_client->state == LSP_SHUTDOWN)
lspStart(E.lsp_client, dirname(new_buf->path));
while (E.lsp_client->state != LSP_READY)
;
lspDidOpen(E.lsp_client, new_buf);
}
editorSetStatusMessage("Opened: %s (buffer %d)", filename, new_buf->buffer_id);
return new_buf->buffer_id;
@@ -164,7 +175,7 @@ int bufferClose(int buffer_id)
}
// Free buffer resources
bFree(buf->filename);
free(buf->filename);
buf->filename = NULL;
buf->buffer_id = -1;
@@ -300,7 +311,7 @@ void bufferFind(struct buffer_t* buf)
break;
}
}
bFree(query);
free(query);
}
void bufferFindReverse(struct buffer_t* buf)
@@ -323,14 +334,14 @@ void bufferFindReverse(struct buffer_t* buf)
break;
}
}
bFree(query);
free(query);
}
void bufferInsertRow(struct buffer_t *buffer, int at, char *s, size_t len) {
if (at < 0 || at > buffer->numrows)
return;
row_t *tmp = bRealloc(buffer->row, sizeof(row_t) * (buffer->numrows + 1));
row_t *tmp = realloc(buffer->row, sizeof(row_t) * (buffer->numrows + 1));
if (!tmp)
return;
buffer->row = tmp;
@@ -343,7 +354,7 @@ void bufferInsertRow(struct buffer_t *buffer, int at, char *s, size_t len) {
buffer->row[at].size = (int) len;
buffer->row[at].cap = (int) len + 1;
buffer->row[at].chars = bAlloc(len + 1);
buffer->row[at].chars = malloc(len + 1);
if (!buffer->row[at].chars)
return;
memcpy(buffer->row[at].chars, s, len);
@@ -353,7 +364,7 @@ void bufferInsertRow(struct buffer_t *buffer, int at, char *s, size_t len) {
buffer->dirty++;
}
void bufferFreeRow(row_t *row) { bFree(row->chars); }
void bufferFreeRow(row_t *row) { free(row->chars); }
/**
* \fn editorRowInsertChar(erow *row, int at, int c)
@@ -365,12 +376,12 @@ void bufferRowInsertBytes(struct buffer_t *buffer, row_t *row, int at,
return;
if (row->size + n + 1 > row->cap) {
row->cap = (row->size + n + 1) * 2;
row->chars = bRealloc(row->chars, row->cap);
row->chars = realloc(row->chars, row->cap);
}
memmove(row->chars + at + n, row->chars + at, row->size - at);
memcpy(row->chars + at, src, n);
row->size += n;
row->chars = bRealloc(row->chars, row->size + 2);
row->chars = realloc(row->chars, row->size + 2);
++buffer->dirty;
}
@@ -434,7 +445,7 @@ void bufferDelBytes(void)
int prev_char_count = editorRowCharCount(prev, prev->size);
bufferRowInsertBytes(buf, prev, prev->size, r->chars, r->size);
bFree(r->chars);
free(r->chars);
r->chars = NULL;
memmove(&buf->row[buf->y],
+25 -21
View File
@@ -21,7 +21,7 @@
#include <string.h>
#include "include/completion.h"
#include "include/utils.h"
#include "include/init.h"
/**
* @brief Finds a prefix configuration by name
@@ -68,13 +68,13 @@ Lisp mapKey(Lisp args, LispError* e, LispContext ctx)
// second argument
const Lisp func = lisp_car(args);
memory_temp = (void*)bRealloc(
memory_temp = realloc(
E.key_binds, ++E.number_of_keybinds * sizeof(struct keyBind_t));
E.key_binds = (struct keyBind_t*)memory_temp;
if (!E.key_binds)
editorQuit(args, e, ctx);
E.key_binds[E.number_of_keybinds - 1].key_sequence =
(char*)bAlloc(50 * sizeof(char));
(char*)malloc(50 * sizeof(char));
strncpy(E.key_binds[E.number_of_keybinds - 1].key_sequence, key_sequence, 50);
@@ -136,27 +136,27 @@ Lisp moveCursor(Lisp args, LispError* e, LispContext ctx)
void bFree_structs(void)
{
int i, j;
bFree(E.prefix);
free(E.prefix);
for (i = 0; i < E.number_of_keybinds; ++i)
{
bFree(E.key_binds[i].key_sequence);
free(E.key_binds[i].key_sequence);
}
bFree(E.key_binds);
free(E.key_binds);
// bFree layout
bFree(E.layout.panes);
free(E.layout.panes);
// bFree buffers
for (i = 0; i < E.number_of_buffer; ++i)
{
bFree(E.buffers[i].filename);
free(E.buffers[i].filename);
for (j = 0; j < E.buffers[i].numrows; ++j)
{
bFree(E.buffers[i].row[j].chars);
free(E.buffers[i].row[j].chars);
}
bFree(E.buffers[i].row);
free(E.buffers[i].row);
}
bFree(E.init_file_path);
free(E.init_file_path);
fclose(E.fd_init_file);
}
@@ -185,10 +185,10 @@ Lisp editorQuit(Lisp args, LispError* e, LispContext ctx)
bFree_structs();
write(STDOUT_FILENO, "\x1b[2J", 4);
write(STDOUT_FILENO, CURSOR_TOP_LEFT, 3);
disableRawMode();
lspShutdown(E.lsp_client);
lisp_shutdown(E.ctx);
appDebug("Rest alloc %d\n", beluga_alloc_counter);
deInitEditor();
disableRawMode();
exit(0);
}
@@ -218,7 +218,6 @@ Lisp l_editorSplitScreenVertical(Lisp args, LispError* e, LispContext ctx)
Lisp l_editorSave(Lisp args, LispError* e, LispContext ctx)
{
editorSave();
return lisp_null();
}
@@ -378,7 +377,7 @@ Lisp editorOpenFile(Lisp args, LispError* e, LispContext ctx)
EditorPane* active = splitScreenGetActivePane();
active->buffer_id = bufferCreate(filename, READ_AND_WRITE);
}
bFree(filename);
free(filename);
return lisp_null();
}
@@ -415,7 +414,7 @@ Lisp addPackage(Lisp args, LispError* e, LispContext ctx)
{
const char* package_name = lisp_string(lisp_car(args));
appDebug("%s\n", package_name);
char* package_dir = (char*)calloc(256, sizeof(char));
char* package_dir = calloc(256, sizeof(char));
FILE* fd_package = NULL;
strcat(package_dir, getenv("HOME"));
strcat(package_dir, "/.beluga/packages/");
@@ -426,7 +425,7 @@ Lisp addPackage(Lisp args, LispError* e, LispContext ctx)
lisp_eval(lisp_read_file(fd_package, &E.ctx_error, E.ctx), &E.ctx_error,
E.ctx);
fclose(fd_package);
bFree(package_dir);
free(package_dir);
return lisp_null();
}
@@ -557,8 +556,7 @@ Lisp editorSetPrefix(Lisp args, LispError* e, LispContext ctx)
*/
Lisp editorPrefix(Lisp args, LispError* e, LispContext ctx)
{
void * memory_temp;
E.prefix = (struct prefix_t*)bRealloc(E.prefix, (++(E.number_of_prefix) + 1) *
E.prefix = (struct prefix_t*)realloc(E.prefix, (++(E.number_of_prefix) + 1) *
sizeof(struct prefix_t));
E.prefix[E.number_of_prefix].prefix_id = E.number_of_prefix;
strncpy(E.prefix[E.number_of_prefix].prefix_name, lisp_string(lisp_car(args)),
@@ -610,6 +608,9 @@ Lisp editorMoveEndBuffer(Lisp args, LispError* e, LispContext ctx)
Lisp editorAutoComplete(Lisp args, LispError* e, LispContext ctx)
{
if (!E.constantes.LSP) {
return lisp_null();
}
// createContextBuffer(E.cursor_x - 2, E.cursor_y + 1, "hello");
appDebug("editor-auto-complete\n");
EditorPane* active = splitScreenGetActivePane();
@@ -618,8 +619,8 @@ Lisp editorAutoComplete(Lisp args, LispError* e, LispContext ctx)
lspRequestCompletion(
E.lsp_client,
buffer,
active->cursor_y + active->y_offset, // file line
active->cursor_x + active->x_offset, // file col
buffer->y, // file line
buffer->x, // file col
active->cursor_x + active->origin_x + GUTTER_WIDTH, // screen x
active->cursor_y + active->origin_y // screen y
);
@@ -628,6 +629,9 @@ Lisp editorAutoComplete(Lisp args, LispError* e, LispContext ctx)
Lisp lspDefinition(Lisp args, LispError* e, LispContext ctx)
{
if (!E.constantes.LSP) {
return lisp_null();
}
(void)args;
(void)e;
(void)ctx;
+1
View File
@@ -1906,6 +1906,7 @@ CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array)
return 0;
}
child = array->child;
while(child != NULL)
+170 -131
View File
@@ -13,22 +13,8 @@
#include "include/cJSON.h"
#include "include/data.h"
#include "include/lsp_ui.h"
#include "include/split_screen.h"
#include "include/terminal.h"
#include "include/utils.h"
void createContextBuffer(const int x, const int y, const char* text)
{
E.context_buffers = bAlloc(sizeof(ContextBuffer));
ContextBuffer* buffer = E.context_buffers;
buffer->editor_x = x;
buffer->editor_y = y;
buffer->height = 1;
buffer->rows = bAlloc(sizeof(struct row));
if (!buffer->rows) return;
buffer->rows[0].chars = strdup(text);
buffer->rows[0].size = strlen(text);
buffer->width = strlen(text);
}
static void lsp_send(int fd, const char* json)
{
@@ -42,28 +28,10 @@ static void lsp_send(int fd, const char* json)
write(fd, json, body_len);
// Log to stderr for debugging
fprintf(stderr, "[LSP →] Content-Length: %d | %s\n", body_len, json);
appDebug("[LSP →] Content-Length: %d | %s\n", body_len, json);
fflush(stderr);
}
static int lsp_uri_to_buffer_id(const char* uri)
{
const char *path = uri;
if (strncmp(uri, "file://", 7) == 0)
path = uri + 7;
// path is now "/absolute/path" — realpath output matches this directly
for (int i = 0; i < E.number_of_buffer; i++) {
if (E.buffers[i].filename == NULL) continue;
char abs[PATH_MAX];
realpath(E.buffers[i].filename, abs);
fprintf(stderr, "[URI MATCH] comparing '%s' vs '%s'\n", abs, path);
if (strcmp(abs, path) == 0)
return E.buffers[i].buffer_id;
}
return -1;
}
static char* lsp_recv(int fd)
{
char header[1024];
@@ -89,14 +57,14 @@ static char* lsp_recv(int fd)
if (content_length == 0) return NULL;
char* body = bAlloc(content_length + 1);
char* body = malloc(content_length + 1);
int total = 0;
while (total < content_length)
{
int n = read(fd, body + total, content_length - total);
if (n <= 0)
{
bFree(body);
free(body);
return NULL;
}
total += n;
@@ -112,7 +80,7 @@ static void lsp_dispatch(LspClient* lsp, const char* json)
cJSON* root = cJSON_Parse(json);
if (!root)
{
fprintf(stderr, "[LSP ←] Failed to parse JSON: %.120s\n", json);
appDebug("[LSP ←] Failed to parse JSON: %.120s\n", json);
return;
}
@@ -125,7 +93,7 @@ static void lsp_dispatch(LspClient* lsp, const char* json)
if (error)
{
cJSON* msg = cJSON_GetObjectItem(error, "message");
fprintf(stderr, "[LSP ←] ERROR: %s\n",
appDebug("[LSP ←] ERROR: %s\n",
msg ? msg->valuestring : "(no message)");
cJSON_Delete(root);
return;
@@ -135,17 +103,16 @@ static void lsp_dispatch(LspClient* lsp, const char* json)
if (method && !id)
{
const char* m = method->valuestring;
fprintf(stderr, "[LSP ←] NOTIF: %s\n", m);
appDebug("[LSP ←] NOTIF: %s\n", m);
if (strcmp(m, "textDocument/publishDiagnostics") == 0)
{
// Find which buffer this diagnostic belongs to
cJSON* params = cJSON_GetObjectItem(root, "params");
cJSON* uri = cJSON_GetObjectItem(params, "uri");
int buf_id = lsp_uri_to_buffer_id(
uri ? uri->valuestring : "");
int buf_id = splitScreenGetActivePane()->buffer_id;
fprintf(stderr, "[LSP ←] Diagnostics for buffer %d\n", buf_id);
appDebug("[LSP ←] Diagnostics for buffer %d\n", buf_id);
pthread_mutex_lock(&lsp->lock);
lspParseDiagnostics(json, &E.lsp_diagnostics, buf_id);
@@ -157,7 +124,7 @@ static void lsp_dispatch(LspClient* lsp, const char* json)
{
cJSON* params = cJSON_GetObjectItem(root, "params");
cJSON* message = cJSON_GetObjectItem(params, "message");
fprintf(stderr, "[LSP ←] LOG: %s\n",
appDebug("[LSP ←] LOG: %s\n",
message ? message->valuestring : "");
}
E.lsp_client->completion_just_arrived = 1;
@@ -171,12 +138,12 @@ static void lsp_dispatch(LspClient* lsp, const char* json)
if (id && result)
{
int response_id = id->valueint;
fprintf(stderr, "[LSP ←] RESPONSE id=%d\n", response_id);
appDebug("[LSP ←] RESPONSE id=%d\n", response_id);
// initialize response → send initialized + mark ready
if (lsp->state == LSP_INITIALIZING)
{
fprintf(stderr, "[LSP ←] Initialize OK, sending initialized\n");
appDebug("[LSP ←] Initialize OK, sending initialized\n");
lsp_send(lsp->write_fd,
"{\"jsonrpc\":\"2.0\",\"method\":\"initialized\",\"params\":{}}");
@@ -195,7 +162,7 @@ static void lsp_dispatch(LspClient* lsp, const char* json)
if (items && cJSON_IsArray(items))
{
int count = cJSON_GetArraySize(items);
fprintf(stderr, "[LSP ←] Completion: %d items\n", count);
appDebug("[LSP ←] Completion: %d items\n", count);
// Print each item to stderr for debugging
cJSON* item;
@@ -205,14 +172,14 @@ static void lsp_dispatch(LspClient* lsp, const char* json)
cJSON* label = cJSON_GetObjectItem(item, "label");
cJSON* detail = cJSON_GetObjectItem(item, "detail");
cJSON* kind = cJSON_GetObjectItem(item, "kind");
fprintf(stderr, " [%d] kind=%-2d %-40s %s\n",
appDebug(" [%d] kind=%-2d %-40s %s\n",
i++,
kind ? kind->valueint : 0,
label ? label->valuestring : "(no label)",
detail ? detail->valuestring : "");
if (i >= 10)
{
fprintf(stderr, " ... (%d more)\n", count - 10);
appDebug(" ... (%d more)\n", count - 10);
break;
}
}
@@ -224,7 +191,7 @@ static void lsp_dispatch(LspClient* lsp, const char* json)
pthread_mutex_unlock(&lsp->lock);
E.lsp_client->completion_just_arrived = 1;
fprintf(stderr, "[POPUP] visible=%d count=%d origin=(%d,%d)\n",
appDebug("[POPUP] visible=%d count=%d origin=(%d,%d)\n",
E.lsp_completion.visible,
E.lsp_completion.count,
E.lsp_completion.origin_x,
@@ -243,7 +210,7 @@ static void lsp_dispatch(LspClient* lsp, const char* json)
cJSON* start = cJSON_GetObjectItem(range, "start");
int line = cJSON_GetObjectItem(start, "line")->valueint;
int col = cJSON_GetObjectItem(start, "character")->valueint;
fprintf(stderr, "[LSP ←] Definition: %s:%d:%d\n",
appDebug("[LSP ←] Definition: %s:%d:%d\n",
uri_item->valuestring, line, col);
E.lsp_client->completion_just_arrived = 1;
@@ -252,7 +219,7 @@ static void lsp_dispatch(LspClient* lsp, const char* json)
return;
}
fprintf(stderr, "[LSP ←] Unhandled response id=%d: %.80s\n",
appDebug("[LSP ←] Unhandled response id=%d: %.80s\n",
response_id, json);
}
@@ -267,70 +234,129 @@ static void* lsp_reader(void* arg)
char* msg = lsp_recv(lsp->read_fd);
if (!msg) break; // ← pipe closed or error, exit cleanly
lsp_dispatch(lsp, msg);
bFree(msg);
free(msg);
}
return NULL;
}
// ─── lifecycle ───────────────────────────────────────────────────────────────
int lspStart(LspClient* lsp, const char* project_root)
int lspStart(LspClient *lsp, const char *project_root)
{
// ── Pipes ─────────────────────────────────────────────────────────────────
int to_clangd[2], from_clangd[2];
pipe(to_clangd);
pipe(from_clangd);
pipe(lsp->wake_pipe);
if (pipe(to_clangd) < 0 || pipe(from_clangd) < 0) {
fprintf(stderr, "[LSP] pipe() failed\n");
free(lsp);
return 0;
}
if (pipe(lsp->wake_pipe) < 0) {
fprintf(stderr, "[LSP] wake pipe() failed\n");
free(lsp);
return 0;
}
// ── Fork clangd ───────────────────────────────────────────────────────────
lsp->pid = fork();
if (lsp->pid == 0)
{
// Child: become clangd
dup2(to_clangd[0], STDIN_FILENO);
if (lsp->pid < 0) {
fprintf(stderr, "[LSP] fork() failed\n");
free(lsp);
return 0;
}
if (lsp->pid == 0) {
// Child — become clangd
dup2(to_clangd[0], STDIN_FILENO);
dup2(from_clangd[1], STDOUT_FILENO);
close(to_clangd[1]);
close(from_clangd[0]);
execlp("clangd", "clangd", "--log=error", "--completion-style=detailed", NULL);
_exit(1); // clangd not found
close(lsp->wake_pipe[0]);
close(lsp->wake_pipe[1]);
execlp("clangd", "clangd",
"--log=error",
"--completion-style=detailed",
NULL);
fprintf(stderr, "[LSP] execlp failed — is clangd installed?\n");
_exit(1);
}
// Parent — keep write end of to_clangd, read end of from_clangd
close(to_clangd[0]);
close(from_clangd[1]);
lsp->write_fd = to_clangd[1];
lsp->read_fd = from_clangd[0];
lsp->next_id = 1;
lsp->state = LSP_INITIALIZING;
pthread_mutex_init(&lsp->lock, NULL);
lsp->read_fd = from_clangd[0];
lsp->next_id = 1;
lsp->state = LSP_INITIALIZING;
// Send initialize
char buf[1024];
snprintf(buf, sizeof(buf),
"{\"jsonrpc\":\"2.0\",\"id\":%d,\"method\":\"initialize\","
"\"params\":{\"processId\":%d,\"rootUri\":\"file://%s\","
"\"capabilities\":{"
"\"textDocument\":{"
"\"completion\":{\"completionItem\":{\"snippetSupport\":false}},"
"\"hover\":{},"
"\"definition\":{},"
"\"publishDiagnostics\":{}"
"}"
"}}}",
lsp->next_id++, getpid(), project_root);
// ── Threading ─────────────────────────────────────────────────────────────
pthread_mutex_init(&lsp->lock, NULL);
pthread_cond_init (&lsp->ready_cond, NULL);
pthread_mutex_init(&lsp->lock, NULL);
pthread_cond_init(&lsp->ready_cond, NULL);
// Start reader thread BEFORE sending initialize
// so it can handle the response
pthread_create(&lsp->reader_thread, NULL, lsp_reader, lsp);
// ── Send initialize ───────────────────────────────────────────────────────
char abs_root[PATH_MAX];
if (realpath(project_root, abs_root) == NULL)
strncpy(abs_root, project_root, PATH_MAX - 1);
lsp_send(lsp->write_fd, buf);
cJSON *req = cJSON_CreateObject();
cJSON *params = cJSON_CreateObject();
cJSON *caps = cJSON_CreateObject();
cJSON *td_caps = cJSON_CreateObject();
cJSON *comp_caps = cJSON_CreateObject();
cJSON *comp_item = cJSON_CreateObject();
cJSON_AddStringToObject(req, "jsonrpc", "2.0");
cJSON_AddNumberToObject(req, "id", lsp->next_id++);
cJSON_AddStringToObject(req, "method", "initialize");
// rootUri
char root_uri[PATH_MAX + 8];
snprintf(root_uri, sizeof(root_uri), "file://%s", abs_root);
cJSON_AddNumberToObject(params, "processId", getpid());
cJSON_AddStringToObject(params, "rootUri", root_uri);
// Capabilities — tell clangd what we support
cJSON_AddBoolToObject (comp_item, "snippetSupport", 0);
cJSON_AddBoolToObject (comp_item, "commitCharactersSupport", 0);
cJSON_AddItemToObject (comp_caps, "completionItem", comp_item);
cJSON_AddItemToObject (td_caps, "completion", comp_caps);
cJSON_AddItemToObject (td_caps, "hover", cJSON_CreateObject());
cJSON_AddItemToObject (td_caps, "definition", cJSON_CreateObject());
cJSON_AddItemToObject (td_caps, "publishDiagnostics", cJSON_CreateObject());
cJSON_AddItemToObject (caps, "textDocument", td_caps);
cJSON_AddItemToObject (params, "capabilities", caps);
cJSON_AddItemToObject (req, "params", params);
char *msg = cJSON_PrintUnformatted(req);
lsp_send(lsp->write_fd, msg);
free(msg);
cJSON_Delete(req);
// ── Wait for LSP_READY ────────────────────────────────────────────────────
// Reader thread will handle the initialize response,
// send "initialized", and signal ready_cond
pthread_mutex_lock(&lsp->lock);
while (lsp->state != LSP_READY)
pthread_cond_wait(&lsp->ready_cond, &lsp->lock);
while (lsp->state != LSP_READY) {
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec += 5; // 5 second timeout — clangd should respond fast
int rc = pthread_cond_timedwait(&lsp->ready_cond, &lsp->lock, &ts);
if (rc == ETIMEDOUT) {
fprintf(stderr, "[LSP] timeout waiting for initialize response\n");
pthread_mutex_unlock(&lsp->lock);
// Don't kill clangd — it might still come up, just return what we have
return 1;
}
}
pthread_mutex_unlock(&lsp->lock);
return 0;
}
fprintf(stderr, "[LSP] ready — clangd initialized at %s\n", abs_root);
return 1;
}
// ─── document sync ───────────────────────────────────────────────────────────
// Build the full buffer text into a bAlloc'd string
@@ -339,7 +365,7 @@ static char* buffer_to_text(struct buffer_t* buf)
int total = 0;
for (int i = 0; i < buf->numrows; i++)
total += buf->row[i].size + 1; // +1 for \n
char* text = bAlloc(total + 1);
char* text = malloc(total + 1);
char* p = text;
for (int i = 0; i < buf->numrows; i++)
{
@@ -353,12 +379,12 @@ static char* buffer_to_text(struct buffer_t* buf)
void lspDidOpen(LspClient* lsp, struct buffer_t* buf)
{
appDebug("[LSP] opening file");
if (lsp->state != LSP_READY || buf->b_lsp_open) return;
char abs[PATH_MAX];
realpath(buf->filename, abs);
char uri[PATH_MAX + 8];
snprintf(uri, sizeof(uri), "file://%s", abs);
snprintf(uri, sizeof(uri), "file://%s", buf->fullname);
const char* lang = "c";
if (strstr(buf->filename, ".cpp") || strstr(buf->filename, ".cc"))
@@ -385,8 +411,8 @@ void lspDidOpen(LspClient* lsp, struct buffer_t* buf)
char* msg = cJSON_PrintUnformatted(root);
lsp_send(lsp->write_fd, msg);
bFree(msg);
bFree(raw);
free(msg);
free(raw);
cJSON_Delete(root);
buf->b_lsp_open = 1;
}
@@ -395,10 +421,9 @@ void lspDidChange(LspClient* lsp, struct buffer_t* buf)
{
if (lsp->state != LSP_READY || !buf->b_lsp_open) return;
char abs[PATH_MAX];
realpath(buf->filename, abs);
char uri[PATH_MAX + 8];
snprintf(uri, sizeof(uri), "file://%s", abs);
snprintf(uri, sizeof(uri), "file://%s", buf->fullname);
char* raw = buffer_to_text(buf);
@@ -424,17 +449,16 @@ void lspDidChange(LspClient* lsp, struct buffer_t* buf)
char* msg = cJSON_PrintUnformatted(root);
lsp_send(lsp->write_fd, msg);
bFree(msg);
bFree(raw);
free(msg);
free(raw);
cJSON_Delete(root);
}
void lspDidClose(LspClient* lsp, struct buffer_t* buf)
{
char abs[PATH_MAX];
realpath(buf->filename, abs);
char uri[PATH_MAX + 8];
snprintf(uri, sizeof(uri), "file://%s", abs);
snprintf(uri, sizeof(uri), "file://%s", buf->fullname);
cJSON* root = cJSON_CreateObject();
cJSON* params = cJSON_CreateObject();
@@ -446,7 +470,7 @@ void lspDidClose(LspClient* lsp, struct buffer_t* buf)
cJSON_AddItemToObject(root, "params", params);
char* msg = cJSON_PrintUnformatted(root);
lsp_send(lsp->write_fd, msg);
bFree(msg);
free(msg);
cJSON_Delete(root);
buf->b_lsp_open = 0;
}
@@ -458,16 +482,15 @@ void lspRequestCompletion(LspClient* lsp, struct buffer_t* buf,
int screen_x, int screen_y)
{
if (lsp->state != LSP_READY) return;
lsp->completion_cursor_x = screen_x; // ← add
lsp->completion_cursor_x = screen_x;
lsp->completion_cursor_y = screen_y;
appDebug("LSP REQUEST COMP");
char* msg;
char abs[PATH_MAX];
realpath(buf->filename, abs);
char uri[PATH_MAX + 8];
snprintf(uri, sizeof(uri), "file://%s", abs);
snprintf(uri, sizeof(uri), "file://%s", buf->fullname);
appDebug("FULLNAME : %s\n", buf->fullname);
cJSON* req = cJSON_CreateObject();
cJSON* params = cJSON_CreateObject();
@@ -491,7 +514,7 @@ void lspRequestCompletion(LspClient* lsp, struct buffer_t* buf,
lsp_send(lsp->write_fd, msg);
E.lsp_client->completion_requested = 1;
cJSON_Delete(req);
bFree(msg);
free(msg);
}
void lspRequestDefinition(LspClient* lsp, struct buffer_t* buf, int line, int col)
@@ -504,52 +527,68 @@ void lspRequestDefinition(LspClient* lsp, struct buffer_t* buf, int line, int co
"\"position\":{\"line\":%d,\"character\":%d}}}",
lsp->next_id++, buf->filename, line, col);
lsp_send(lsp->write_fd, msg);
bFree(msg);
free(msg);
}
void lspShutdown(LspClient* lsp)
void lspShutdown(LspClient *lsp)
{
if (!lsp || lsp->state == LSP_SHUTDOWN) return;
lsp->state = LSP_SHUTDOWN;
// 1. Send shutdown request (clangd expects this before exit)
cJSON* req = cJSON_CreateObject();
// 1. Send didClose for all open buffers
for (int i = 0; i < E.number_of_buffer; i++) {
if (E.buffers[i].b_lsp_open)
lspDidClose(lsp, &E.buffers[i]);
}
// 2. Send shutdown request (clangd expects this before exit)
cJSON *req = cJSON_CreateObject();
cJSON_AddStringToObject(req, "jsonrpc", "2.0");
cJSON_AddNumberToObject(req, "id", lsp->next_id++);
cJSON_AddStringToObject(req, "method", "shutdown");
cJSON_AddNullToObject(req, "params");
char* msg = cJSON_PrintUnformatted(req);
cJSON_AddNumberToObject(req, "id", lsp->next_id++);
cJSON_AddStringToObject(req, "method", "shutdown");
cJSON_AddNullToObject (req, "params");
char *msg = cJSON_PrintUnformatted(req);
lsp_send(lsp->write_fd, msg);
bFree(msg);
free(msg);
cJSON_Delete(req);
// 2. Wait briefly for the shutdown response
// (don't block forever — clangd has 2s to reply)
struct timeval tv = {.tv_sec = 2, .tv_usec = 0};
// 3. Wait briefly for the shutdown response (2s timeout)
struct timeval tv = { .tv_sec = 2, .tv_usec = 0 };
fd_set fds;
FD_ZERO(&fds);
FD_SET(lsp->read_fd, &fds);
if (select(lsp->read_fd + 1, &fds, NULL, NULL, &tv) > 0)
{
char* resp = lsp_recv(lsp->read_fd);
bFree(resp);
if (select(lsp->read_fd + 1, &fds, NULL, NULL, &tv) > 0) {
char *resp = lsp_recv(lsp->read_fd);
free(resp);
}
// 3. Send exit notification
// 4. Send exit notification
lsp_send(lsp->write_fd,
"{\"jsonrpc\":\"2.0\",\"method\":\"exit\",\"params\":null}");
"{\"jsonrpc\":\"2.0\",\"method\":\"exit\",\"params\":null}");
// 4. Close pipes — this signals the reader thread to stop
// 5. Close write pipe first — reader thread will get EOF and exit
close(lsp->write_fd);
close(lsp->read_fd);
lsp->write_fd = -1;
// 5. Wait for reader thread to finish
// 6. Wake the main loop so it doesn't stay blocked in select()
write(lsp->wake_pipe[1], "q", 1);
// 7. Wait for reader thread to finish
pthread_join(lsp->reader_thread, NULL);
pthread_mutex_destroy(&lsp->lock);
// 6. Reap the clangd process
// 8. Close remaining fds
close(lsp->read_fd);
lsp->read_fd = -1;
close(lsp->wake_pipe[0]);
close(lsp->wake_pipe[1]);
// 9. Destroy synchronization primitives
pthread_mutex_destroy(&lsp->lock);
pthread_cond_destroy (&lsp->ready_cond);
// 10. Reap the clangd process
waitpid(lsp->pid, NULL, 0);
bFree(lsp);
free(lsp);
}
+4 -3
View File
@@ -8,7 +8,6 @@
#include "../include/split_screen.h"
#include "../include/terminal.h"
#include "../include/utf8.h"
#include "include/utils.h"
extern struct editorConfig E;
@@ -74,6 +73,8 @@ int editorMoveCursor(int key) {
buf->x = buf->row[buf->y].size;
}
break;
default:
break;
}
return 1;
}
@@ -84,13 +85,13 @@ char *editorGetClipboard(void) {
size_t cap = 4096;
size_t len = 0;
char *buf = bAlloc(cap);
char *buf = malloc(cap);
int c;
while ((c = fgetc(pipe)) != EOF) {
if (len + 1 >= cap) {
cap *= 2;
buf = bRealloc(buf, cap);
buf = realloc(buf, cap);
}
buf[len++] = (char)c;
}
+8 -12
View File
@@ -17,13 +17,9 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <errno.h>
#include "../include/utils.h"
extern struct editorConfig E;
/**
* @brief Closes the current file and resets editor state
@@ -39,13 +35,13 @@ void editorCloseFile(void) {
active->x_offset = 0;
active->y_offset = 0;
for (int i = 0; i < buf->numrows; ++i) {
bFree(buf->row[i].chars);
free(buf->row[i].chars);
}
buf->numrows = 0;
bFree(buf->row);
free(buf->row);
buf->row = NULL;
buf->dirty = 0;
bFree(buf->filename);
free(buf->filename);
buf->filename = NULL;
E.status_msg[0] = '\0';
E.status_msg_time = 0;
@@ -56,7 +52,7 @@ void editorCloseFile(void) {
* @details Loads file content into editor rows, one line per row. If another
* file is already open, it is closed first (without saving). File is opened in
* a+ (read/append) mode to allow both reading and modification.
* @param filename Path to the file to open (relative or absolute)
* @param buffer Path to the file to open (relative or absolute)
* @note Updates global editor state E
* @note Calls die() on file open failure
* @note Newline characters are stripped from loaded lines
@@ -88,10 +84,10 @@ void editorOpen(struct buffer_t* buffer) {
}
appDebug("line %s\n", line);
bufferInsertRow(buffer, buffer->numrows, line, line_len);
bFree(line);
free(line);
line = NULL;
}
bFree(line);
free(line);
fclose(fp);
E.dirty = 0;
}
@@ -118,11 +114,11 @@ void editorSave() {
return;
}
}
fd = open(buffer->filename, O_RDWR | O_CREAT, 0644);
fd = open(buffer->fullname, O_RDWR | O_CREAT, 0644);
if (fd != -1) {
for (int i = 0; i < buffer->numrows; ++i)
{
len = strlen(buffer->row[i].chars);
len = (int) strlen(buffer->row[i].chars);
if (write(fd, buffer->row[i].chars, len) != len) {
close(fd);
editorSetStatusMessage("Can't save! I/O error: %s", strerror(errno));
+20 -4
View File
@@ -11,7 +11,6 @@
#define LISP_IMPLEMENTATION
#include "../include/lisp.h"
#include "../include/lisp_lib.h"
#include "include/utils.h"
struct editorConfig;
@@ -75,6 +74,8 @@ void initConfig() {
void initTheme() {
E.constantes.THEME = (char *)lisp_string(
lisp_eval(lisp_read("THEME", &E.ctx_error, E.ctx), &E.ctx_error, E.ctx));
E.constantes.LSP = lisp_bool(lisp_eval(lisp_read("LSP", &E.ctx_error, E.ctx), &E.ctx_error, E.ctx));
appDebug("LSP ON : %d", E.constantes.LSP);
if (strcmp(E.constantes.THEME, "dark") == 0) {
E.theme.BACKGROUND_COLOR = ANSI_BG_RGB(40, 44, 52);
E.theme.COLOR_KEYWORD = ANSI_FG_RGB(198, 120, 221);
@@ -99,7 +100,7 @@ void initEditor() {
if (getWindowSize(&E.screenrows, &E.screencols) == -1) {
die("getWindowSize");
}
appDebug("%d %d\n", E.screenrows, E.screencols);
appDebug("%d %d", E.screenrows, E.screencols);
E.screenrows -= 2;
@@ -131,12 +132,13 @@ void initEditor() {
E.number_of_keybinds = 0;
E.number_of_prefix = 0;
// General prefix is 0 (no prefix)
E.prefix = (struct prefix_t *)bAlloc(sizeof(struct prefix_t));
E.prefix = (struct prefix_t *)malloc(sizeof(struct prefix_t));
E.prefix[0].prefix_id = 0;
strncpy(E.prefix[0].prefix_name, "no-prefix", 64);
E.prefix_state = 0;
E.lsp_client = (LspClient*)bAlloc(sizeof(LspClient));
E.lsp_client = (LspClient*)malloc(sizeof(LspClient));
E.lsp_client->state = LSP_SHUTDOWN;
initConfig();
initTheme();
@@ -154,3 +156,17 @@ void initEditor() {
E.quit_times_buffer = E.constantes.QUIT_TIMES;
}
void deInitEditor()
{
freeScreenLayout(&E.layout);
free(E.lsp_client);
free(E.status_msg);
free(E.init_file_path);
free(E.key_binds);
for (int i = 0; i < E.number_of_keybinds; i++)
{
free(E.key_binds[i].key_sequence);
}
}
+71 -62
View File
@@ -2,32 +2,26 @@
#include "../include/define.h"
#include "../include/editor_op.h"
#include "../include/output.h"
#include "include/data.h"
#include "include/buffer.h"
#include "include/builtins.h"
#include "../include/completion.h"
#include "include/data.h"
#include "include/split_screen.h"
#include "include/completion.h"
#include "include/lsp_ui.h"
#include <ctype.h>
#include <sys/stat.h>
#include <dirent.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include "include/terminal.h"
#include "include/utf8.h"
#include "include/utils.h"
extern struct editorConfig E;
/**
* @file input.c
* @brief Input handling module for the Beluga text editor
* @details Manages user input processing, key bindings, cursor movement, and file path completion
* @details Manages user input processing, key bindings, cursor movement, and
* file path completion
*/
/**
@@ -36,7 +30,8 @@ extern struct editorConfig E;
* the first file or directory entry that matches the filename prefix.
* Appends a trailing slash for directory entries.
* @param path The file path to complete (can be relative or absolute)
* @return Pointer to the completed file path (dynamically allocated), or NULL if:
* @return Pointer to the completed file path (dynamically allocated), or NULL
* if:
* - path ends with '/' (already a directory)
* - no matching entries found
* - directory cannot be opened
@@ -63,7 +58,7 @@ const char *fileCompletion(const char *path) {
if (last_slash) {
dir_len = last_slash - path + 1; // length of dir_path
strncpy(directory, path, dir_len);
predict_len = strlen(path) - dir_len;
predict_len = (int)(strlen(path) - dir_len);
strncpy(predict, last_slash + 1, predict_len);
directory[dir_len] = '\0';
predict[predict_len] = '\0';
@@ -95,16 +90,16 @@ const char *fileCompletion(const char *path) {
// Cleanup when no more entries
closedir(dir);
dir = NULL;
bFree(entry);
free(entry);
appDebug("[FILE COMP] no entries\n");
return strdup(path);
}
/**
* @brief Displays an interactive prompt and returns user input
* @details Allows the user to enter text in a prompt with optional path completion
* via Tab key. Supports backspace, delete, and escape key handling. Dynamically
* allocates memory for the input buffer.
* @details Allows the user to enter text in a prompt with optional path
* completion via Tab key. Supports backspace, delete, and escape key handling.
* Dynamically allocates memory for the input buffer.
* @param prompt The prompt message format string (printf-style)
* @param placeHolder Initial text to display in the input buffer
* @param bPathMode If non-zero, enables Tab key file path completion
@@ -117,7 +112,7 @@ const char *fileCompletion(const char *path) {
char *editorPrompt(char *prompt, char *placeHolder, char bPathMode) {
size_t buf_size = 256;
appDebug("[FILE COMP] %s %d\n", placeHolder, strlen(placeHolder));
char *buf = bAlloc(buf_size);
char *buf = malloc(buf_size);
size_t buf_len = 0;
int c = 0;
buf[0] = '\0';
@@ -134,7 +129,7 @@ char *editorPrompt(char *prompt, char *placeHolder, char bPathMode) {
}
} else if (c == ESCAPE) {
editorSetStatusMessage("");
bFree(buf);
free(buf);
return NULL;
} else if (c == '\r') {
if (buf_len != 0) {
@@ -154,26 +149,23 @@ char *editorPrompt(char *prompt, char *placeHolder, char bPathMode) {
strcpy(path, buf);
}
memset(buf, 0, 256);
buf_len = 0;
char * buf_complete = (char *) fileCompletion(path);
char *buf_complete = (char *)fileCompletion(path);
strcpy(buf, buf_complete);
bFree(buf_complete);
free(buf_complete);
buf_len = strlen(buf);
buf[buf_len] = '\0';
} else if (!iscntrl(c) && c < 256) {
if (buf_len == buf_size - 1) {
buf_size *= 2;
buf = bRealloc(buf, buf_size);
buf = realloc(buf, buf_size);
}
buf[buf_len++] = c;
buf[buf_len++] = (char)c;
buf[buf_len] = '\0';
}
}
}
/**
* @brief Executes the command bound to a key sequence
* @details Searches the keybinding table for a matching key sequence and
@@ -210,56 +202,63 @@ int executeKeyBind(char *key_sequence) {
* and either executes the bound command or inserts the character. Resets
* the quit buffer counter on successful key processing.
* @note Updates global editor state E
* @note Calls editorReadKey() to get input and editorInsertChar() for unbound keys
* @note Calls editorReadKey() to get input and editorInsertChar() for unbound
* keys
*/
void editorProcessKeypress() {
int c = editorReadKey();
char key_sequence[8];
EditorPane *active = splitScreenGetActivePane();
struct buffer_t *buf = bufferFindById(active->buffer_id);
if (E.lsp_client && E.lsp_completion.visible) {
if (c == ARROW_UP || c == CTRL_KEY('p')) {
if (E.lsp_completion.selected > 0)
E.lsp_completion.selected--;
return; // consumed, redraw on next loop
}
if (c == ARROW_DOWN || c == CTRL_KEY('n')) {
if (E.lsp_completion.selected < E.lsp_completion.count - 1)
E.lsp_completion.selected++;
if (E.constantes.LSP && buf->b_lsp_open) {
if (c == LSP_WAKE_KEY)
return;
}
if (c == '\r') {
CompletionItem *item = &E.lsp_completion.items[E.lsp_completion.selected];
EditorPane *active = splitScreenGetActivePane();
struct buffer_t *buf = bufferFindById(active->buffer_id);
if (E.lsp_client && E.lsp_completion.visible) {
if (c == ARROW_UP || c == CTRL_KEY('p')) {
if (E.lsp_completion.selected > 0)
E.lsp_completion.selected--;
return; // consumed, redraw on next loop
}
if (c == ARROW_DOWN || c == CTRL_KEY('n')) {
if (E.lsp_completion.selected < E.lsp_completion.count - 1)
E.lsp_completion.selected++;
return;
}
if (c == '\r') {
CompletionItem *item =
&E.lsp_completion.items[E.lsp_completion.selected];
// Find how many chars the user already typed by looking at the
// current word (chars before cursor on the same line)
int file_col = active->cursor_x + active->x_offset;
row_t *row = &buf->row[active->cursor_y + active->y_offset];
// Walk backwards from cursor to find start of current word
int word_start = file_col;
while (word_start > 0 &&
(isalnum((unsigned char)row->chars[word_start - 1]) ||
row->chars[word_start - 1] == '_'))
word_start--;
// Find how many chars the user already typed by looking at the
// current word (chars before cursor on the same line)
int file_col = active->cursor_x + active->x_offset;
row_t *row = &buf->row[active->cursor_y + active->y_offset];
int already_typed = file_col - word_start; // chars user already typed
// Walk backwards from cursor to find start of current word
int word_start = file_col;
while (word_start > 0 &&
(isalnum((unsigned char)row->chars[word_start - 1]) ||
row->chars[word_start - 1] == '_'))
word_start--;
// Insert only the suffix — what comes after what's already typed
const char *suffix = item->label + already_typed;
for (int i = 0; suffix[i]; i++)
bufferInsertBytes(&suffix[i], 1);
int already_typed = file_col - word_start; // chars user already typed
// Insert only the suffix — what comes after what's already typed
const char *suffix = item->label + already_typed;
for (int i = 0; suffix[i]; i++)
bufferInsertBytes(&suffix[i], 1);
E.lsp_completion.visible = 0;
return;
}
if (c == ESCAPE) {
E.lsp_completion.visible = 0;
return;
}
// Any other key: dismiss popup and fall through to normal handling
E.lsp_completion.visible = 0;
return;
}
if (c == ESCAPE) {
E.lsp_completion.visible = 0;
return;
}
// Any other key: dismiss popup and fall through to normal handling
E.lsp_completion.visible = 0;
}
if (executeKeyBind(keyToString(c))) {
@@ -268,5 +267,15 @@ void editorProcessKeypress() {
int seq_len = utf8Encode(c, key_sequence);
appDebug("key seq : %s\n", key_sequence);
bufferInsertBytes(key_sequence, seq_len);
if (buf->b_lsp_open && is_word_char(key_sequence)) {
if (E.lsp_client && E.lsp_client->state == LSP_READY) {
lspDidChange(E.lsp_client, buf);
E.lsp_client->completion_just_arrived = 0; // consume the flag
}
buf->b_has_changed = 0;
editorAutoComplete(lisp_null(), &E.ctx_error, E.ctx);
}
E.quit_times_buffer = E.constantes.QUIT_TIMES;
}
+21 -15
View File
@@ -5,12 +5,12 @@
#include "include/lsp_ui.h"
#include "include/data.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// We use cJSON — drop cJSON.c + cJSON.h into src/ and include/
#include "include/cJSON.h"
#include "include/append_buffer.h"
#include "include/terminal.h"
// ─── ANSI helpers ─────────────────────────────────────────────────────────────
@@ -73,7 +73,7 @@ static const char *kind_color(int k) {
// editorRefreshScreen() before the final write().
void lspUiDrawCompletion(struct abuf *ab, CompletionPopup *popup) {
fprintf(stderr, "[DRAW] visible=%d count=%d origin=(%d,%d)\n",
appDebug("[DRAW] visible=%d count=%d origin=(%d,%d)\n",
popup->visible, popup->count,
popup->origin_x, popup->origin_y);
if (!popup->visible || popup->count == 0) return;
@@ -104,7 +104,7 @@ void lspUiDrawCompletion(struct abuf *ab, CompletionPopup *popup) {
if (is_sel) ab_sgr(ab, "7"); // reverse video (highlight)
else ab_sgr(ab, "0;37;40");
abAppend(ab, " ", 2);
abAppend(ab, "| ", 2);
// kind tag in color
if (!is_sel) ab_sgr(ab, kind_color(it->kind));
@@ -131,7 +131,7 @@ void lspUiDrawCompletion(struct abuf *ab, CompletionPopup *popup) {
AB_RESET(ab);
if (is_sel) ab_sgr(ab, "7");
else ab_sgr(ab, "37;40");
abAppend(ab, " ", 2);
abAppend(ab, " |", 2);
AB_RESET(ab);
}
@@ -162,12 +162,8 @@ int lspUiHandleKey(CompletionPopup *popup, int key) {
if (!popup->visible) return 0;
switch (key) {
case '\x1b': // ESC — dismiss
popup->visible = 0;
return 1;
case '\r': // Enter — accept
// Caller should insert popup->items[popup->selected].label
case '\x1b':
case '\r': // ESC — dismiss
popup->visible = 0;
return 1;
@@ -248,14 +244,13 @@ void lspParseCompletion(const char *json, CompletionPopup *popup,
int screen_x, int screen_y) {
popup->count = 0;
popup->selected = 0;
popup->origin_x = screen_x;
popup->origin_y = screen_y + 1; // one row below cursor
popup->origin_x = screen_x + 1;
popup->origin_y = screen_y + 2; // one row below cursor
cJSON *root = cJSON_Parse(json);
if (!root) return;
cJSON *result = cJSON_GetObjectItem(root, "result");
if (!result) { cJSON_Delete(root); return; }
// result can be a list or {isIncomplete, items:[…]}
cJSON *items = cJSON_IsArray(result)
? result
@@ -276,7 +271,11 @@ void lspParseCompletion(const char *json, CompletionPopup *popup,
strncpy(ci->label, raw_label, 127);
strncpy(ci->detail, detail ? detail->valuestring : "", 63);
ci->kind = kind ? kind->valueint : 0;
if (!kind)
ci->kind = 0;
else
ci->kind = kind->valueint;
}
popup->visible = (popup->count > 0);
@@ -317,7 +316,14 @@ void lspParseDiagnostics(const char *json, DiagnosticList *diags,
diag->col_end = cJSON_GetObjectItem(end_pos, "character")->valueint;
diag->severity = sev ? (DiagSeverity)sev->valueint : DIAG_ERROR;
strncpy(diag->message, msg ? msg->valuestring : "", 255);
const char *raw = msg ? msg->valuestring : "";
int i = 0;
while (raw[i] && raw[i] != '\n' && i < 255)
{
diag->message[i] = raw[i];
i++;
}
diag->message[i] = '\0';
}
cJSON_Delete(root);
+52 -75
View File
@@ -21,11 +21,6 @@
#include <string.h>
#include <time.h>
#include "include/completion.h"
#include "include/utils.h"
extern struct editorConfig E;
/**
* @brief Renders a single pane with its buffer content
*/
@@ -74,7 +69,10 @@ static void editorDrawPane(struct abuf* ab, EditorPane* pane)
}
else
{
lspUiDrawGutter(ab, &E.lsp_diagnostics, pane->buffer_id, file_row);
if (E.constantes.LSP) {
lspUiDrawGutter(ab, &E.lsp_diagnostics, pane->buffer_id, file_row);
}
if (buf->filename[strlen(buf->filename) - 1] == 'c' || buf->filename[strlen(buf->filename) - 1] == 'h')
{
@@ -84,7 +82,7 @@ static void editorDrawPane(struct abuf* ab, EditorPane* pane)
// Print only up to pane width
abAppend(ab, highlighted, byte_len_to_print);
bFree(highlighted);
free(highlighted);
}
else
{
@@ -304,11 +302,8 @@ void editorDrawStatusBar(struct abuf* ab)
abAppend(ab, render_status, render_len);
break;
}
else
{
abAppend(ab, " ", 1);
++len;
}
abAppend(ab, " ", 1);
++len;
}
abAppend(ab, "\x1b[m", 3); // normal text mode
@@ -336,36 +331,6 @@ void editorDrawMessageBar(struct abuf* ab)
}
}
void editorDrawContextBuffer(struct abuf* ab)
{
int pos_len;
char pos_buf[1024];
int i, j;
if (!E.context_buffers)
return;
appDebug("Printing context");
for (i = 0; i < E.context_buffers->height; ++i)
{
if (E.context_buffers->editor_y + i + 1 > 0)
{
pos_len = snprintf(pos_buf, sizeof(pos_buf), "\x1b[%d;%dH",
E.context_buffers->editor_y + i + 1, E.context_buffers->editor_x - 2);
abAppend(ab, pos_buf, pos_len);
// Apply background color (6 bytes for RGB format)
abAppend(ab, E.theme.BACKGROUND_COLOR, (int)strlen(E.theme.BACKGROUND_COLOR));
abAppend(ab, "|", 1);
abAppend(ab, E.context_buffers->rows->chars, E.context_buffers->rows->size);
abAppend(ab, "|", 1);
}
}
bFree(E.context_buffers);
E.context_buffers = NULL;
}
/**
* @brief Performs complete screen refresh and buffer synchronization
* @details Clears screen, redraws all visible content (rows, status bar,
@@ -388,50 +353,62 @@ void editorRefreshScreen()
(int)strlen(E.theme.BACKGROUND_COLOR));
editorScroll();
EditorPane* active = splitScreenGetActivePane();
struct buffer_t* buffer = bufferFindById(active->buffer_id);
editorDrawAllPanes(&ab);
if (E.constantes.LSP) {
// ── LSP: draw completion popup every frame while visible ──────────────────
appDebug("[REFRESH] lsp_completion.visible=%d\n",
E.lsp_completion.visible);
while (E.lsp_client->completion_requested && !E.lsp_client->completion_just_arrived);
// reset flags
E.lsp_client->completion_just_arrived = 0;
E.lsp_client->completion_requested = 0;
// ── LSP: diagnostic for current line in status bar ────────────────────────
const char* diag = lspUiDiagnosticAtCursor(
&E.lsp_diagnostics,
active->buffer_id,
buffer->y);
if (diag) {
char single_line[512];
int i = 0;
// Copy until newline, \0, or screen width
while (diag[i] && diag[i] != '\n' && i < E.screencols - 4)
{
single_line[i] = diag[i];
i++;
}
// If message was truncated, add ellipsis
if (diag[i] != '\0' && diag[i] != '\n')
{
single_line[i++] = '.';
single_line[i++] = '.';
single_line[i++] = '.';
}
single_line[i] = '\0';
editorSetStatusMessage("● %s", single_line);
}
}
editorDrawStatusBar(&ab);
editorDrawMessageBar(&ab);
EditorPane *active = splitScreenGetActivePane();
struct buffer_t *buffer = bufferFindById(active->buffer_id);
// ── LSP: sync buffer changes to clangd ────────────────────────────────────
if (buffer->b_has_changed) {
if (E.lsp_client && E.lsp_client->state == LSP_READY) {
lspDidChange(E.lsp_client, buffer);
E.lsp_client->completion_just_arrived = 0; // consume the flag
}
buffer->b_has_changed = 0;
}
// ── LSP: draw completion popup every frame while visible ──────────────────
fprintf(stderr, "[REFRESH] lsp_completion.visible=%d\n",
E.lsp_completion.visible);
while (E.lsp_client->completion_requested && !E.lsp_client->completion_just_arrived)
;
// reset flags
E.lsp_client->completion_just_arrived = 0;
E.lsp_client->completion_requested = 0;
if (E.lsp_client && E.lsp_client->state == LSP_READY)
if (E.constantes.LSP && (E.lsp_client && E.lsp_client->state == LSP_READY))
{
lspUiDrawCompletion(&ab, &E.lsp_completion);
appDebug("ready\n");
}
// ── LSP: diagnostic for current line in status bar ────────────────────────
const char *diag = lspUiDiagnosticAtCursor(
&E.lsp_diagnostics,
active->buffer_id,
active->cursor_y + active->y_offset);
if (diag)
editorSetStatusMessage("● %s", diag);
// ── Position cursor (account for gutter width) ────────────────────────────
snprintf(buf, sizeof(buf), "\x1b[%d;%dH",
active->cursor_y + active->origin_y + 1,
active->cursor_x + active->origin_x + 1 + GUTTER_WIDTH);
active->cursor_x + active->origin_x + 1 + (E.constantes.LSP ? GUTTER_WIDTH : 0));
abAppend(&ab, buf, (int)strlen(buf));
abAppend(&ab, SHOW_CURSOR, 6);
+13 -4
View File
@@ -9,7 +9,6 @@
#include <stdlib.h>
#include <string.h>
#include "include/utils.h"
extern struct editorConfig E;
@@ -21,7 +20,7 @@ void splitScreenInit(void) {
E.layout.num_panes = 1;
E.layout.active_pane = 0;
E.layout.panes = bAlloc(sizeof(EditorPane) * 2);
E.layout.panes = malloc(sizeof(EditorPane) * 2);
// Initialize single fullscreen pane
E.layout.panes[0].buffer_id = -1; // No buffer for now
@@ -51,7 +50,7 @@ int splitScreenVertical(int buffer_id_left, int buffer_id_right) {
}
// bReallocate panes array
E.layout.panes = bRealloc(E.layout.panes, sizeof(EditorPane) * 2);
E.layout.panes = realloc(E.layout.panes, sizeof(EditorPane) * 2);
E.layout.mode = SPLIT_VERTICAL;
E.layout.num_panes = 2;
E.layout.active_pane = 0;
@@ -102,7 +101,7 @@ int splitScreenHorizontal(int buffer_id_top, int buffer_id_bottom) {
}
// bReallocate panes array
E.layout.panes = bRealloc(E.layout.panes, sizeof(EditorPane) * 2);
E.layout.panes = realloc(E.layout.panes, sizeof(EditorPane) * 2);
E.layout.mode = SPLIT_HORIZONTAL;
E.layout.num_panes = 2;
E.layout.active_pane = 0;
@@ -218,3 +217,13 @@ EditorPane *splitScreenGetActivePane(void) {
if (E.layout.num_panes == 0) return NULL;
return &E.layout.panes[E.layout.active_pane];
}
void freeScreenLayout(ScreenLayout *layout)
{
free(layout->panes);
}
void freePane(EditorPane *pane)
{
free(pane);
}
+25 -27
View File
@@ -5,7 +5,6 @@
#include <stdlib.h>
#include <string.h>
#include "include/utils.h"
extern struct editorConfig E;
@@ -34,6 +33,30 @@ static int utf8_char_len(const char *s)
return 1; // continuation byte or invalid — advance 1 to avoid infinite loop
}
int is_word_char(const char *s)
{
uint32_t cp = utf8Decode(&s);
if ((cp >= 'a' && cp <= 'z') || (cp >= 'A' && cp <= 'Z') ||
(cp >= '0' && cp <= '9') || cp == '_' || cp == '#')
return 1;
if (cp == 0xFFFD) return 0;
if (cp >= 0x00C0 && cp <= 0x017F) return 1;
if (cp >= 0x0370 && cp <= 0x03FF) return 1;
if (cp >= 0x0400 && cp <= 0x04FF) return 1;
if (cp >= 0x0600 && cp <= 0x06FF) return 1;
if (cp >= 0x05D0 && cp <= 0x05EA) return 1;
if (cp >= 0x0900 && cp <= 0x097F) return 1;
if (cp >= 0x4E00 && cp <= 0x9FFF) return 1;
if ((cp >= 0x3040 && cp <= 0x309F) ||
(cp >= 0x30A0 && cp <= 0x30FF)) return 1;
if (cp >= 0xAC00 && cp <= 0xD7A3) return 1;
return 0;
}
// Copy one full UTF-8 character from src+i into dst+pos, advance both indices.
static void copy_utf8_char(char *dst, int *dst_pos, const char *src, int *src_pos)
{
@@ -43,31 +66,6 @@ static void copy_utf8_char(char *dst, int *dst_pos, const char *src, int *src_po
}
// Check if character is alphanumeric or underscore
int is_word_char(const char *s)
{
uint32_t cp = utf8Decode(&s);
if ((cp >= 'a' && cp <= 'z') || (cp >= 'A' && cp <= 'Z') ||
(cp >= '0' && cp <= '9') || cp == '_' || cp == '#')
return 1;
if (cp == 0xFFFD) return 0;
if (cp >= 0x00C0 && cp <= 0x017F) return 1;
if (cp >= 0x0370 && cp <= 0x03FF) return 1;
if (cp >= 0x0400 && cp <= 0x04FF) return 1;
if (cp >= 0x0600 && cp <= 0x06FF) return 1;
if (cp >= 0x05D0 && cp <= 0x05EA) return 1;
if (cp >= 0x0900 && cp <= 0x097F) return 1;
if (cp >= 0x4E00 && cp <= 0x9FFF) return 1;
if ((cp >= 0x3040 && cp <= 0x309F) ||
(cp >= 0x30A0 && cp <= 0x30FF)) return 1;
if (cp >= 0xAC00 && cp <= 0xD7A3) return 1;
if ((cp >= 0x0660 && cp <= 0x0669) ||
(cp >= 0x06F0 && cp <= 0x06F9)) return 1;
return 0;
}
// Check if string is a keyword
int is_keyword(const char *word) {
@@ -114,7 +112,7 @@ char *highlight_line(const char *line, int *length) {
// Allocate generously based on line length to avoid overflow.
int line_len = strlen(line);
int buf_size = line_len * 32 + 256;
char *result = bAlloc(buf_size);
char *result = malloc(buf_size);
int result_pos = 0;
int i = 0;
+272 -189
View File
@@ -10,229 +10,312 @@
#include <string.h>
#include <unistd.h>
#include "include/utf8.h"
#include "../include/buffer.h"
#include "../include/split_screen.h"
#include "../include/utf8.h"
void die(const char *s) {
write(STDOUT_FILENO, "\x1b[2J", 4);
write(STDOUT_FILENO, CURSOR_TOP_LEFT, 3);
lisp_shutdown(E.ctx);
perror(s);
exit(1);
void die(const char* s)
{
write(STDOUT_FILENO, "\x1b[2J", 4);
write(STDOUT_FILENO, CURSOR_TOP_LEFT, 3);
lisp_shutdown(E.ctx);
perror(s);
exit(1);
}
void disableRawMode() {
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &E.orig_termios) == -1) {
die("tcsetattr");
}
void disableRawMode()
{
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &E.orig_termios) == -1)
{
die("tcsetattr");
}
}
void enableRawMode() {
if (tcgetattr(STDIN_FILENO, &E.orig_termios) == -1) {
die("tcgetattr");
}
void enableRawMode()
{
if (tcgetattr(STDIN_FILENO, &E.orig_termios) == -1)
{
die("tcgetattr");
}
struct termios raw = E.orig_termios;
raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
raw.c_oflag &= ~(OPOST);
raw.c_cflag |= (CS8);
raw.c_lflag &= ~(ECHO | ICANON | ISIG | IEXTEN);
raw.c_cc[VMIN] = 0;
raw.c_cc[VTIME] = 1;
struct termios raw = E.orig_termios;
raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
raw.c_oflag &= ~(OPOST);
raw.c_cflag |= (CS8);
raw.c_lflag &= ~(ECHO | ICANON | ISIG | IEXTEN);
raw.c_cc[VMIN] = 0;
raw.c_cc[VTIME] = 1;
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) == -1) {
die("tcgetattr");
}
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) == -1)
{
die("tcgetattr");
}
}
#include <ctype.h> /* isprint */
char *keyToString(int key) {
static char key_str[32];
char* keyToString(int key)
{
static char key_str[32];
if (key == '\r') {
strcpy(key_str, "ENTER");
} else if (key == 0x09) {
strcpy(key_str, "TAB");
} else if (key >= 1 && key <= 26) {
snprintf(key_str, sizeof(key_str), "CTRL-%c", 'a' + key - 1);
} else {
switch (key) {
case ARROW_UP:
strcpy(key_str, "ARROW-UP");
break;
case ARROW_DOWN:
strcpy(key_str, "ARROW-DOWN");
break;
case ARROW_LEFT:
strcpy(key_str, "ARROW-LEFT");
break;
case ARROW_RIGHT:
strcpy(key_str, "ARROW-RIGHT");
break;
case PAGE_UP:
strcpy(key_str, "PAGE-UP");
break;
case PAGE_DOWN:
strcpy(key_str, "PAGE-DOWN");
break;
case DEL_KEY:
strcpy(key_str, "DEL");
break;
case BACKSPACE:
strcpy(key_str, "BACKSPACE");
break;
case BEG_LINE:
strcpy(key_str, "HOME");
break;
case END_LINE:
strcpy(key_str, "END");
break;
case '\x1b':
strcpy(key_str, "ESCAPE");
break;
default:
if (key > 127) {
/* UTF-8 code point — re-encode into the buffer */
char buf[5] = {0};
int n = utf8Encode((uint32_t)key, buf);
snprintf(key_str, sizeof(key_str), "%.*s", n, buf);
} else if (isprint(key)) {
snprintf(key_str, sizeof(key_str), "%c", key);
} else {
snprintf(key_str, sizeof(key_str), "KEY-%d", key);
}
if (key == '\r')
{
strcpy(key_str, "ENTER");
}
}
return key_str;
}
int editorReadKey() {
char c;
/* read first byte — may be start of UTF-8 or escape */
while (read(STDIN_FILENO, &c, 1) != 1)
;
appDebug("f : %hhu %ld\r\n", c, 0x200);
if (c == '\x1b') {
char seq[6];
/* try to read escape sequence */
if (read(STDIN_FILENO, &seq[0], 1) != 1)
return '\x1b';
if (read(STDIN_FILENO, &seq[1], 1) != 1)
return '\x1b';
appDebug("f2 : %s\r\n", seq);
if (seq[0] == '[') {
if (seq[1] >= '0' && seq[1] <= '9') {
if (read(STDIN_FILENO, &seq[2], 1) != 1)
return '\x1b';
if (seq[2] == '~') {
switch (seq[1]) {
case '1':
return BEG_LINE;
case '3':
return DEL_KEY;
case '4':
return END_LINE;
case '5':
return PAGE_UP;
case '6':
return PAGE_DOWN;
case '7':
return BEG_LINE;
case '8':
return END_LINE;
}
else if (key == 0x09)
{
strcpy(key_str, "TAB");
}
else if (key >= 1 && key <= 26)
{
snprintf(key_str, sizeof(key_str), "CTRL-%c", 'a' + key - 1);
}
else
{
switch (key)
{
case ARROW_UP:
strcpy(key_str, "ARROW-UP");
break;
case ARROW_DOWN:
strcpy(key_str, "ARROW-DOWN");
break;
case ARROW_LEFT:
strcpy(key_str, "ARROW-LEFT");
break;
case ARROW_RIGHT:
strcpy(key_str, "ARROW-RIGHT");
break;
case PAGE_UP:
strcpy(key_str, "PAGE-UP");
break;
case PAGE_DOWN:
strcpy(key_str, "PAGE-DOWN");
break;
case DEL_KEY:
strcpy(key_str, "DEL");
break;
case BACKSPACE:
strcpy(key_str, "BACKSPACE");
break;
case BEG_LINE:
strcpy(key_str, "HOME");
break;
case END_LINE:
strcpy(key_str, "END");
break;
case '\x1b':
strcpy(key_str, "ESCAPE");
break;
default:
if (key > 127)
{
/* UTF-8 code point — re-encode into the buffer */
char buf[5] = {0};
int n = utf8Encode((uint32_t)key, buf);
snprintf(key_str, sizeof(key_str), "%.*s", n, buf);
}
else if (isprint(key))
{
snprintf(key_str, sizeof(key_str), "%c", key);
}
else
{
snprintf(key_str, sizeof(key_str), "KEY-%d", key);
}
}
} else {
switch (seq[1]) {
case 'A':
return ARROW_UP;
case 'B':
return ARROW_DOWN;
case 'C':
return ARROW_RIGHT;
case 'D':
return ARROW_LEFT;
case 'H':
return BEG_LINE;
case 'F':
return END_LINE;
}
return key_str;
}
int editorReadKey()
{
char c;
int nread;
while (1)
{
fd_set fds;
FD_ZERO(&fds);
FD_SET(STDIN_FILENO, &fds);
int max_fd = STDIN_FILENO;
// Only watch wake pipe if LSP is ready AND active buffer is open
EditorPane* active = splitScreenGetActivePane();
struct buffer_t* buf = active ? bufferFindById(active->buffer_id) : NULL;
int lsp_active = E.lsp_client
&& E.lsp_client->wake_pipe[0] > 0
&& E.lsp_client->state == LSP_READY
&& buf
&& buf->b_lsp_open; // ← only if this buffer is tracked
if (lsp_active)
{
FD_SET(E.lsp_client->wake_pipe[0], &fds);
if (E.lsp_client->wake_pipe[0] > max_fd)
max_fd = E.lsp_client->wake_pipe[0];
}
int ready = select(max_fd + 1, &fds, NULL, NULL, NULL);
if (ready <= 0) continue;
if (lsp_active && FD_ISSET(E.lsp_client->wake_pipe[0], &fds))
{
char tmp[16];
read(E.lsp_client->wake_pipe[0], tmp, sizeof(tmp));
return LSP_WAKE_KEY;
}
if (FD_ISSET(STDIN_FILENO, &fds))
{
nread = read(STDIN_FILENO, &c, 1);
if (nread == 1) break;
}
}
}
return '\x1b';
}
/* multi-byte UTF-8: read remaining bytes */
int seqlen = utf8Seqlen((unsigned char)c);
if (seqlen > 1) {
/* pack into a pseudo-codepoint just to pass bytes through;
we handle encoding/decoding at the row level */
char buf[4] = {c, 0, 0, 0};
for (int i = 1; i < seqlen; i++)
if (read(STDIN_FILENO, &buf[i], 1) != 1)
break;
/* decode and return as uint32, but we need int — use high range */
const char *p = buf;
uint32_t cp = utf8Decode(&p);
return (int)cp; /* caller re-encodes when inserting */
}
return (unsigned char)c;
appDebug("f : %hhu %ld\r\n", c, 0x200);
if (c == '\x1b')
{
char seq[6];
/* try to read escape sequence */
if (read(STDIN_FILENO, &seq[0], 1) != 1)
return '\x1b';
if (read(STDIN_FILENO, &seq[1], 1) != 1)
return '\x1b';
appDebug("f2 : %s\r\n", seq);
if (seq[0] == '[')
{
if (seq[1] >= '0' && seq[1] <= '9')
{
if (read(STDIN_FILENO, &seq[2], 1) != 1)
return '\x1b';
if (seq[2] == '~')
{
switch (seq[1])
{
case '1':
return BEG_LINE;
case '3':
return DEL_KEY;
case '4':
return END_LINE;
case '5':
return PAGE_UP;
case '6':
return PAGE_DOWN;
case '7':
return BEG_LINE;
case '8':
return END_LINE;
}
}
}
else
{
switch (seq[1])
{
case 'A':
return ARROW_UP;
case 'B':
return ARROW_DOWN;
case 'C':
return ARROW_RIGHT;
case 'D':
return ARROW_LEFT;
case 'H':
return BEG_LINE;
case 'F':
return END_LINE;
}
}
}
return '\x1b';
}
/* multi-byte UTF-8: read remaining bytes */
int seqlen = utf8Seqlen((unsigned char)c);
if (seqlen > 1)
{
/* pack into a pseudo-codepoint just to pass bytes through;
we handle encoding/decoding at the row level */
char buf[4] = {c, 0, 0, 0};
for (int i = 1; i < seqlen; i++)
if (read(STDIN_FILENO, &buf[i], 1) != 1)
break;
/* decode and return as uint32, but we need int — use high range */
const char* p = buf;
uint32_t cp = utf8Decode(&p);
return (int)cp; /* caller re-encodes when inserting */
}
return (unsigned char)c;
}
int getCursorPosition(int *rows, int *cols) {
char buf[32];
unsigned int i = 0;
int getCursorPosition(int* rows, int* cols)
{
char buf[32];
unsigned int i = 0;
if (write(STDOUT_FILENO, "\x1b[6n", 4) != 4) {
return -1;
}
while (i < sizeof(buf) - 1) {
if (read(STDIN_FILENO, &buf[i], 1) != 1) {
break;
if (write(STDOUT_FILENO, "\x1b[6n", 4) != 4)
{
return -1;
}
if (buf[i] == 'R') {
break;
while (i < sizeof(buf) - 1)
{
if (read(STDIN_FILENO, &buf[i], 1) != 1)
{
break;
}
if (buf[i] == 'R')
{
break;
}
++i;
}
++i;
}
buf[i] = '\0';
buf[i] = '\0';
if (buf[0] != '\x1b' || buf[1] != '[') {
return -1;
}
if (sscanf(&buf[2], "%d;%d", rows, cols) != 2) {
return -1;
}
if (buf[0] != '\x1b' || buf[1] != '[')
{
return -1;
}
if (sscanf(&buf[2], "%d;%d", rows, cols) != 2)
{
return -1;
}
return 0;
return 0;
}
int getWindowSize(int *rows, int *cols) {
struct winsize ws;
int getWindowSize(int* rows, int* cols)
{
struct winsize ws;
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0) {
if (write(STDOUT_FILENO, "\x1b[999C\x1b[999B", 12) != 12) {
return -1;
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0)
{
if (write(STDOUT_FILENO, "\x1b[999C\x1b[999B", 12) != 12)
{
return -1;
}
return getCursorPosition(rows, cols);
}
return getCursorPosition(rows, cols);
} else {
*cols = ws.ws_col;
*rows = ws.ws_row;
return 0;
}
}
void appDebug(const char *fmt, ...) {
void appDebug(const char* fmt, ...)
{
#ifdef APP_DEBUG
va_list ap;
char message[256];
va_start(ap, fmt);
vsnprintf(message, 256, fmt, ap);
va_end(ap);
fprintf(stderr, "%s\n", message);
va_list ap;
char message[1024];
va_start(ap, fmt);
vsnprintf(message, 1024, fmt, ap);
va_end(ap);
fprintf(stderr, "%s\n", message);
#endif
}
-38
View File
@@ -1,38 +0,0 @@
//
// Created by Giorgio on 28/05/2026.
//
#include "../include/utils.h"
#include <stdlib.h>
int beluga_alloc_counter = 0;
void * bAlloc(size_t size)
{
void * result = malloc(size);
if (!result)
return NULL;
beluga_alloc_counter++;
return result;
}
void * bRealloc(void * ptr, size_t size)
{
void * result = realloc(ptr, size);
if (!result)
return NULL;
beluga_alloc_counter++;
return result;
}
void * bFree(void * ptr)
{
if (ptr)
{
free(ptr);
beluga_alloc_counter--;
}
return NULL;
}