-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic_editor.cpp
More file actions
460 lines (399 loc) · 15.6 KB
/
Copy pathbasic_editor.cpp
File metadata and controls
460 lines (399 loc) · 15.6 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
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
/*
* Terminal-based code editor with autocomplete.
*
* Features:
* - ncurses-based text editing
* - syntax highlighting
* - file open / save
* - search and navigation
* - undo / redo (Ctrl+Z / Ctrl+Y)
* - intelligent autocomplete using classic DSA
*
* Autocomplete engine uses:
* - TST for prefix matching
* - Ranker for scoring (frequency + co-occurrence graph boost)
* - MinHeap (inside Ranker) for top-K selection
* - LRU cache for reuse
* - KMP for substring match fallback
*/
#include <ncurses.h>
#include <string>
#include <vector>
#include <fstream>
#include <cstring>
#include <algorithm>
#include <filesystem>
#include <unordered_set>
#include "tst.h"
#include "phrase_store.h"
#include "freq_store.h"
#include "ranker.h"
#include "graph.h"
#include "kmp.h"
#include "minheap.h"
#include "lru.h"
#include "stack.h"
#include <chrono>
class BasicEditor {
private:
std::vector<std::string> lines;
std::vector<std::string> suggestions;
int cursorY = 0;
int cursorX = 0;
int scrollY = 0;
bool showingSuggestions = false;
int selectedSuggestion = 0;
TST tst;
PhraseStore phraseStore;
FreqStore freqStore;
CooccurrenceGraph graph;
Ranker ranker;
std::vector<std::string> dictionaryWords;
std::string lastAcceptedWord;
// [CHANGE 1] Removed MinHeap suggestionHeap member.
// The Ranker creates its own MinHeap internally in rankResults(),
// so a separate heap here was redundant.
lru_cache suggestionCache{100};
UndoRedoStack undoRedoStack;
std::string currentFileName;
bool fileModified = false;
std::string searchQuery;
public:
BasicEditor()
: phraseStore("data/phrases.txt"),
freqStore("data/frequency.txt"),
ranker(&freqStore, &graph) {
lines.push_back("");
loadDictionary();
std::error_code ec;
std::filesystem::create_directories("scratch", ec);
}
void run() {
initscr();
raw();
keypad(stdscr, TRUE);
noecho();
curs_set(1);
start_color();
init_pair(1, COLOR_BLUE, COLOR_BLACK);
init_pair(2, COLOR_GREEN, COLOR_BLACK);
init_pair(3, COLOR_CYAN, COLOR_BLACK);
init_pair(4, COLOR_YELLOW, COLOR_BLACK);
init_pair(5, COLOR_MAGENTA, COLOR_BLACK);
init_pair(6, COLOR_RED, COLOR_BLACK);
bool running = true;
while (running) {
draw();
running = handleInput(getch());
}
phraseStore.save();
freqStore.save();
endwin();
}
private:
void loadDictionary() {
std::ifstream file("data/words.txt");
if (!file.is_open()) return;
std::string word;
while (file >> word) {
tst.insert(word);
dictionaryWords.push_back(word);
}
}
bool isKeyword(const std::string& w) {
static const std::vector<std::string> keys = {
"auto","break","case","char","const","continue","default","do",
"double","else","enum","extern","float","for","goto","if",
"int","long","register","return","short","signed","sizeof","static",
"struct","switch","typedef","union","unsigned","void","volatile","while",
"class","namespace","template","public","private","protected","virtual",
"bool","true","false","nullptr","new","delete","try","catch","throw",
"using","std","string","vector","map","set","include","define","ifdef"
};
return std::find(keys.begin(), keys.end(), w) != keys.end();
}
void drawLine(int y, int num, const std::string& line) {
mvprintw(y, 0, "%3d | ", num);
int x = 6;
for (size_t i = 0; i < line.size(); i++) {
if (line[i] == '"' || line[i] == '\'') {
char q = line[i];
attron(COLOR_PAIR(2));
mvaddch(y, x++, line[i++]);
while (i < line.size() && line[i] != q) {
mvaddch(y, x++, line[i]);
if (line[i] == '\\' && i + 1 < line.size())
mvaddch(y, x++, line[++i]);
i++;
}
if (i < line.size()) mvaddch(y, x++, line[i]);
attroff(COLOR_PAIR(2));
continue;
}
if (i + 1 < line.size() && line[i] == '/' && line[i + 1] == '/') {
attron(COLOR_PAIR(3));
while (i < line.size()) mvaddch(y, x++, line[i++]);
attroff(COLOR_PAIR(3));
break;
}
if (line[i] == '#') {
attron(COLOR_PAIR(5));
while (i < line.size() && (isalnum(line[i]) || line[i] == '_' || line[i] == '#'))
mvaddch(y, x++, line[i++]);
attroff(COLOR_PAIR(5));
i--;
continue;
}
if (isdigit(line[i])) {
attron(COLOR_PAIR(4));
while (i < line.size() && (isdigit(line[i]) || line[i] == '.'))
mvaddch(y, x++, line[i++]);
attroff(COLOR_PAIR(4));
i--;
continue;
}
if (strchr("+-*/%=<>!&|^~?:;,(){}[]", line[i])) {
attron(COLOR_PAIR(6));
mvaddch(y, x++, line[i]);
attroff(COLOR_PAIR(6));
continue;
}
if (isalnum(line[i]) || line[i] == '_') {
std::string word;
while (i < line.size() && (isalnum(line[i]) || line[i] == '_'))
word += line[i++];
i--;
if (isKeyword(word)) {
attron(COLOR_PAIR(1) | A_BOLD);
mvprintw(y, x, "%s", word.c_str());
attroff(COLOR_PAIR(1) | A_BOLD);
} else {
mvprintw(y, x, "%s", word.c_str());
}
x += word.size();
continue;
}
mvaddch(y, x++, line[i]);
}
}
void draw() {
clear();
int maxLines = LINES - 3;
for (int i = 0; i < maxLines && scrollY + i < (int)lines.size(); i++)
drawLine(i, scrollY + i + 1, lines[scrollY + i]);
if (showingSuggestions && !suggestions.empty()) {
int y = cursorY - scrollY + 1;
int x = cursorX + 6;
for (int i = 0; i < (int)suggestions.size() && i < 5; i++)
mvprintw(y + i, x,
i == selectedSuggestion ? " > %s" : " %s",
suggestions[i].c_str());
}
// [CHANGE 5] Updated status bar to show Ctrl+Z / Ctrl+Y
attron(A_REVERSE);
mvprintw(LINES - 2, 0,
" %s%s | Ln %d/%zu Col %d | ^O Open ^W Save ^R Search ^Z Undo ^Y Redo ^Q Quit ",
currentFileName.empty() ? "[No Name]" : currentFileName.c_str(),
fileModified ? " [+]" : "",
cursorY + 1, lines.size(), cursorX + 1);
attroff(A_REVERSE);
move(cursorY - scrollY, cursorX + 6);
refresh();
}
void updateScroll() {
int maxLines = LINES - 3;
if (cursorY < scrollY) scrollY = cursorY;
else if (cursorY >= scrollY + maxLines)
scrollY = cursorY - maxLines + 1;
}
bool handleInput(int ch) {
switch (ch) {
case 17: return false; // Ctrl+Q
case KEY_UP:
if (showingSuggestions && selectedSuggestion > 0) {
selectedSuggestion--;
} else if (!showingSuggestions && cursorY > 0) {
cursorY--;
updateScroll();
}
break;
case KEY_DOWN:
if (showingSuggestions && selectedSuggestion < (int)suggestions.size() - 1) {
selectedSuggestion++;
} else if (!showingSuggestions && cursorY < (int)lines.size() - 1) {
cursorY++;
updateScroll();
}
break;
case KEY_LEFT:
if (cursorX > 0) cursorX--;
break;
case KEY_RIGHT:
if (cursorX < (int)lines[cursorY].size()) cursorX++;
break;
case '\n':
undoRedoStack.pushInsert(cursorY, lines[cursorY]);
lines.insert(lines.begin() + cursorY + 1,
lines[cursorY].substr(cursorX));
lines[cursorY] = lines[cursorY].substr(0, cursorX);
cursorY++;
cursorX = 0;
fileModified = true;
updateScroll();
break;
case KEY_BACKSPACE:
case 127:
undoRedoStack.pushInsert(cursorY, lines[cursorY]);
if (cursorX > 0) {
lines[cursorY].erase(cursorX - 1, 1);
cursorX--;
}
fileModified = true;
break;
// ──────────────────────────────────────────────
// [CHANGE 4] Undo / Redo keybindings
// ──────────────────────────────────────────────
case 26: { // Ctrl+Z — Undo
if (undoRedoStack.canUndo()) {
auto [lineNum, oldText] = undoRedoStack.undo();
if (lineNum >= 0 && lineNum < (int)lines.size()) {
lines[lineNum] = oldText;
cursorY = lineNum;
cursorX = std::min(cursorX, (int)oldText.size());
fileModified = true;
updateScroll();
}
}
break;
}
case 25: { // Ctrl+Y — Redo
if (undoRedoStack.canRedo()) {
auto [lineNum, newText] = undoRedoStack.redo();
if (lineNum >= 0 && lineNum < (int)lines.size()) {
lines[lineNum] = newText;
cursorY = lineNum;
cursorX = std::min(cursorX, (int)newText.size());
fileModified = true;
updateScroll();
}
}
break;
}
// ──────────────────────────────────────────────
case '\t':
if (showingSuggestions) acceptSuggestion();
else triggerAutocomplete();
break;
default:
if (ch >= 32 && ch <= 126) {
undoRedoStack.pushInsert(cursorY, lines[cursorY]);
lines[cursorY].insert(cursorX++, 1, ch);
fileModified = true;
triggerAutocomplete();
}
}
return true;
}
// ──────────────────────────────────────────────────────────────
// [CHANGE 2] Rewritten triggerAutocomplete()
//
// Before: manual freqStore.get() → heap.insert() → sort
// (Ranker, Graph, KMP all unused)
//
// Now: PhraseStore (top phrases)
// + TST prefix search
// + KMP substring fallback (when prefix matches < 5)
// + Ranker.rankResults() which internally uses:
// - FreqStore.get() for frequency score
// - Graph.getBoost() for co-occurrence boost
// - MinHeap for top-K selection
// ──────────────────────────────────────────────────────────────
void triggerAutocomplete() {
auto t0 = std::chrono::high_resolution_clock::now();
std::string word = getCurrentWord();
if (word.empty()) {
showingSuggestions = false;
return;
}
suggestions.clear();
// 1. Check LRU cache first (avoids redundant lookups)
if (suggestionCache.exists(word)) {
suggestions = suggestionCache.get(word);
showingSuggestions = true;
selectedSuggestion = 0;
return;
}
// 2. Collect phrase matches (snippets like fori → for loop)
auto phrases = phraseStore.getTopPhrases(word, 3);
// 3. Collect prefix matches from TST
auto candidates = tst.prefixSearch(word, 10);
// 4. KMP substring fallback: if prefix matches are sparse,
// search the full dictionary for words CONTAINING the typed text.
// This is where KMP earns its place — O(n+m) per word instead
// of naive O(n*m), and it avoids duplicating prefix results.
if ((int)candidates.size() < 5) {
for (const auto& dictWord : dictionaryWords) {
if (KMP::contains(dictWord, word)) {
// Avoid duplicates already found by prefix search
if (std::find(candidates.begin(), candidates.end(), dictWord)
== candidates.end()) {
candidates.push_back(dictWord);
if (candidates.size() >= 15) break;
}
}
}
}
// 5. Score and rank via Ranker
// Ranker.computeScore() = freqStore.get(token) + graph.getBoost(last, token)
// This is where the Graph's co-occurrence data is finally READ,
// not just written. The lastAcceptedWord context influences ranking.
ranker.setLastToken(lastAcceptedWord);
auto ranked = ranker.rankResults(candidates, 10);
// 6. Assemble final suggestions: phrases first, then ranked tokens
for (auto& p : phrases)
suggestions.push_back("[PHRASE] " + p.snippet);
for (auto& [token, score] : ranked)
suggestions.push_back(token);
// Cap at 10 total suggestions
if (suggestions.size() > 10)
suggestions.resize(10);
// 7. Cache result in LRU for next time
suggestionCache.put(word, suggestions);
showingSuggestions = true;
selectedSuggestion = 0;
auto t1 = std::chrono::high_resolution_clock::now();
auto us = std::chrono::duration_cast<std::chrono::microseconds>(t1 - t0).count();
mvprintw(LINES - 1, 0, "autocomplete: %ld us", us);
}
void acceptSuggestion() {
std::string word = getCurrentWord();
std::string s = suggestions[selectedSuggestion];
if (s.rfind("[PHRASE]", 0) == 0)
s = s.substr(9);
int start = cursorX - word.size();
lines[cursorY].erase(start, word.size());
lines[cursorY].insert(start, s);
cursorX = start + s.size();
freqStore.bump(s, 1);
if (!lastAcceptedWord.empty())
graph.addEdge(lastAcceptedWord, s);
// [CHANGE 3] Keep Ranker in sync with accepted word
// so the NEXT autocomplete uses co-occurrence context.
ranker.setLastToken(s);
lastAcceptedWord = s;
showingSuggestions = false;
}
std::string getCurrentWord() {
auto& line = lines[cursorY];
int end = cursorX, start = end;
while (start > 0 &&
(isalnum(line[start - 1]) || line[start - 1] == '_' || line[start - 1] == '#'))
start--;
return line.substr(start, end - start);
}
};
int main() {
BasicEditor editor;
editor.run();
return 0;
}