commit 461803ad76e2698b9bd468aa81ed0ad93f099669
parent 5702e585fb5ef422e82aecc0653aeaa2c21da572
Author: Martin Ashby <martin@ashbysoft.com>
Date: Sat, 13 Jan 2024 20:50:10 +0000
Handle some edge cases with cursor movement
Make it match sublime text :)
Diffstat:
M | src/main.zig | | | 48 | ++++++++++++++++++++++++++++++++++++++---------- |
1 file changed, 38 insertions(+), 10 deletions(-)
diff --git a/src/main.zig b/src/main.zig
@@ -39,6 +39,7 @@ const EditorState = struct {
screenrows: usize = 0,
screencols: usize = 0,
cx: usize = 0,
+ cx_t: usize = 0,
cy: usize = 0,
rowoff: usize = 0,
coloff: usize = 0,
@@ -307,41 +308,68 @@ fn editorProcessKeyPress(es: *EditorState) !void {
},
.virt => |v| {
switch (v) {
- .ARROW_UP, .ARROW_DOWN, .ARROW_LEFT, .ARROW_RIGHT, .PAGE_UP, .PAGE_DOWN, .HOME, .END => try editorMoveCursor(key, es),
+ .ARROW_UP, .ARROW_DOWN, .ARROW_LEFT, .ARROW_RIGHT, .PAGE_UP, .PAGE_DOWN, .HOME, .END => editorMoveCursor(key, es),
else => {},
}
},
}
}
-fn editorMoveCursor(key: editorKey, es: *EditorState) !void {
+fn editorVMove(dir: enum{up,down}, n: usize, es: *EditorState) void {
+ es.cy = switch (dir) {
+ .up => std.math.sub(usize, es.cy, n) catch 0,
+ .down => std.math.clamp(es.cy+n, 0, es.erow.len-1),
+ };
+}
+
+fn editorMoveCursor(key: editorKey, es: *EditorState) void {
switch (key.virt) {
.ARROW_UP => {
- if (es.cy > 0) es.cy -= 1;
+ editorVMove(.up, 1, es);
},
.ARROW_DOWN => {
- if (es.cy < es.erow.len) es.cy += 1;
+ editorVMove(.down, 1, es);
},
.ARROW_LEFT => {
- if (es.cx > 0) es.cx -= 1;
+ if (es.cx_t == 0) {
+ if (es.cy > 0) {
+ es.cy -= 1;
+ es.cx_t = es.erow[es.cy].len;
+ }
+ } else {
+ if (es.cx_t == std.math.maxInt(usize)) {
+ es.cx_t = es.erow[es.cy].len-1;
+ } else {
+ es.cx_t -= 1;
+ }
+ }
},
.ARROW_RIGHT => {
- es.cx += 1;
+ if (es.cx_t >= es.erow[es.cy].len) {
+ if (es.cy < (es.erow.len-1)) {
+ es.cy += 1;
+ es.cx_t = 0;
+ }
+ } else {
+ es.cx_t += 1;
+ }
},
.PAGE_UP => {
- es.cy = std.math.sub(usize, es.cy, es.screenrows) catch 0;
+ editorVMove(.up, es.screenrows, es);
},
.PAGE_DOWN => {
- es.cy = @min(es.cy+es.screenrows, es.erow.len-1);
+ editorVMove(.down, es.screenrows, es);
},
.HOME => {
- es.cx = 0;
+ es.cx_t = 0;
},
.END => {
- es.cx = es.screencols-1;
+ es.cx_t = std.math.maxInt(usize);
},
else => {},
}
+
+ es.cx = std.math.clamp(es.cx_t, 0, es.erow[es.cy].len);
}
//// Init