SD said:
I am thinking about writing a text editor in C for unix
sometime soon. I am just doing this to learn more about C. I
want to write something like ed.c, a simple line editor. What
types of data structures would be appropriate?
Buffer Gap and paged Buffer Gap seem to be popular.
Try posting this on comp.editors - they go into great detail
about such things from time to time.
In the meantime, you might like playing with Ant's Editor
vIOCCC91 - which uses Buffer Gap, by the way. To compile
on my system, I type: gcc ant.c -o ant -lcurses. Yours
may be different.
#include <stdio.h>
#include <ctype.h>
#include <curses.h>
#define BUF 0x40000
#define T isspace(*(t=Z(p)))&&
#define V return
#define _ while
#define e int
#define o char
e d,i,j,m,n,p,q,x,y;
o*c,b[BUF],*f,*g=b,*h,*t;
o*Z(e a){if(a<0)V b;V b+a+(b+a<g?0:h-g);}
P(o*a){V a-b-(a<h?0:h-g);}
S(){p=0;}
bf(){n=p=P(c);}
Q(){q=1;}
G(){t=Z(p);_(t<g)*--h=*--g;_(h<t)*g++=*h++;p=P(h);}
B(){_(!T b<t)--p;_(T b<t)--p;}
M(e a){_(b<(t=Z(--a))&&*t-'\n');V b<t?++a:0;}
N(e a){_((t=Z(a++))<c&&*t-'\n');V t<c?a
(c);}
A(e a,e j){i=0;_((t=Z(a))<c&&*t-'\n'&&i<j){
i+=*t-'\t'?1:8-(i&7);++a;}V a;}
L(){0<p&&--p;}
R(){p<P(c)&&++p;}
U(){p=A(M(M(p)-1),x);}
D(){p=A(N(p),x);}
H(){p=M(p);}
E(){p=N(p);L();}
J(){m=p=M(n-1);_(0<y--)D();n=P(c);}
K(){j=d;_(0<--j)m=M(m-1),U();}
X(){G();p=h<c?P(++h)
;}
F(){FILE*fp=fopen(f,"w");j=p;p=0;G();
fwrite(h,1,(e)(c-h),fp);fclose(fp);p=j;}
W(){_(!T t<c)++p;_(T t<c)++p;}
Y(){m=p<m?M(p):m;if(n<=p){m=N(p);i=m-P(c)?d:d-2;
_(0<i--)m=M(m-1);}move(0,0);i=j=0;n=m;for(;
{p-n||(y=i,x=j);
t=Z(n);if(d<=i||c<=t)break;
if(*t-'\r')addch(*t),j+=*t-'\t'?1:8-(j&7);
if(*t=='\n'||COLS<=j)++i,j=0;++n;}clrtobot();
if(++i<d)mvaddstr(i,0,"<<EOF>>");move(y,x);refresh();}
I(){G();_((j=getch())!='\f'){
if(j-'\b')g-h&&(*g++=(o)(j-'\r'?j:'\n'));else b<g&&--g;
p=P(h);Y();}}
C(){clear();Y();}
e(*z[])()={L,D,U,R,B,J,K,W,H,E,S,bf,I,X,F,C,Q,G};
o k[]="hjklHJKL[]tbixWRQ";
e main(e u,o**v){FILE*fp;h=c=b+BUF;if(u<2)V 2;initscr();
d=LINES;raw();noecho();idlok(stdscr,1);
if(0!=(fp=fopen(f=*++v,"r"))){g+=fread(b,1,BUF,fp);g=g<b?b:g;
fclose(fp);}S();_(!q){Y();j=getch();
for(i=0;k
&&j-k;++i);(*z)();}endwin();V 0;}