-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheditorRow.c
More file actions
56 lines (52 loc) · 1.22 KB
/
editorRow.c
File metadata and controls
56 lines (52 loc) · 1.22 KB
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
#include <stdlib.h>
#include <string.h>
#include "editorRow.h"
EditorRow *newRow(char *s, size_t length, int tabSize) {
EditorRow *row = malloc(sizeof(*row));
row->size = length;
row->chars = s;
row->renderSize = 0;
row->renderChars = NULL;
editorUpdateRow(row, tabSize);
return row;
}
int editorCursorToRender(EditorRow *row, int cursorX, int tabSize) {
int renderX = 0;
for (int j = 0; j < cursorX; j++) {
if (row->chars[j] == '\t') {
renderX += tabSize;
} else {
renderX += 1;
}
}
return renderX;
}
/**
* Update the rendered characters for a row.
*/
void editorUpdateRow(EditorRow *row, int tabSize) {
int tabs = 0;
for (int j = 0; j < row->size; j++) {
if (row->chars[j] == '\t') {
tabs++;
}
}
free(row->renderChars);
row->renderChars = malloc(row->size + tabs * (tabSize - 1) + 1);
int i = 0;
for (int j = 0; j < row->size; j++) {
if (row->chars[j] == '\t') {
for (int size = tabSize; size > 0; size--) {
row->renderChars[i++] = ' ';
}
} else {
row->renderChars[i++] = row->chars[j];
}
}
row->renderChars[i] = '\0';
row->renderSize = i;
}
void editorFreeRow(EditorRow *row) {
free(row->renderChars);
free(row->chars);
}