kiloz

Following through https://viewsourcecode.org/snaptoken/kilo/index.html in Zig
git clone git://code.mfashby.net:/kiloz
Log | Files | Refs | README

commit 049356ea597213f6209d7bb31b777d5be49cc97c
Author: Martin Ashby <martin@ashbysoft.com>
Date:   Sat,  6 Jan 2024 23:25:28 +0000

Initial commit

Diffstat:
A.gitignore | 2++
AREADME.md | 6++++++
Abuild.zig | 91+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Abuild.zig.zon | 62++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/c.zig | 0
Asrc/main.zig | 140+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/root.zig | 10++++++++++
7 files changed, 311 insertions(+), 0 deletions(-)

diff --git a/.gitignore b/.gitignore @@ -0,0 +1,2 @@ +zig-cache/ +zig-out/ diff --git a/README.md b/README.md @@ -0,0 +1,5 @@ +# kiloz + +https://viewsourcecode.org/snaptoken/kilo/ + +Following through a 'build your own' text editor, but in zig. +\ No newline at end of file diff --git a/build.zig b/build.zig @@ -0,0 +1,91 @@ +const std = @import("std"); + +// Although this function looks imperative, note that its job is to +// declaratively construct a build graph that will be executed by an external +// runner. +pub fn build(b: *std.Build) void { + // Standard target options allows the person running `zig build` to choose + // what target to build for. Here we do not override the defaults, which + // means any target is allowed, and the default is native. Other options + // for restricting supported target set are available. + const target = b.standardTargetOptions(.{}); + + // Standard optimization options allow the person running `zig build` to select + // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. Here we do not + // set a preferred release mode, allowing the user to decide how to optimize. + const optimize = b.standardOptimizeOption(.{}); + + const lib = b.addStaticLibrary(.{ + .name = "kiloz", + // In this case the main source file is merely a path, however, in more + // complicated build scripts, this could be a generated file. + .root_source_file = .{ .path = "src/root.zig" }, + .target = target, + .optimize = optimize, + }); + + // This declares intent for the library to be installed into the standard + // location when the user invokes the "install" step (the default step when + // running `zig build`). + b.installArtifact(lib); + + const exe = b.addExecutable(.{ + .name = "kiloz", + .root_source_file = .{ .path = "src/main.zig" }, + .target = target, + .optimize = optimize, + }); + + // This declares intent for the executable to be installed into the + // standard location when the user invokes the "install" step (the default + // step when running `zig build`). + b.installArtifact(exe); + + // This *creates* a Run step in the build graph, to be executed when another + // step is evaluated that depends on it. The next line below will establish + // such a dependency. + const run_cmd = b.addRunArtifact(exe); + + // By making the run step depend on the install step, it will be run from the + // installation directory rather than directly from within the cache directory. + // This is not necessary, however, if the application depends on other installed + // files, this ensures they will be present and in the expected location. + run_cmd.step.dependOn(b.getInstallStep()); + + // This allows the user to pass arguments to the application in the build + // command itself, like this: `zig build run -- arg1 arg2 etc` + if (b.args) |args| { + run_cmd.addArgs(args); + } + + // This creates a build step. It will be visible in the `zig build --help` menu, + // and can be selected like this: `zig build run` + // This will evaluate the `run` step rather than the default, which is "install". + const run_step = b.step("run", "Run the app"); + run_step.dependOn(&run_cmd.step); + + // Creates a step for unit testing. This only builds the test executable + // but does not run it. + const lib_unit_tests = b.addTest(.{ + .root_source_file = .{ .path = "src/root.zig" }, + .target = target, + .optimize = optimize, + }); + + const run_lib_unit_tests = b.addRunArtifact(lib_unit_tests); + + const exe_unit_tests = b.addTest(.{ + .root_source_file = .{ .path = "src/main.zig" }, + .target = target, + .optimize = optimize, + }); + + const run_exe_unit_tests = b.addRunArtifact(exe_unit_tests); + + // Similar to creating the run step earlier, this exposes a `test` step to + // the `zig build --help` menu, providing a way for the user to request + // running the unit tests. + const test_step = b.step("test", "Run unit tests"); + test_step.dependOn(&run_lib_unit_tests.step); + test_step.dependOn(&run_exe_unit_tests.step); +} diff --git a/build.zig.zon b/build.zig.zon @@ -0,0 +1,62 @@ +.{ + .name = "kiloz", + // This is a [Semantic Version](https://semver.org/). + // In a future version of Zig it will be used for package deduplication. + .version = "0.0.0", + + // This field is optional. + // This is currently advisory only; Zig does not yet do anything + // with this value. + //.minimum_zig_version = "0.11.0", + + // This field is optional. + // Each dependency must either provide a `url` and `hash`, or a `path`. + // `zig build --fetch` can be used to fetch all dependencies of a package, recursively. + // Once all dependencies are fetched, `zig build` no longer requires + // Internet connectivity. + .dependencies = .{ + // See `zig fetch --save <url>` for a command-line interface for adding dependencies. + //.example = .{ + // // When updating this field to a new URL, be sure to delete the corresponding + // // `hash`, otherwise you are communicating that you expect to find the old hash at + // // the new URL. + // .url = "https://example.com/foo.tar.gz", + // + // // This is computed from the file contents of the directory of files that is + // // obtained after fetching `url` and applying the inclusion rules given by + // // `paths`. + // // + // // This field is the source of truth; packages do not come from an `url`; they + // // come from a `hash`. `url` is just one of many possible mirrors for how to + // // obtain a package matching this `hash`. + // // + // // Uses the [multihash](https://multiformats.io/multihash/) format. + // .hash = "...", + // + // // When this is provided, the package is found in a directory relative to the + // // build root. In this case the package's hash is irrelevant and therefore not + // // computed. This field and `url` are mutually exclusive. + // .path = "foo", + //}, + }, + + // Specifies the set of files and directories that are included in this package. + // Only files and directories listed here are included in the `hash` that + // is computed for this package. + // Paths are relative to the build root. Use the empty string (`""`) to refer to + // the build root itself. + // A directory listed here means that all files within, recursively, are included. + .paths = .{ + // This makes *all* files, recursively, included in this package. It is generally + // better to explicitly list the files and directories instead, to insure that + // fetching from tarballs, file system paths, and version control all result + // in the same contents hash. + "", + // For example... + //"build.zig", + //"build.zig.zon", + //"src", + //"LICENSE", + //"README.md", + }, +} diff --git a/src/c.zig b/src/c.zig diff --git a/src/main.zig b/src/main.zig @@ -0,0 +1,140 @@ +const std = @import("std"); + +const quit = 17; // ctrl+q + +pub fn main() !void { + var es: EditorState = .{}; + es.termios_orig = try enterRawMode(); + defer disableRawMode(&es.termios_orig); + defer clearScreen(); + + try initEditor(&es); + + while (true) { + try editorRefreshScreen(es); + + editorProcessKeyPress() catch |e| switch (e) { + error.Quit => return, + else => return e, + }; + } +} + +//// Data + +const EditorState = struct { + termios_orig: std.os.linux.termios = undefined, + screenrows: u16 = 0, + screencols: u16 = 0, +}; + +//// Terminal handling + +// Returns the original termios setting for restoring terminal function at exit. +fn enterRawMode() !std.os.linux.termios { + var termios_orig: std.os.linux.termios = undefined; + if (std.os.linux.tcgetattr(std.os.linux.STDIN_FILENO, &termios_orig) != 0) return error.TcGetAttr; + var termios_raw = termios_orig; + termios_raw.iflag &= ~(std.os.linux.IXON | std.os.linux.ICRNL | std.os.linux.BRKINT | std.os.linux.INPCK | std.os.linux.ISTRIP); + termios_raw.lflag &= ~(std.os.linux.ECHO | std.os.linux.ICANON | std.os.linux.ISIG | std.os.linux.IEXTEN); + termios_raw.oflag &= ~(std.os.linux.OPOST); + termios_raw.cflag |= ~(std.os.linux.CS8); + termios_raw.cc[std.os.linux.V.MIN] = 0; + termios_raw.cc[std.os.linux.V.TIME] = 1; + if (std.os.linux.tcsetattr(std.os.linux.STDIN_FILENO, .FLUSH, &termios_raw) != 0) return error.TcSetAttr; + return termios_orig; +} + +fn disableRawMode(t: *const std.os.linux.termios) void { + if (std.os.linux.tcsetattr(std.os.linux.STDIN_FILENO, .FLUSH, t) != 0) { + std.fmt.format(std.io.getStdErr().writer(), "Error resetting terminal, it might be broken\r\n", .{}) catch {}; + } +} + +fn editorReadKey() !u8 { + var rdr = std.io.getStdIn().reader(); + while (true) { + return rdr.readByte() catch |e| switch (e) { + error.EndOfStream => continue, + else => return e, + }; + } +} + +fn getCursorPosition() !Size { + const wtr = std.io.getStdOut().writer(); + var rdr = std.io.getStdIn().reader(); + try wtr.writeAll("\x1b[6n"); + try wtr.writeAll("\r\n"); + var buf = [_]u8{0} ** 32; + try rdr.skipBytes(2, .{}); + const szstr = try rdr.readUntilDelimiter(&buf, 'R'); + var spl = std.mem.splitScalar(u8, szstr, ';'); + const rowsstr = spl.first(); + const colsstr = spl.next() orelse return error.CursorPosFormatError; + const rows = try std.fmt.parseInt(u16, rowsstr, 10); + const cols = try std.fmt.parseInt(u16, colsstr, 10); + return .{ .rows = rows, .cols = cols }; +} + +const Size = struct { + rows: u16, + cols: u16, +}; + +fn getWindowSize() !Size { + var out = std.io.getStdOut(); + var wsz: std.os.linux.winsize = undefined; + if (std.os.linux.ioctl(out.handle, std.os.linux.T.IOCGWINSZ, @intFromPtr(&wsz)) == -1 or wsz.ws_col == 0) { + // Hack: move teh cursor then read it's position + try out.writer().writeAll("\x1b[999C\x1b[999B"); + return getCursorPosition(); + } else { + return .{ + .rows = wsz.ws_row, + .cols = wsz.ws_col, + }; + } +} + +//// Output + +fn editorRefreshScreen(es: EditorState) !void { + // Check the vt100 manual! + const wtr = std.io.getStdOut().writer(); + try wtr.writeAll("\x1b[2J"); + try wtr.writeAll("\x1b[H"); + try editorDrawRows(es); + try wtr.writeAll("\x1b[H"); +} + +fn clearScreen() void { + const wtr = std.io.getStdOut().writer(); + wtr.writeAll("\x1b[2J") catch {}; + wtr.writeAll("\x1b[H") catch {}; +} + +fn editorDrawRows(es: EditorState) !void { + const wtr = std.io.getStdOut().writer(); + for (0..(es.screenrows - 1)) |_| { + try wtr.writeAll("~\r\n"); + } +} + +//// Input + +fn editorProcessKeyPress() !void { + const ch = try editorReadKey(); + switch (ch) { + quit => return error.Quit, + else => {}, + } +} + +//// Init + +fn initEditor(es: *EditorState) !void { + const sz = try getWindowSize(); + es.screenrows = sz.rows; + es.screencols = sz.cols; +} diff --git a/src/root.zig b/src/root.zig @@ -0,0 +1,10 @@ +const std = @import("std"); +const testing = std.testing; + +export fn add(a: i32, b: i32) i32 { + return a + b; +} + +test "basic add functionality" { + try testing.expect(add(3, 7) == 10); +}