sim

the sim text editor
git clone git://ssnf.xyz/sim
Log | Files | Refs | README

commit 01b00dbf354ccb907c467c4f62bfabf2d9e0722b
parent fdaaa933fea81bf2e29ea586841a3ab6d74c7d28
Author: ssnf <ssnf@ssnf.xyz>
Date:   Sun, 18 Jul 2021 13:29:17 +0000

implemented key management

Diffstat:
M.gitignore | 1+
MMakefile | 3+++
Aconfig.def.h | 7+++++++
Msim.c | 58+++++++++++++++++++++++++++++++++++++++++++++-------------
Msim.h | 8++++++++
5 files changed, 64 insertions(+), 13 deletions(-)

diff --git a/.gitignore b/.gitignore @@ -1,2 +1,3 @@ sim +config.h *.o diff --git a/Makefile b/Makefile @@ -5,6 +5,9 @@ OBJ = ${SRC:.c=.o} all: sim +config.h: + cp config.def.h $@ + sim: ${OBJ} ${CC} ${OBJ} -o $@ diff --git a/config.def.h b/config.def.h @@ -0,0 +1,7 @@ +Key keys = { + { 'q', quit }, + { 'h', move, -1 }, + { 'j', move, +2 }, + { 'k', move, +1 }, + { 'l', move, -2 }, +}; diff --git a/sim.c b/sim.c @@ -5,8 +5,17 @@ #include "sim.h" +void die(char*, ...); +void* emalloc(ulong); +void* erealloc(void*, ulong); +void move(int); +void quit(int); + File f; Window w; +uchar refresh; + +#include "config.h" void die(char* fmt, ...) @@ -40,7 +49,7 @@ emalloc(ulong n) } void* -erealloc(void *p, ulong n) +erealloc(void* p, ulong n) { p = realloc(p, n); if (!p) @@ -48,10 +57,39 @@ erealloc(void *p, ulong n) return p; } +void +move(int arg) +{ + switch (arg) { + case -1: + if (f.dot.p0) + f.dot.p1 = --f.dot.p0; + break; + case +1: + if (f.dot.p0 < f.s->n) + f.dot.p1 = ++f.dot.p0; + break; + case -2: + for (;f.dot.p0 && f.s->s[f.dot.p0 - 1] != '\n'; f.dot.p1 = --f.dot.p0); + break; + case +2: + for (;f.dot.p0 < f.s->n && f.s->s[f.dot.p0] != '\n'; f.dot.p1 = ++f.dot.p0); + break; + }; +} + +void +quit(int arg) +{ + win_end(); + exit(arg); +} + int main(int argc, char* argv[]) { - Address a; + int i; + uchar c; win_init(); if (argv[1]) @@ -60,18 +98,12 @@ main(int argc, char* argv[]) for (;;) { win_query(&w); - switch (fgetc(stdin)) { - case 'q': - goto exit; - case 'h': - if (f.dot.p1) - f.dot.p0 = --f.dot.p1; + c = fgetc(stdin); + for (i = 0; i < LENGTH(keys); ++i) { + if (keys[i].key == c) { + keys[i].func(keys[i].value); break; - case 'l': - if (f.dot.p1 < f.s->n) - f.dot.p0 = ++f.dot.p1; + } } } -exit: - win_end(); } diff --git a/sim.h b/sim.h @@ -1,5 +1,6 @@ #define ED "\x1b[2J" #define CSI "\x1b[" +#define LENGTH(a) (sizeof(a)/sizeof(a[0])) typedef long Posn; typedef unsigned char uchar; @@ -10,6 +11,7 @@ typedef struct Address Address; typedef struct File File; typedef struct String String; typedef struct Window Window; +typedef struct Key Key; struct Address { Posn p0, p1; @@ -32,6 +34,12 @@ struct Window { ushort cx; }; +struct Key { + uchar key; + void (*func)(int); + int value; +}; + void die(char* fmt, ...); void* emalloc(ulong n); void* erealloc(void* p, ulong n);