-
Notifications
You must be signed in to change notification settings - Fork 0
/
kilo.cpp
518 lines (451 loc) · 13.1 KB
/
kilo.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
/* The implementation file of kilo-cpp. */
#define _DEFAULT_SOURCE
#define _BSD_SOURCE
#define _GNU_SOURCE // feature test macros
#include "kilo.h"
#include <sstream>
#include <fstream>
#include <algorithm>
#include <cctype>
#include <cstdio>
#include <cstdlib>
#include <sys/ioctl.h>
#define CTRL_KEY(c) ((c) & 0x1f)
#define TAB_SIZE 8
#define QUIT_TIMES 3
// escape sequences to control screen and cursor
#define CLEAR_LINE "\x1b[K"
#define CLEAR_SCREEN "\x1b[2J"
#define REPOS_CURSOR "\x1b[H"
#define HIDE_CURSOR "\x1b[?25l"
#define DISPLAY_CURSOR "\x1b[?25h"
#define INVERT_COLOR "\x1b[7m"
#define RESUME_COLOR "\x1b[m"
using namespace std;
// helper functions
static inline int min(int a, int b) { return a < b ? a : b; }
static inline int max(int a, int b) { return a > b ? a : b; }
// Clear the screen, hide and display cursor, and reposition the cursor.
static inline void clearScreen(ostream& os=cout) { os << CLEAR_SCREEN; }
static inline void hideCursor(ostream& os=cout) { os << HIDE_CURSOR; }
static inline void displayCursor(ostream& os=cout) { os << DISPLAY_CURSOR; }
// welcome message
static const string welcome = "Text editor Kilo - C++ version.";
/*** Error handling ***/
void Kilo::die(const char *str) {
clearScreen();
reposCursor();
disableRawMode();
perror(str);
exit(1);
}
/*** Terminal setup ***/
int Kilo::setWindowSize() {
struct winsize ws;
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0)
return -1;
screenRows = ws.ws_row - 2;
screenCols = ws.ws_col;
return 0;
}
void Kilo::enableRawMode() {
if (tcgetattr(STDIN_FILENO, &orig_termios) == -1)
die("tcgetattr failed");
termios raw = orig_termios;
raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
raw.c_oflag &= ~(OPOST);
raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
raw.c_cflag |= (CS8);
raw.c_cc[VMIN] = 0;
raw.c_cc[VTIME] = 1;
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) == -1)
die("tcsetattr failed");
}
/*** Input Handling ***/
int Kilo::readKey() {
char c;
char seq[3];
// Read input every 0.1 sec. Return -1 (EOF) to c if no char is read.
while ( (c = getchar()) == EOF ) {}
if (c == '\x1b') {
seq[0] = getchar();
seq[1] = getchar();
if (seq[0] == '[') {
if (seq[1] >= '0' && seq[1] <= '9') {
seq[2] = getchar();
if (seq[2] == '~') {
switch (seq[1]) {
case '1': return KeyType::KEY_HOME;
case '3': return KeyType::KEY_DELETE;
case '4': return KeyType::KEY_END;
case '5': return KeyType::PAGE_UP;
case '6': return KeyType::PAGE_DOWN;
case '7': return KeyType::KEY_HOME;
case '8': return KeyType::KEY_END;
}
}
}
switch (seq[1]) {
case 'A': return KeyType::ARROW_UP;
case 'B': return KeyType::ARROW_DOWN;
case 'C': return KeyType::ARROW_RIGHT;
case 'D': return KeyType::ARROW_LEFT;
case 'H': return KeyType::KEY_HOME;
case 'F': return KeyType::KEY_END;
}
} else if (seq[0] == 'O') {
switch (seq[1]) {
case 'H': return KeyType::KEY_HOME;
case 'F': return KeyType::KEY_END;
}
}
}
return c;
}
bool Kilo::processKeypress() {
static int quit = QUIT_TIMES;
int c = readKey();
bool flag = true;
switch (c) {
case CTRL_KEY('q'): // Ctrl-Q
if (modified && quit > 0) {
string msg("Warning: file modified and unsaved. Please press Ctrl-Q ");
msg += to_string(quit) + " more times to quit.";
setStatusMessage(msg);
quit--;
return flag;
}
clearScreen();
reposCursor();
flag = false;
break;
case KeyType::ARROW_UP:
case KeyType::ARROW_LEFT:
case KeyType::ARROW_DOWN:
case KeyType::ARROW_RIGHT:
moveCursor(c);
break;
case KeyType::PAGE_UP:
cy = max((cy - screenRows + 1), 0);
rowOffset = max((rowOffset - screenRows + 1), 0);
break;
case KeyType::PAGE_DOWN:
cy = min((cy + screenRows - 1), numRows);
rowOffset = min((rowOffset + screenRows - 1), max((numRows - screenRows + 1), 0));
break;
case KeyType::KEY_HOME:
case KeyType::KEY_END:
cx = (c == KEY_HOME) ? 0 : getRowLen();
break;
case KeyType::KEY_DELETE:
case CTRL_KEY('h'):
case KeyType::BACKSPACE:
if (c == KEY_DELETE) moveCursor(ARROW_RIGHT);
deleteChar();
modified = true;
break;
case '\r': // Enter key
insertNewLine();
modified = true;
break;
case CTRL_KEY('s'):
saveToFile(); // save content to the file
modified = false; // reset dirty flag
break;
case CTRL_KEY('l'):
case '\x1b':
// Escape Key: do nothing
break;
default:
insertChar(c);
modified = true;
}
quit = QUIT_TIMES;
if (flag) scroll();
return flag;
}
void Kilo::moveCursor(int direction) {
switch (direction) {
case ARROW_UP: {
if (cy > 0)
cy--;
break;
}
case ARROW_LEFT: {
if (cx > 0) {
cx--;
} else if (cy > 0) {
cy--;
cx = rows[cy].length();
}
break;
}
case ARROW_DOWN: {
if (cy < numRows)
cy++;
break;
}
case ARROW_RIGHT: {
int len = getRowLen();
if (cx < len) {
cx++;
} else if (cy < numRows) {
cy++;
cx = 0;
}
break;
}
}
int len = getRowLen();
if (cx > len)
cx = len;
}
void Kilo::scroll() {
rx = 0;
// set the correct value of rx
if (cy < numRows) {
for (int i = 0; i < cx; i++) {
if (rows[cy][i] == '\t') {
rx += TAB_SIZE - (rx % TAB_SIZE);
} else {
rx++;
}
}
}
if (cy < rowOffset) {
rowOffset = cy;
} else if (cy >= rowOffset + screenRows) {
rowOffset = cy - screenRows + 1;
} else if (rx < colOffset) {
colOffset = rx;
} else if (rx >= colOffset + screenCols) {
colOffset = rx - screenCols + 1;
}
}
string Kilo::promptInput(string prompt) {
// prompt for user input
string input;
int c;
while (1) {
setStatusMessage(prompt + input);
refreshScreen();
c = readKey();
if (!iscntrl(c) && c < 128) {
input.push_back(c);
} else if (c == KeyType::BACKSPACE && input.length() > 0) {
input.pop_back();
} else if (c == '\x1b') {
//Escape key: abort the saving.
input.clear();
break;
} else if (c == '\r' && input.length() > 0) {
break;
}
}
return input;
}
/*** Output Handling ***/
void inline Kilo::reposCursor(ostream& os) { os << REPOS_CURSOR; } // position the cursor to the upper-left corner of the terminal.
void inline Kilo::reposCursor(int x, int y, ostream& os) {
// position the cursor to terminal location (x, y)
string controlStr = "\x1b[" + to_string(y - rowOffset + 1) + ';' +
to_string(x - colOffset + 1) + 'H'; // "\x1b[%d;%dH"
os << controlStr;
}
void Kilo::setStatusMessage(string msg) {
statusMessage = msg;
statusMsgTime = time(NULL);
}
void Kilo::drawRows(ostream& os) {
// Draw tilds at the beginning of each row.
for (int r = 0; r < screenRows; r++) {
int row = r + rowOffset;
if (row < numRows) {
int len = renders[row].length();
os << renders[row].substr(min(colOffset, len), screenCols);
} else if (r == screenRows / 3 && numRows == 0) {
// Welcome message
int padding = (screenCols - welcome.length()) / 2;
if (padding) {
os << "~";
padding--;
}
while (padding--) os << " ";
os << "Text editor Kilo - C++ version.";
} else {
os << "~";
}
os << "\r\n";
}
}
void Kilo::drawStatusBar(ostream& os) {
os << INVERT_COLOR;
// draw status bar
string status(filename);
if (status.length() == 0) status += "[No Name]";
if (modified) status += " (modified)";
status += " - " + to_string(numRows) + " lines " +
to_string(cy+1) + '/' + to_string(numRows);
// trim the status text or pad with white spaces
if (status.length() > (unsigned) screenCols) {
status = status.substr(0, screenCols);
} else {
status += string(screenCols - status.length(), ' ');
}
os << status;
os << RESUME_COLOR << "\r\n";
}
void Kilo::drawMessageBar(ostream& os) {
os << CLEAR_LINE;
// print status message that is in 5 sec
if (time(NULL) - statusMsgTime < 5) {
os << statusMessage.substr(0, screenCols);
}
}
void Kilo::refreshScreen() {
ostringstream ss;
hideCursor(ss);
clearScreen(ss);
reposCursor(ss);
drawRows(ss);
drawStatusBar(ss);
drawMessageBar(ss);
reposCursor(rx, cy, ss);
displayCursor(ss);
cout << ss.str();
cout.flush();
}
/*** Row Operations ***/
string Kilo::renderRow(const string& row) {
string render;
for (char c : row) {
if (c == '\t') { // render tabs as multiple space chars
render += string(TAB_SIZE-(render.length() % TAB_SIZE), ' ');
} else {
render += c;
}
}
return render;
}
void Kilo::insertRow(int y, const string& newRow=string()) {
// insert a new row to the editor.
if (y < 0 || y > numRows) y = numRows;
rows.insert(rows.begin() + y, newRow);
renders.insert(renders.begin() + y, renderRow(newRow));
numRows++;
}
void Kilo::removeRow(int y) {
if (numRows == 0 || y < 0 || y >= numRows)
return;
rows.erase(rows.begin() + y);
renders.erase(renders.begin() + y);
numRows--;
}
void Kilo::rowInsertChar(int row, int pos, char c) {
string &rowStr = rows[row];
if (pos < 0 || (unsigned) pos > rowStr.length()) pos = rowStr.length();
rowStr.insert(rowStr.begin()+pos, c);
// update renders
renders[row] = renderRow(rowStr);
}
void Kilo::rowDeleteChar(int row, int pos) {
string &rowStr = rows[row];
if (pos < 0 || (unsigned) pos >= rowStr.length()) return;
rowStr.erase(rowStr.begin()+pos);
// update renders
renders[row] = renderRow(rowStr);
}
/*** Editing Operations ***/
void Kilo::insertChar(char c) {
// insert a char at current position (cx, cy)
if (cy == numRows) {
insertRow(cy);
}
rowInsertChar(cy, cx, c);
cx++;
}
void Kilo::deleteChar() {
if (cy == numRows) {
if (cy - 1 >= 0 && rows[cy-1].length() == 0) {
cy--;
removeRow(cy);
}
return;
}
if (cx == 0 && cy == 0) return;
if (cx > 0) {
rowDeleteChar(cy, cx-1);
cx--;
} else {
// append the row to the previous row and delete it.
cx = rows[cy-1].length();
rows[cy-1].append(rows[cy]);
renders[cy-1] = renderRow(rows[cy-1]);
removeRow(cy);
// repos cursor
cy--;
}
}
void Kilo::insertNewLine() {
if (cy < numRows) {
insertRow(cy+1, rows[cy].substr(cx));
rows[cy].erase(cx);
renders[cy] = renderRow(rows[cy]);
cy++;
cx = 0;
} else {
// insert an empty row.
insertRow(cy);
}
}
/*** File IO ***/
void Kilo::openFile(string& fileName) {
this->filename = fileName;
ifstream infile(fileName);
if (infile.is_open()) {
string row;
while (getline(infile, row)) {
insertRow(numRows, row);
}
infile.close();
}
}
static const string filenamePrompt = "Save as (file name): ";
void Kilo::saveToFile() {
if (filename.length() == 0) {
filename = promptInput(filenamePrompt);
if (filename.length() == 0) {
setStatusMessage("Save aborted.");
return;
}
}
ostringstream os;
for (string& s: rows) {
os << s << endl;
}
ofstream outfile(filename);
if (!outfile) {
setStatusMessage("IO error: save to file failed.");
}
outfile << os.str();
setStatusMessage("File saved.");
outfile.close();
}
/*** Public interface ***/
Kilo::Kilo(string& file) {
cx = cy = rx = 0;
numRows = 0;
rowOffset = colOffset = 0;
statusMsgTime = 0;
modified = false;
enableRawMode();
if (setWindowSize() == -1) die("setWindowSize");
if (file.length() > 0)
openFile(file);
}
void Kilo::run() {
setStatusMessage("HELP: Ctrl-S = save | Ctrl-Q = quit");
do {
refreshScreen();
} while ( processKeypress() );
}