started the norminette

This commit is contained in:
Maieul BOYER 2024-07-10 15:54:23 +02:00
parent 46e96a2120
commit f4a5c0984e
No known key found for this signature in database
7 changed files with 318 additions and 295 deletions

View file

@ -11,16 +11,16 @@
/* ************************************************************************** */ /* ************************************************************************** */
#ifndef _LINE_FUNCTIONS_H #ifndef _LINE_FUNCTIONS_H
#define _LINE_FUNCTIONS_H # define _LINE_FUNCTIONS_H
#include "line/_line_structs.h"
#include "me/fs/fs.h"
#include "me/types.h"
#include "me/vec/vec_str.h"
# include "line/_line_structs.h"
# include "me/fs/fs.h"
# include "me/types.h"
# include "me/vec/vec_str.h"
t_error line_edit_insert(t_line_state *state, char c); t_error line_edit_insert(t_line_state *state, char c);
t_error line_edit_start(t_line_state *state, t_fd *stdin_fd, t_fd *stdout_fd, t_const_str prompt); t_error line_edit_start(t_line_state *state, t_fd *stdin_fd, t_fd *stdout_fd,
t_const_str prompt);
t_str line_edit_feed(t_line_state *state); t_str line_edit_feed(t_line_state *state);
void line_edit_backspace(t_line_state *state); void line_edit_backspace(t_line_state *state);
void line_edit_delete(t_line_state *state); void line_edit_delete(t_line_state *state);

View file

@ -1,23 +1,23 @@
/* ************************************************************************** */ /* ************************************************************************** */
/* */ /* */
/* ::: :::::::: */ /* ::: :::::::: */
/* _line_interal.h :+: :+: :+: */ /* _line_internal.h :+: :+: :+: */
/* +:+ +:+ +:+ */ /* +:+ +:+ +:+ */
/* By: maiboyer <maiboyer@student.42.fr> +#+ +:+ +#+ */ /* By: maiboyer <maiboyer@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */ /* +#+#+#+#+#+ +#+ */
/* Created: 2024/07/10 15:37:40 by maiboyer #+# #+# */ /* Created: 2024/07/10 15:37:40 by maiboyer #+# #+# */
/* Updated: 2024/07/10 15:38:51 by maiboyer ### ########.fr */ /* Updated: 2024/07/10 15:48:56 by maiboyer ### ########.fr */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
#ifndef _LINE_INTERAL_H #ifndef _LINE_INTERNAL_H
#define _LINE_INTERAL_H # define _LINE_INTERNAL_H
#include "line/_line_functions.h" # include "line/_line_functions.h"
#include "me/fs/fs.h" # include "me/fs/fs.h"
#include "me/string/string.h" # include "me/string/string.h"
#include "me/types.h" # include "me/types.h"
#include "me/vec/vec_str.h" # include "me/vec/vec_str.h"
t_const_str get_unfinished_str(void); t_const_str get_unfinished_str(void);
t_raw_mode_state *get_raw_mode_state(void); t_raw_mode_state *get_raw_mode_state(void);
@ -26,7 +26,8 @@ void free_history(void);
t_error gnl_wrapper(t_fd *fd, t_string *out); t_error gnl_wrapper(t_fd *fd, t_string *out);
void line_uninit_lib(void); void line_uninit_lib(void);
t_error line_get_cursor_position(t_fd *input, t_fd *output, t_u32 *column_out); t_error line_get_cursor_position(t_fd *input, t_fd *output,
t_u32 *column_out);
t_u32 line_get_columns(t_fd *input, t_fd *output); t_u32 line_get_columns(t_fd *input, t_fd *output);
t_usize line_get_prompt_len(t_const_str s); t_usize line_get_prompt_len(t_const_str s);
t_str line_no_tty_impl(void); t_str line_no_tty_impl(void);

View file

@ -6,17 +6,17 @@
/* By: maiboyer <maiboyer@student.42.fr> +#+ +:+ +#+ */ /* By: maiboyer <maiboyer@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */ /* +#+#+#+#+#+ +#+ */
/* Created: 2024/07/10 15:24:34 by maiboyer #+# #+# */ /* Created: 2024/07/10 15:24:34 by maiboyer #+# #+# */
/* Updated: 2024/07/10 15:32:35 by maiboyer ### ########.fr */ /* Updated: 2024/07/10 15:53:54 by maiboyer ### ########.fr */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
#ifndef _LINE_STRUCTS_H #ifndef _LINE_STRUCTS_H
#define _LINE_STRUCTS_H # define _LINE_STRUCTS_H
#include "me/fs/fs.h" # include "me/fs/fs.h"
#include "me/string/string.h" # include "me/string/string.h"
#include "me/types.h" # include "me/types.h"
#include <termios.h> # include <termios.h>
typedef struct s_line_state t_line_state; typedef struct s_line_state t_line_state;
typedef struct s_raw_mode_state t_raw_mode_state; typedef struct s_raw_mode_state t_raw_mode_state;
@ -24,16 +24,24 @@ typedef enum e_line_flags t_line_flags;
typedef enum e_key_action t_key_action; typedef enum e_key_action t_key_action;
typedef enum e_history_direction t_history_direction; typedef enum e_history_direction t_history_direction;
/// @param input_fd Terminal stdin file descriptor.
/// @param output_fd Terminal stdout file descriptor.
/// @param buf Edited line buffer.
/// @param prompt_len Prompt to display.
/// @param pos Prompt length.
/// @param prompt_len Current cursor position.
/// @param columns Number of columns in terminal.
/// @param history_index The history index we are currently editing.
struct s_line_state struct s_line_state
{ {
t_fd *input_fd; /* Terminal stdin file descriptor. */ t_fd *input_fd;
t_fd *output_fd; /* Terminal stdout file descriptor. */ t_fd *output_fd;
t_string buf; /* Edited line buffer. */ t_string buf;
t_const_str prompt; /* Prompt to display. */ t_const_str prompt;
t_usize prompt_len; /* Prompt length. */ t_usize prompt_len;
t_usize pos; /* Current cursor position. */ t_usize pos;
t_usize columns; /* Number of columns in terminal. */ t_usize columns;
t_i32 history_index; /* The history index we are currently editing. */ t_i32 history_index;
}; };
struct s_raw_mode_state struct s_raw_mode_state
@ -44,33 +52,33 @@ struct s_raw_mode_state
enum e_key_action enum e_key_action
{ {
K_KEY_NULL = 0, /* NULL */ K_KEY_NULL = 0,
K_CTRL_A = 1, /* Ctrl+a */ K_CTRL_A = 1,
K_CTRL_B = 2, /* Ctrl-b */ K_CTRL_B = 2,
K_CTRL_C = 3, /* Ctrl-c */ K_CTRL_C = 3,
K_CTRL_D = 4, /* Ctrl-d */ K_CTRL_D = 4,
K_CTRL_E = 5, /* Ctrl-e */ K_CTRL_E = 5,
K_CTRL_F = 6, /* Ctrl-f */ K_CTRL_F = 6,
K_CTRL_H = 8, /* Ctrl-h */ K_CTRL_H = 8,
K_TAB = 9, /* Tab */ K_TAB = 9,
K_NEWLINE = 10, /* Newline */ K_NEWLINE = 10,
K_CTRL_K = 11, /* Ctrl+k */ K_CTRL_K = 11,
K_CTRL_L = 12, /* Ctrl+l */ K_CTRL_L = 12,
K_ENTER = 13, /* Enter */ K_ENTER = 13,
K_CTRL_N = 14, /* Ctrl-n */ K_CTRL_N = 14,
K_CTRL_P = 16, /* Ctrl-p */ K_CTRL_P = 16,
K_CTRL_T = 20, /* Ctrl-t */ K_CTRL_T = 20,
K_CTRL_U = 21, /* Ctrl+u */ K_CTRL_U = 21,
K_CTRL_W = 23, /* Ctrl+w */ K_CTRL_W = 23,
K_ESC = 27, /* Escape */ K_ESC = 27,
K_BACKSPACE = 127 /* Backspace */ K_BACKSPACE = 127
}; };
enum e_line_flags enum e_line_flags
{ {
REFRESH_CLEAN = 1 << 0, // Clean the old prompt from the screen REFRESH_CLEAN = 1 << 0,
REFRESH_WRITE = 1 << 1, // Rewrite the prompt on the screen. REFRESH_WRITE = 1 << 1,
REFRESH_ALL = REFRESH_CLEAN | REFRESH_WRITE, // Do both. REFRESH_ALL = REFRESH_CLEAN | REFRESH_WRITE,
}; };
enum e_history_direction enum e_history_direction

View file

@ -14,9 +14,9 @@
/// https://github.com/antirez/linenoise /// https://github.com/antirez/linenoise
#ifndef LINE_H #ifndef LINE_H
#define LINE_H # define LINE_H
#include "line/_line_functions.h" # include "line/_line_functions.h"
#include "line/_line_structs.h" # include "line/_line_structs.h"
#endif /* LINE_H */ #endif /* LINE_H */

View file

@ -1 +1,2 @@
line line
line_globals

View file

@ -6,21 +6,10 @@
/* By: maiboyer <maiboyer@student.42.fr> +#+ +:+ +#+ */ /* By: maiboyer <maiboyer@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */ /* +#+#+#+#+#+ +#+ */
/* Created: 2024/07/07 16:53:27 by maiboyer #+# #+# */ /* Created: 2024/07/07 16:53:27 by maiboyer #+# #+# */
/* Updated: 2024/07/10 15:41:07 by maiboyer ### ########.fr */ /* Updated: 2024/07/10 15:47:55 by maiboyer ### ########.fr */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <termios.h>
#include <unistd.h>
#include "line/_line_internal.h" #include "line/_line_internal.h"
#include "line/line.h" #include "line/line.h"
#include "me/fs/fs.h" #include "me/fs/fs.h"
@ -31,47 +20,16 @@
#include "me/string/string.h" #include "me/string/string.h"
#include "me/types.h" #include "me/types.h"
#include "me/vec/vec_str.h" #include "me/vec/vec_str.h"
#include <ctype.h>
t_const_str get_unfinished_str(void) #include <errno.h>
{ #include <stdio.h>
return ("If you see this, you are misusing the API: when linenoiseEditFeed() is called, if it returns get_unfinished_str() " #include <stdlib.h>
"the user is yet editing the line. See the README file for more information."); #include <string.h>
} #include <sys/ioctl.h>
#include <sys/stat.h>
t_vec_str *get_history(void) #include <sys/types.h>
{ #include <termios.h>
static t_vec_str history = {}; #include <unistd.h>
static bool init = false;
if (!init)
{
history = vec_str_new(256, (void (*)())mem_free);
init = true;
}
return (&history);
}
t_raw_mode_state *get_raw_mode_state(void)
{
static t_raw_mode_state state = {};
return (&state);
}
/* Free the history, but does not reset it. Only used when we have to
* exit() to avoid memory leaks are reported by valgrind & co. */
void free_history(void)
{
t_vec_str *history = get_history();
vec_str_free(*history);
}
/* At exit we'll try to fix the terminal to the initial conditions. */
__attribute__((destructor)) void line_uninit_lib(void)
{
line_disable_raw_mode(get_stdin());
free_history();
}
#define lndebug(fmt, ...) #define lndebug(fmt, ...)
@ -83,24 +41,23 @@ __attribute__((destructor)) void line_uninit_lib(void)
t_error line_get_cursor_position(t_fd *input, t_fd *output, t_u32 *column_out) t_error line_get_cursor_position(t_fd *input, t_fd *output, t_u32 *column_out)
{ {
char buf[32]; char buf[32];
int cols, rows; unsigned int i;
unsigned int i = 0;
int cols, rows;
i = 0;
/* Report cursor location */ /* Report cursor location */
if (write_fd(output, (t_u8 *)"\x1b[6n", 4, NULL)) if (write_fd(output, (t_u8 *)"\x1b[6n", 4, NULL))
return (ERROR); return (ERROR);
/* Read the response: ESC [ rows ; cols R */ /* Read the response: ESC [ rows ; cols R */
while (i < sizeof(buf) - 1) while (i < sizeof(buf) - 1)
{ {
if (read_fd(input, (t_u8 *)(buf + i), 1, NULL)) if (read_fd(input, (t_u8 *)(buf + i), 1, NULL))
break; break ;
if (buf[i] == 'R') if (buf[i] == 'R')
break; break ;
i++; i++;
} }
buf[i] = '\0'; buf[i] = '\0';
/* Parse it. */ /* Parse it. */
if (buf[0] != K_ESC && buf[1] != '[') if (buf[0] != K_ESC && buf[1] != '[')
return (ERROR); return (ERROR);
@ -123,12 +80,10 @@ t_u32 line_get_columns(t_fd *input, t_fd *output)
/* Get the initial position so we can restore it later. */ /* Get the initial position so we can restore it later. */
if (line_get_cursor_position(input, output, &start)) if (line_get_cursor_position(input, output, &start))
return (80); return (80);
/* Go to right margin and get position. */ /* Go to right margin and get position. */
me_printf_fd(output, "\x1b[999C"); me_printf_fd(output, "\x1b[999C");
if (line_get_cursor_position(input, output, &cols)) if (line_get_cursor_position(input, output, &cols))
return (80); return (80);
if (cols > start) if (cols > start)
{ {
me_printf_fd(output, "\x1b[%dD", cols - start); me_printf_fd(output, "\x1b[%dD", cols - start);
@ -152,12 +107,10 @@ t_error line_enable_raw_mode(t_fd *fd)
t_raw_mode_state *raw_state; t_raw_mode_state *raw_state;
raw_state = get_raw_mode_state(); raw_state = get_raw_mode_state();
if (!isatty(fd->fd)) if (!isatty(fd->fd))
return (errno = ENOTTY, ERROR); return (errno = ENOTTY, ERROR);
if (tcgetattr(fd->fd, &raw_state->state) == -1) if (tcgetattr(fd->fd, &raw_state->state) == -1)
return (errno = ENOTTY, ERROR); return (errno = ENOTTY, ERROR);
raw = raw_state->state; /* modify the original mode */ raw = raw_state->state; /* modify the original mode */
/* input modes: no break, no CR to NL, no parity check, no strip char, /* input modes: no break, no CR to NL, no parity check, no strip char,
* no start/stop output control. */ * no start/stop output control. */
@ -173,7 +126,6 @@ t_error line_enable_raw_mode(t_fd *fd)
* We want read to return every single byte, without timeout. */ * We want read to return every single byte, without timeout. */
raw.c_cc[VMIN] = 1; raw.c_cc[VMIN] = 1;
raw.c_cc[VTIME] = 0; /* 1 byte, no timer */ raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
/* put terminal in raw mode after flushing */ /* put terminal in raw mode after flushing */
if (tcsetattr(fd->fd, TCSAFLUSH, &raw) < 0) if (tcsetattr(fd->fd, TCSAFLUSH, &raw) < 0)
return (errno = ENOTTY, ERROR); return (errno = ENOTTY, ERROR);
@ -229,7 +181,7 @@ t_usize line_get_prompt_len(t_const_str s)
else if (s[i] == 'm') else if (s[i] == 'm')
{ {
i++; i++;
break; break ;
} }
} }
} }
@ -255,7 +207,8 @@ void line_refresh(t_line_state *state, t_line_flags flags)
str = string_new(64); str = string_new(64);
string_push(&str, "\r\x1b[2K"); string_push(&str, "\r\x1b[2K");
if (flags & REFRESH_WRITE) if (flags & REFRESH_WRITE)
me_printf_str(&str, "%s%s\x1b[0G\x1b[%uC", state->prompt, state->buf.buf, state->pos + line_get_prompt_len(state->prompt)); me_printf_str(&str, "%s%s\x1b[0G\x1b[%uC", state->prompt,
state->buf.buf, state->pos + line_get_prompt_len(state->prompt));
me_printf_fd(state->output_fd, "%s", str.buf); me_printf_fd(state->output_fd, "%s", str.buf);
string_free(str); string_free(str);
} }
@ -337,32 +290,34 @@ void line_edit_move_end(t_line_state *state)
/* Substitute the currently edited line with the next or previous history /* Substitute the currently edited line with the next or previous history
* entry as specified by 'dir'. */ * entry as specified by 'dir'. */
void line_edit_history_next(t_line_state *state, t_history_direction direction) void line_edit_history_next(t_line_state *state,
t_history_direction direction)
{ {
t_vec_str *history; t_vec_str *history;
history = get_history(); history = get_history();
if (history->len > 1) if (history->len > 1)
{ {
/* Update the current history entry before to /* Update the current history entry before to
* overwrite it with the next one. */ * overwrite it with the next one. */
mem_free(history->buffer[history->len - 1 - state->history_index]); mem_free(history->buffer[history->len - 1 - state->history_index]);
history->buffer[history->len - 1 - state->history_index] = str_clone(state->buf.buf); history->buffer[history->len - 1
- state->history_index] = str_clone(state->buf.buf);
/* Show the new entry */ /* Show the new entry */
state->history_index += (direction == HIST_PREV) ? 1 : -1; state->history_index += (direction == HIST_PREV) ? 1 : -1;
if (state->history_index < 0) if (state->history_index < 0)
{ {
state->history_index = 0; state->history_index = 0;
return; return ;
} }
else if ((t_usize)state->history_index >= history->len) else if ((t_usize)state->history_index >= history->len)
{ {
state->history_index = history->len - 1; state->history_index = history->len - 1;
return; return ;
} }
string_clear(&state->buf); string_clear(&state->buf);
string_push(&state->buf, history->buffer[history->len - 1 - state->history_index]); string_push(&state->buf, history->buffer[history->len - 1
- state->history_index]);
state->pos = state->buf.len; state->pos = state->buf.len;
line_refresh_line(state); line_refresh_line(state);
} }
@ -411,13 +366,13 @@ void line_edit_backspace(t_line_state *state)
* fails. If stdin_fd or stdout_fd are set to -1, the default is to use * fails. If stdin_fd or stdout_fd are set to -1, the default is to use
* STDIN_FILENO and STDOUT_FILENO. * STDIN_FILENO and STDOUT_FILENO.
*/ */
t_error line_edit_start(t_line_state *state, t_fd *stdin_fd, t_fd *stdout_fd, t_const_str prompt) t_error line_edit_start(t_line_state *state, t_fd *stdin_fd, t_fd *stdout_fd,
t_const_str prompt)
{ {
if (stdin_fd == NULL) if (stdin_fd == NULL)
stdin_fd = get_stdin(); stdin_fd = get_stdin();
if (stdout_fd == NULL) if (stdout_fd == NULL)
stdout_fd = get_stdout(); stdout_fd = get_stdout();
/* Populate the linenoise state that we pass to functions implementing /* Populate the linenoise state that we pass to functions implementing
* specific editing functionalities. */ * specific editing functionalities. */
state->input_fd = stdin_fd; state->input_fd = stdin_fd;
@ -426,24 +381,19 @@ t_error line_edit_start(t_line_state *state, t_fd *stdin_fd, t_fd *stdout_fd, t_
state->prompt = prompt; state->prompt = prompt;
state->prompt_len = str_len(state->prompt); state->prompt_len = str_len(state->prompt);
state->pos = 0; state->pos = 0;
/* Enter raw mode. */ /* Enter raw mode. */
if (line_enable_raw_mode(state->input_fd)) if (line_enable_raw_mode(state->input_fd))
return (ERROR); return (ERROR);
state->columns = line_get_columns(stdin_fd, stdout_fd); state->columns = line_get_columns(stdin_fd, stdout_fd);
state->history_index = 0; state->history_index = 0;
/* If stdin is not a tty, stop here with the initialization. We /* If stdin is not a tty, stop here with the initialization. We
* will actually just read a line from standard input in blocking * will actually just read a line from standard input in blocking
* mode later, in linenoiseEditFeed(). */ * mode later, in linenoiseEditFeed(). */
if (!isatty(state->input_fd->fd)) if (!isatty(state->input_fd->fd))
return (NO_ERROR); return (NO_ERROR);
/* The latest history entry is always our current buffer, that /* The latest history entry is always our current buffer, that
* initially is just an empty string. */ * initially is just an empty string. */
line_history_add(""); line_history_add("");
if (write_fd(state->output_fd, (t_u8 *)prompt, state->prompt_len, NULL)) if (write_fd(state->output_fd, (t_u8 *)prompt, state->prompt_len, NULL))
return (ERROR); return (ERROR);
return (NO_ERROR); return (NO_ERROR);
@ -455,6 +405,7 @@ t_error line_edit_start(t_line_state *state, t_fd *stdin_fd, t_fd *stdout_fd, t_
* descriptor. In the case of blocking operations, this function can just be * descriptor. In the case of blocking operations, this function can just be
* called in a loop, and block. * called in a loop, and block.
* *
* The function returns get_unfinished_str() to signal that line editing is still * The function returns get_unfinished_str() to signal that line editing is still
* in progress, that is, the user didn't yet pressed enter / CTRL-D. Otherwise * in progress, that is, the user didn't yet pressed enter / CTRL-D. Otherwise
* the function returns the pointer to the heap-allocated buffer with the * the function returns the pointer to the heap-allocated buffer with the
@ -469,32 +420,32 @@ t_error line_edit_start(t_line_state *state, t_fd *stdin_fd, t_fd *stdout_fd, t_
*/ */
t_str line_edit_feed(t_line_state *state) t_str line_edit_feed(t_line_state *state)
{ {
/* Not a TTY, pass control to line reading without character
* count limits. */
if (!isatty(state->input_fd->fd))
return line_no_tty_impl();
char c; char c;
t_isize nread; t_isize nread;
char seq[3]; char seq[3];
t_vec_str *history = get_history(); t_vec_str *history;
t_str tmp; t_str tmp;
/* Not a TTY, pass control to line reading without character
* count limits. */
if (!isatty(state->input_fd->fd))
return (line_no_tty_impl());
history = get_history();
if (read_fd(state->input_fd, (t_u8 *)&c, 1, &nread)) if (read_fd(state->input_fd, (t_u8 *)&c, 1, &nread))
return (NULL); return (NULL);
switch (c) switch (c)
{ {
case K_NEWLINE: /* enter */ case K_NEWLINE: /* enter */
case K_ENTER: /* enter */ case K_ENTER: /* enter */
if (!vec_str_pop(history, &tmp)) if (!vec_str_pop(history, &tmp))
mem_free(tmp); mem_free(tmp);
return str_clone(state->buf.buf); return (str_clone(state->buf.buf));
case K_CTRL_C: /* ctrl-c */ case K_CTRL_C: /* ctrl-c */
return (errno = EAGAIN, NULL); return (errno = EAGAIN, NULL);
case K_BACKSPACE: /* backspace */ case K_BACKSPACE: /* backspace */
case K_CTRL_H: /* ctrl-h */ case K_CTRL_H: /* ctrl-h */
line_edit_backspace(state); line_edit_backspace(state);
break; break ;
case K_CTRL_D: /* ctrl-d, remove char at right of cursor, or if the case K_CTRL_D: /* ctrl-d, remove char at right of cursor, or if the
line is empty, act as end-of-file. */ line is empty, act as end-of-file. */
if (state->buf.len > 0) if (state->buf.len > 0)
@ -505,28 +456,27 @@ t_str line_edit_feed(t_line_state *state)
mem_free(history->buffer[history->len]); mem_free(history->buffer[history->len]);
return (errno = ENOENT, NULL); return (errno = ENOENT, NULL);
} }
break; break ;
case K_CTRL_B: /* ctrl-b */ case K_CTRL_B: /* ctrl-b */
line_edit_move_left(state); line_edit_move_left(state);
break; break ;
case K_CTRL_F: /* ctrl-f */ case K_CTRL_F: /* ctrl-f */
line_edit_move_right(state); line_edit_move_right(state);
break; break ;
case K_CTRL_P: /* ctrl-p */ case K_CTRL_P: /* ctrl-p */
line_edit_history_next(state, HIST_PREV); line_edit_history_next(state, HIST_PREV);
break; break ;
case K_CTRL_N: /* ctrl-n */ case K_CTRL_N: /* ctrl-n */
line_edit_history_next(state, HIST_NEXT); line_edit_history_next(state, HIST_NEXT);
break; break ;
case K_ESC: /* escape sequence */ case K_ESC: /* escape sequence */
/* Read the next two bytes representing the escape sequence. /* Read the next two bytes representing the escape sequence.
* Use two calls to handle slow terminals returning the two * Use two calls to handle slow terminals returning the two
* chars at different times. */ * chars at different times. */
if (read_fd(state->input_fd, (t_u8 *)seq, 1, NULL)) if (read_fd(state->input_fd, (t_u8 *)seq, 1, NULL))
break; break ;
if (read_fd(state->input_fd, (t_u8 *)(seq + 1), 1, NULL)) if (read_fd(state->input_fd, (t_u8 *)(seq + 1), 1, NULL))
break; break ;
/* ESC [ sequences. */ /* ESC [ sequences. */
if (seq[0] == '[') if (seq[0] == '[')
{ {
@ -534,7 +484,7 @@ t_str line_edit_feed(t_line_state *state)
{ {
/* Extended escape, read additional byte. */ /* Extended escape, read additional byte. */
if (read_fd(state->input_fd, (t_u8 *)(seq + 2), 1, NULL)) if (read_fd(state->input_fd, (t_u8 *)(seq + 2), 1, NULL))
break; break ;
if (seq[1] == '3' && seq[2] == '~') if (seq[1] == '3' && seq[2] == '~')
line_edit_delete(state); line_edit_delete(state);
} }
@ -544,26 +494,25 @@ t_str line_edit_feed(t_line_state *state)
{ {
case 'A': /* Up */ case 'A': /* Up */
line_edit_history_next(state, HIST_PREV); line_edit_history_next(state, HIST_PREV);
break; break ;
case 'B': /* Down */ case 'B': /* Down */
line_edit_history_next(state, HIST_NEXT); line_edit_history_next(state, HIST_NEXT);
break; break ;
case 'C': /* Right */ case 'C': /* Right */
line_edit_move_right(state); line_edit_move_right(state);
break; break ;
case 'D': /* Left */ case 'D': /* Left */
line_edit_move_left(state); line_edit_move_left(state);
break; break ;
case 'H': /* Home */ case 'H': /* Home */
line_edit_move_home(state); line_edit_move_home(state);
break; break ;
case 'F': /* End*/ case 'F': /* End*/
line_edit_move_end(state); line_edit_move_end(state);
break; break ;
} }
} }
} }
/* ESC O sequences. */ /* ESC O sequences. */
else if (seq[0] == 'O') else if (seq[0] == 'O')
{ {
@ -571,36 +520,36 @@ t_str line_edit_feed(t_line_state *state)
{ {
case 'H': /* Home */ case 'H': /* Home */
line_edit_move_home(state); line_edit_move_home(state);
break; break ;
case 'F': /* End*/ case 'F': /* End*/
line_edit_move_end(state); line_edit_move_end(state);
break; break ;
} }
} }
break; break ;
case K_CTRL_U: /* Ctrl+u, delete the whole line. */ case K_CTRL_U: /* Ctrl+u, delete the whole line. */
string_clear(&state->buf); string_clear(&state->buf);
state->pos = 0; state->pos = 0;
line_refresh_line(state); line_refresh_line(state);
break; break ;
case K_CTRL_K: /* Ctrl+k, delete from current to end of line. */ case K_CTRL_K: /* Ctrl+k, delete from current to end of line. */
string_clear_after(&state->buf, state->pos); string_clear_after(&state->buf, state->pos);
line_refresh_line(state); line_refresh_line(state);
break; break ;
case K_CTRL_A: /* Ctrl+a, go to the start of the line */ case K_CTRL_A: /* Ctrl+a, go to the start of the line */
line_edit_move_home(state); line_edit_move_home(state);
break; break ;
case K_CTRL_E: /* ctrl+e, go to the end of the line */ case K_CTRL_E: /* ctrl+e, go to the end of the line */
line_edit_move_end(state); line_edit_move_end(state);
break; break ;
case K_CTRL_L: /* ctrl+l, clear screen */ case K_CTRL_L: /* ctrl+l, clear screen */
line_clear_screen(state->output_fd); line_clear_screen(state->output_fd);
line_refresh_line(state); line_refresh_line(state);
break; break ;
default: default:
if (line_edit_insert(state, c)) if (line_edit_insert(state, c))
return (NULL); return (NULL);
break; break ;
} }
return ((t_str)get_unfinished_str()); return ((t_str)get_unfinished_str());
} }
@ -612,7 +561,7 @@ t_str line_edit_feed(t_line_state *state)
void line_edit_stop(t_line_state *state) void line_edit_stop(t_line_state *state)
{ {
if (!isatty(state->input_fd->fd)) if (!isatty(state->input_fd->fd))
return; return ;
line_disable_raw_mode(state->input_fd); line_disable_raw_mode(state->input_fd);
me_printf_fd(state->output_fd, "\n"); me_printf_fd(state->output_fd, "\n");
string_free(state->buf); string_free(state->buf);
@ -625,13 +574,13 @@ void line_edit_stop(t_line_state *state)
t_str line_blocking_edit(t_fd *stdin_fd, t_fd *stdout_fd, t_const_str prompt) t_str line_blocking_edit(t_fd *stdin_fd, t_fd *stdout_fd, t_const_str prompt)
{ {
t_line_state l; t_line_state l;
t_str res;
line_edit_start(&l, stdin_fd, stdout_fd, prompt); line_edit_start(&l, stdin_fd, stdout_fd, prompt);
t_str res;
while ((res = line_edit_feed(&l)) == get_unfinished_str()) while ((res = line_edit_feed(&l)) == get_unfinished_str())
; ;
line_edit_stop(&l); line_edit_stop(&l);
return res; return (res);
} }
/* This special mode is used by linenoise in order to print scan codes /* This special mode is used by linenoise in order to print scan codes
@ -640,27 +589,27 @@ t_str line_blocking_edit(t_fd *stdin_fd, t_fd *stdout_fd, t_const_str prompt)
void line_print_key_codes(void) void line_print_key_codes(void)
{ {
char quit[4]; char quit[4];
char c;
t_isize nread;
printf("Linenoise key codes debugging mode.\n" printf("Linenoise key codes debugging mode.\n"
"Press keys to see scan codes. Type 'quit' at any time to exit.\n"); "Press keys to see scan codes. Type 'quit' at any time to exit.\n");
// if (enableRawMode(STDIN_FILENO) == -1) // if (enableRawMode(STDIN_FILENO) == -1)
// return; // return ;
mem_set(quit, ' ', 4); mem_set(quit, ' ', 4);
while (1) while (1)
{ {
char c;
t_isize nread;
if (read_fd(get_stdin(), (void *)&c, 1, &nread)) if (read_fd(get_stdin(), (void *)&c, 1, &nread))
continue; continue ;
if (nread <= 0) if (nread <= 0)
continue; continue ;
mem_move(quit, quit + 1, sizeof(quit) - 1); /* shift string to left. */ mem_move(quit, quit + 1, sizeof(quit) - 1); /* shift string to left. */
quit[sizeof(quit) - 1] = c; /* Insert current char on the right. */ quit[sizeof(quit) - 1] = c;
/* Insert current char on the right. */
if (mem_compare(quit, "quit", sizeof(quit))) if (mem_compare(quit, "quit", sizeof(quit)))
break; break ;
printf("'%c' %02x (%d) (type quit to exit)\n", isprint(c) ? c : '?',
printf("'%c' %02x (%d) (type quit to exit)\n", isprint(c) ? c : '?', (int)c, (int)c); (int)c, (int)c);
printf("\r"); /* Go left edge manually, we are in raw mode. */ printf("\r"); /* Go left edge manually, we are in raw mode. */
fflush(stdout); fflush(stdout);
} }
@ -708,7 +657,7 @@ t_str linenoise(t_const_str prompt)
{ {
/* Not a tty: read from file / pipe. In this mode we don't want any /* Not a tty: read from file / pipe. In this mode we don't want any
* limit to the line size, so we call a function to handle that. */ * limit to the line size, so we call a function to handle that. */
return line_no_tty_impl(); return (line_no_tty_impl());
} }
retval = line_blocking_edit(get_stdin(), get_stdout(), prompt); retval = line_blocking_edit(get_stdin(), get_stdout(), prompt);
return (retval); return (retval);
@ -729,7 +678,6 @@ bool line_history_add(t_const_str line)
t_vec_str *history; t_vec_str *history;
history = get_history(); history = get_history();
if (history->len != 0 && !strcmp(history->buffer[history->len - 1], line)) if (history->len != 0 && !strcmp(history->buffer[history->len - 1], line))
return (false); return (false);
linecopy = str_clone(line); linecopy = str_clone(line);
@ -748,14 +696,15 @@ t_error line_history_save(t_str name)
t_vec_str *history; t_vec_str *history;
history = get_history(); history = get_history();
fd = open_fd(name, FD_READ, FD_CLOSE_ON_EXEC | FD_TRUNCATE | FD_CREATE,
fd = open_fd(name, FD_READ, FD_CLOSE_ON_EXEC | FD_TRUNCATE | FD_CREATE, FP_OWRITE); FP_OWRITE);
if (fd == NULL) if (fd == NULL)
return (ERROR); return (ERROR);
j = 0; j = 0;
while (j < history->len) while (j < history->len)
{ {
write_fd(fd, (t_u8 *)history->buffer[j], str_len(history->buffer[j]), NULL); write_fd(fd, (t_u8 *)history->buffer[j], str_len(history->buffer[j]),
NULL);
write_fd(fd, (t_u8 *)"\n", 1, NULL); write_fd(fd, (t_u8 *)"\n", 1, NULL);
j++; j++;
} }
@ -793,7 +742,8 @@ t_error line_history_load(t_str name)
history = get_history(); history = get_history();
while (!gnl_wrapper(fd, &tmp)) while (!gnl_wrapper(fd, &tmp))
{ {
while (tmp.len != 0 && (tmp.buf[tmp.len - 1] == '\n' || tmp.buf[tmp.len - 1] == '\r')) while (tmp.len != 0 && (tmp.buf[tmp.len - 1] == '\n' || tmp.buf[tmp.len
- 1] == '\r'))
string_pop(&tmp); string_pop(&tmp);
vec_str_push(history, tmp.buf); vec_str_push(history, tmp.buf);
} }

63
line/src/line_globals.c Normal file
View file

@ -0,0 +1,63 @@
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* line_globals.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: maiboyer <maiboyer@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/07/10 15:47:12 by maiboyer #+# #+# */
/* Updated: 2024/07/10 15:48:09 by maiboyer ### ########.fr */
/* */
/* ************************************************************************** */
#include "me/types.h"
#include "line/_line_internal.h"
#include "line/_line_structs.h"
#include "me/mem/mem.h"
t_const_str get_unfinished_str(void)
{
return ("If you see this,"
" you are misusing the API"
" if it returns get_unfinished_str() "
" the user is yet editing the line. "
"See the README file for more information.");
}
t_vec_str *get_history(void)
{
static t_vec_str history = {};
static bool init = false;
if (!init)
{
history = vec_str_new(256, (void (*)())mem_free);
init = true;
}
return (&history);
}
t_raw_mode_state *get_raw_mode_state(void)
{
static t_raw_mode_state state = {};
return (&state);
}
/* Free the history, but does not reset it. Only used when we have to
* exit() to avoid memory leaks are reported by valgrind & co. */
void free_history(void)
{
t_vec_str *history;
history = get_history();
vec_str_free(*history);
}
/* At exit we'll try to fix the terminal to the initial conditions. */
__attribute__((destructor)) void line_uninit_lib(void)
{
line_disable_raw_mode(get_stdin());
free_history();
}