From 6784995988072263899fe3f730d7245034e9ff80 Mon Sep 17 00:00:00 2001 From: sirlilpanda Date: Thu, 18 Jun 2026 08:52:42 +1200 Subject: [PATCH] init --- .gitignore | 2 + build.zig | 156 +++++ build.zig.zon | 81 +++ readme.md | 109 +++ src/editor.zig | 125 ++++ src/main.zig | 71 ++ src/pieceTable.zig | 1635 ++++++++++++++++++++++++++++++++++++++++++++ src/root.zig | 18 + 8 files changed, 2197 insertions(+) create mode 100644 .gitignore create mode 100644 build.zig create mode 100644 build.zig.zon create mode 100644 readme.md create mode 100644 src/editor.zig create mode 100644 src/main.zig create mode 100644 src/pieceTable.zig create mode 100644 src/root.zig diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0ea71a8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +.zig-cache/ +zig-out/ \ No newline at end of file diff --git a/build.zig b/build.zig new file mode 100644 index 0000000..db985eb --- /dev/null +++ b/build.zig @@ -0,0 +1,156 @@ +const std = @import("std"); + +// Although this function looks imperative, it does not perform the build +// directly and instead it mutates the build graph (`b`) that will be then +// executed by an external runner. The functions in `std.Build` implement a DSL +// for defining build steps and express dependencies between them, allowing the +// build runner to parallelize the build automatically (and the cache system to +// know when a step doesn't need to be re-run). +pub fn build(b: *std.Build) void { + // Standard target options allow 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(.{}); + // It's also possible to define more custom flags to toggle optional features + // of this build script using `b.option()`. All defined flags (including + // target and optimize options) will be listed when running `zig build --help` + // in this directory. + + // This creates a module, which represents a collection of source files alongside + // some compilation options, such as optimization mode and linked system libraries. + // Zig modules are the preferred way of making Zig code available to consumers. + // addModule defines a module that we intend to make available for importing + // to our consumers. We must give it a name because a Zig package can expose + // multiple modules and consumers will need to be able to specify which + // module they want to access. + const mod = b.addModule("pieces", .{ + // The root source file is the "entry point" of this module. Users of + // this module will only be able to access public declarations contained + // in this file, which means that if you have declarations that you + // intend to expose to consumers that were defined in other files part + // of this module, you will have to make sure to re-export them from + // the root file. + .root_source_file = b.path("src/root.zig"), + // Later on we'll use this module as the root module of a test executable + // which requires us to specify a target. + .target = target, + }); + + // Here we define an executable. An executable needs to have a root module + // which needs to expose a `main` function. While we could add a main function + // to the module defined above, it's sometimes preferable to split business + // logic and the CLI into two separate modules. + // + // If your goal is to create a Zig library for others to use, consider if + // it might benefit from also exposing a CLI tool. A parser library for a + // data serialization format could also bundle a CLI syntax checker, for example. + // + // If instead your goal is to create an executable, consider if users might + // be interested in also being able to embed the core functionality of your + // program in their own executable in order to avoid the overhead involved in + // subprocessing your CLI tool. + // + // If neither case applies to you, feel free to delete the declaration you + // don't need and to put everything under a single module. + const exe = b.addExecutable(.{ + .name = "pieces", + .root_module = b.createModule(.{ + // b.createModule defines a new module just like b.addModule but, + // unlike b.addModule, it does not expose the module to consumers of + // this package, which is why in this case we don't have to give it a name. + .root_source_file = b.path("src/main.zig"), + // Target and optimization levels must be explicitly wired in when + // defining an executable or library (in the root module), and you + // can also hardcode a specific target for an executable or library + // definition if desireable (e.g. firmware for embedded devices). + .target = target, + .optimize = optimize, + // List of modules available for import in source files part of the + // root module. + .imports = &.{ + // Here "pieces" is the name you will use in your source code to + // import this module (e.g. `@import("pieces")`). The name is + // repeated because you are allowed to rename your imports, which + // can be extremely useful in case of collisions (which can happen + // importing modules from different packages). + .{ .name = "pieces", .module = mod }, + }, + }), + }); + + // This declares intent for the executable to be installed into the + // install prefix when running `zig build` (i.e. when executing the default + // step). By default the install prefix is `zig-out/` but can be overridden + // by passing `--prefix` or `-p`. + b.installArtifact(exe); + + // This creates a top level step. Top level steps have a name and can be + // invoked by name when running `zig build` (e.g. `zig build run`). + // This will evaluate the `run` step rather than the default step. + // For a top level step to actually do something, it must depend on other + // steps (e.g. a Run step, as we will see in a moment). + const run_step = b.step("run", "Run the app"); + + // This creates a RunArtifact step in the build graph. A RunArtifact step + // invokes an executable compiled by Zig. Steps will only be executed by the + // runner if invoked directly by the user (in the case of top level steps) + // or if another step depends on it, so it's up to you to define when and + // how this Run step will be executed. In our case we want to run it when + // the user runs `zig build run`, so we create a dependency link. + const run_cmd = b.addRunArtifact(exe); + run_step.dependOn(&run_cmd.step); + + // By making the run step depend on the default step, it will be run from the + // installation directory rather than directly from within the cache directory. + 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); + } + + // Creates an executable that will run `test` blocks from the provided module. + // Here `mod` needs to define a target, which is why earlier we made sure to + // set the releative field. + const mod_tests = b.addTest(.{ + .root_module = mod, + }); + + // A run step that will run the test executable. + const run_mod_tests = b.addRunArtifact(mod_tests); + + // Creates an executable that will run `test` blocks from the executable's + // root module. Note that test executables only test one module at a time, + // hence why we have to create two separate ones. + const exe_tests = b.addTest(.{ + .root_module = exe.root_module, + }); + + // A run step that will run the second test executable. + const run_exe_tests = b.addRunArtifact(exe_tests); + + // A top level step for running all tests. dependOn can be called multiple + // times and since the two run steps do not depend on one another, this will + // make the two of them run in parallel. + const test_step = b.step("test", "Run tests"); + test_step.dependOn(&run_mod_tests.step); + test_step.dependOn(&run_exe_tests.step); + + // Just like flags, top level steps are also listed in the `--help` menu. + // + // The Zig build system is entirely implemented in userland, which means + // that it cannot hook into private compiler APIs. All compilation work + // orchestrated by the build system will result in other Zig compiler + // subcommands being invoked with the right flags defined. You can observe + // these invocations when one fails (or you pass a flag to increase + // verbosity) to validate assumptions and diagnose problems. + // + // Lastly, the Zig build system is relatively simple and self-contained, + // and reading its source code will allow you to master it. +} diff --git a/build.zig.zon b/build.zig.zon new file mode 100644 index 0000000..892d57d --- /dev/null +++ b/build.zig.zon @@ -0,0 +1,81 @@ +.{ + // This is the default name used by packages depending on this one. For + // example, when a user runs `zig fetch --save `, this field is used + // as the key in the `dependencies` table. Although the user can choose a + // different name, most users will stick with this provided value. + // + // It is redundant to include "zig" in this name because it is already + // within the Zig package namespace. + .name = .pieces, + // 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", + // Together with name, this represents a globally unique package + // identifier. This field is generated by the Zig toolchain when the + // package is first created, and then *never changes*. This allows + // unambiguous detection of one package being an updated version of + // another. + // + // When forking a Zig project, this id should be regenerated (delete the + // field and run `zig build`) if the upstream project is still maintained. + // Otherwise, the fork is *hostile*, attempting to take control over the + // original project's identity. Thus it is recommended to leave the comment + // on the following line intact, so that it shows up in code reviews that + // modify the field. + .fingerprint = 0xb92d747230a318f2, // Changing this has security and trust implications. + // Tracks the earliest Zig version that the package considers to be a + // supported use case. + .minimum_zig_version = "0.16.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 ` 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. If the contents of a URL change this will result in a hash mismatch + // // which will prevent zig from using it. + // .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 a `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", + // + // // When this is set to `true`, a package is declared to be lazily + // // fetched. This makes the dependency only get fetched if it is + // // actually used. + // .lazy = false, + //}, + }, + // 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. Only files listed here will remain on disk + // when using the zig package manager. As a rule of thumb, one should list + // files required for compilation plus any license(s). + // 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 = .{ + "build.zig", + "build.zig.zon", + "src", + // For example... + //"LICENSE", + //"README.md", + }, +} diff --git a/readme.md b/readme.md new file mode 100644 index 0000000..2712262 --- /dev/null +++ b/readme.md @@ -0,0 +1,109 @@ +feats. i want to add + - image rendering + - 3d object rendering + - text editor can be used as a lib + - lsp or treesitter + - plugins + NO AI PLUGINS + graphing calculator + image renderer + 3d object renderer + tabulated dataviewer + pdf rendering + - NO USE OF AI IN DEVELOPMENT OR WITHIN THE EDITOR AND THIS WILL NEVER CHANGE + - maybe some animations???? + - UTF8 support + + +idea for code structure + +- editor + - editor + - piece table + - text search + +- file view + +- renderer + - tui + - gui + +- plugins + - images + - calculator + +- core + + +editor -> piece table -> writes to buffer -> sends to LSP -> lsp syntax highlights -> send to renderer (sdl3) + | + +--> + + + +TODO add new line optimisation like vscode +TODO implement sequential delete so when the + +piece table implemention attempts to optimise the fuck out of inputting and deleting sequential data + + +add: + piece table delete undo increasing indeces with same text does not add any addtional pieces + +editor +``` +insert +delete + +find + +replace +replaceAll +replaceSome + +newCursor +newCursorFromSelection + +cursorUp +cursorDown +cursorLeft +cursorRight + +cursorEndOfLine +cursorStartOfLine +cursorStartOfFile +cursorEndOfFile + +cursorToNextWord +cursorToNextUnderScore +cursorToNextUnderCaptial + +toggleSelectionMode +getSelection + +copySelection +pasteSelection +cutSelection +deleteSelection + +// follows cursor rules +moveSelectionUp +moveSelectionDown +moveSelectionRight +moveSelectionLeft + +incrementSelection +decrementSelection +addXToSelection + +moveLineUp +moveLineDown + +cutLine +pasteLine + +undo +redo + +writeTo +readFrom \ No newline at end of file diff --git a/src/editor.zig b/src/editor.zig new file mode 100644 index 0000000..10b5ae8 --- /dev/null +++ b/src/editor.zig @@ -0,0 +1,125 @@ +const pieceTable = @import("pieceTable.zig"); +const std = @import("std"); + +pub const Cursor = struct { + pos: usize, + selection: usize, +}; + +pub const Editor = struct { + const Self = @This(); + + buffer: pieceTable.PieceTable, + input_buffer: std.ArrayList(u8) = .empty, // where all the inputs are saved + cursors: std.ArrayList(Cursor) = .empty, + + pub fn init(text: []const u8, alloc: std.mem.Allocator) !Self { + var self = Self{}; + try self.cursors.append(alloc, Cursor{ + .pos = 0, + .selection = 0, + }); + try self.buffer.insert( + alloc, + .{ + .length = text.len, + .start = 0, + .text = &text, + }, + 0, + ); + return self; + } + + pub fn insertChar(self: *Self, alloc: std.mem.Allocator, char: u8) !void { + for (self.cursors) |c| { + try self.input_buffer.append(alloc, char); + try self.buffer.insert(alloc, .{ + .length = 1, + .start = 0, + .text = &self.input_buffer, + }, c.pos); + } + } + + pub fn insertString(self: *Self, alloc: std.mem.Allocator, str: []const u8) !void { + for (self.cursors) |c| { + try self.input_buffer.appendSlice(alloc, str); + try self.buffer.insert(alloc, .{ + .length = 1, + .start = 0, + .text = &self.input_buffer, + }, c.pos); + } + } + + pub fn deleteChar(self: *Self, alloc: std.mem.Allocator) !void { + for (self.cursors) |c| { + try self.buffer.delete(alloc, c.pos, c.pos + 1); + } + } + + // todo implemnt this + // pub fn delete(self : *Self) + + // pub fn find + + // pub fn replace + // pub fn replaceAll + // pub fn replaceSome + + // pub fn newCursor + // pub fn newCursorFromSelection + + // pub fn cursorUp + // pub fn cursorDown + // pub fn cursorLeft + // pub fn cursorRight + + // pub fn cursorUpByX + // pub fn cursorDownByX + // pub fn cursorLeftByX + // pub fn cursorRightByX + + // pub fn cursorEndOfLine + // pub fn cursorStartOfLine + // pub fn cursorStartOfFile + // pub fn cursorEndOfFile + + // pub fn cursorToNextWord + // pub fn cursorToNextUnderScore + // pub fn cursorToNextUnderCaptial + + // pub fn toggleSelectionMode + // pub fn getSelection + + // pub fn copySelection + // pub fn pasteSelection + // pub fn cutSelection + // pub fn deleteSelection + + // pub fn // follows cursor rules + // pub fn moveSelectionUp + // pub fn moveSelectionDown + // pub fn moveSelectionRight + // pub fn moveSelectionLeft + + // pub fn incrementSelection + // pub fn decrementSelection + // pub fn addXToSelection + + // pub fn moveLineUp + // pub fn moveLineDown + + // pub fn cutLine + // pub fn pasteLine + + // pub fn undo + // pub fn redo + + // pub fn resetUndos + + // pub fn writeTo + // pub fn readFrom + +}; diff --git a/src/main.zig b/src/main.zig new file mode 100644 index 0000000..8d0602e --- /dev/null +++ b/src/main.zig @@ -0,0 +1,71 @@ +const std = @import("std"); +const Io = std.Io; + +const pieces = @import("pieces"); + +pub fn main(init: std.process.Init) !void { + // Prints to stderr, unbuffered, ignoring potential errors. + std.debug.print("All your {s} are belong to us.\n", .{"codebase"}); + + // This is appropriate for anything that lives as long as the process. + const arena: std.mem.Allocator = init.arena.allocator(); + + // Accessing command line arguments: + const args = try init.minimal.args.toSlice(arena); + for (args) |arg| { + std.log.info("arg: {s}", .{arg}); + } + + // In order to do I/O operations need an `Io` instance. + const io = init.io; + + // Stdout is for the actual output of your application, for example if you + // are implementing gzip, then only the compressed bytes should be sent to + // stdout, not any debugging messages. + var stdout_buffer: [1024]u8 = undefined; + var stdout_file_writer: Io.File.Writer = .init(.stdout(), io, &stdout_buffer); + const stdout_writer = &stdout_file_writer.interface; + + try pieces.printAnotherMessage(stdout_writer); + + try stdout_writer.flush(); // Don't forget to flush! +} + +test "simple test" { + const gpa = std.testing.allocator; + var list: std.ArrayList(i32) = .empty; + defer list.deinit(gpa); // Try commenting this out and see if zig detects the memory leak! + try list.append(gpa, 42); + try std.testing.expectEqual(@as(i32, 42), list.pop()); +} + +test "fuzz example" { + try std.testing.fuzz({}, testOne, .{}); +} + +fn testOne(context: void, smith: *std.testing.Smith) !void { + _ = context; + // Try passing `--fuzz` to `zig build test` and see if it manages to fail this test case! + + const gpa = std.testing.allocator; + var list: std.ArrayList(u8) = .empty; + defer list.deinit(gpa); + while (!smith.eos()) switch (smith.value(enum { add_data, dup_data })) { + .add_data => { + const slice = try list.addManyAsSlice(gpa, smith.value(u4)); + smith.bytes(slice); + }, + .dup_data => { + if (list.items.len == 0) continue; + if (list.items.len > std.math.maxInt(u32)) return error.SkipZigTest; + const len = smith.valueRangeAtMost(u32, 1, @min(32, list.items.len)); + const off = smith.valueRangeAtMost(u32, 0, @intCast(list.items.len - len)); + try list.appendSlice(gpa, list.items[off..][0..len]); + try std.testing.expectEqualSlices( + u8, + list.items[off..][0..len], + list.items[list.items.len - len ..], + ); + }, + }; +} diff --git a/src/pieceTable.zig b/src/pieceTable.zig new file mode 100644 index 0000000..c72e50a --- /dev/null +++ b/src/pieceTable.zig @@ -0,0 +1,1635 @@ +//! By convention, root.zig is the root source file when making a package. +const std = @import("std"); +const Io = std.Io; + +pub const Piece = struct { + // each piece could just be a slice however this make it easier to write + start: usize, + length: usize, + + text: *const []const u8, + + const nothing: []const u8 = ""; + + pub const none = Piece{ + .start = 0, + .length = 0, + .text = ¬hing, + }; + + pub fn format(self: Piece, writer: *std.Io.Writer) !void { + try writer.print( + "piece {{src@{ptr}[{},{}] : \"{s}\"}}", + .{ self.text, self.start, self.length, self.str() }, + ); + } + + pub fn str(self: Piece) []const u8 { + return self.text.*[self.start .. self.start + self.length]; + } + + pub fn eq(self: Piece, other: Piece) bool { + if (self.start != other.start) return false; + if (self.length != other.length) return false; + if (self.text != other.text) return false; + return true; + } +}; + +pub const ActionType = enum { + append, + insert, + insert_splits_piece, + insert_sequential, + delete, + delete_splits_piece, + delete_sequential, +}; + +const Action = struct { + piece_table_index: usize, + old_start: usize, + old_length: usize, +}; + +pub const ActionGroup = struct { + const PieceRedo = struct { + piece: Piece, + index: usize, + }; + + const DeleteRedo = struct { + from: usize, + to: usize, + }; + + /// holds the min amount of info inorder to restore a change + undo_action: union(ActionType) { + /// this will only occur when the table was already empty so boof it + append: void, + + /// happens when a piece is cleanly inserted in to the table + insert: usize, + + /// happens when the piece requires to be split before indexing + insert_splits_piece: Action, + + insert_sequential: usize, + + /// happens when a piece is deletes (length set to zero) + /// appends all modifed pieces to be restored + delete: std.ArrayList(Action), + + delete_splits_piece: Action, + + delete_sequential: Action, + }, + + /// just keeps the function args, best way to redo something is to redo it + redo_action: union(ActionType) { + append: Piece, + insert: PieceRedo, + insert_splits_piece: PieceRedo, + insert_sequential: PieceRedo, + delete: DeleteRedo, + delete_splits_piece: DeleteRedo, + delete_sequential: DeleteRedo, + }, +}; + +/// abstracted so i can implement redo +const ActionList = struct { + const Self = @This(); + + actions: std.ArrayList(ActionGroup) = .empty, + + /// offsets from the last index i down to zero + undo_offset: usize = 0, + + pub const empty = ActionList{}; + + pub fn append(self: *Self, alloc: std.mem.Allocator, action_group: ActionGroup) !void { + if (self.undo_offset != 0) { + try self.actions.resize(alloc, self.actions.items.len - 1 - self.undo_offset); + self.undo_offset = 0; + } + + try self.actions.append(alloc, action_group); + } + + pub fn undo(self: *Self) ?ActionGroup { + if (self.undo_offset == self.actions.items.len) return null; + defer self.undo_offset += 1; + return self.actions.items[self.actions.items.len - 1 - self.undo_offset]; + } + + pub fn redo(self: *Self) ?ActionGroup { + if (self.undo_offset == 0) return null; + self.undo_offset -= 1; + return self.actions.items[self.actions.items.len - 1 - self.undo_offset]; + } + + pub fn deinit(self: *Self, alloc: std.mem.Allocator) void { + for (self.actions.items) |*act| { + switch (act.undo_action) { + .delete => act.undo_action.delete.deinit(alloc), + else => continue, + } + } + self.actions.deinit(alloc); + } +}; + +/// piece table with built in undo +/// since the piece table is going in a text editor +/// if you dont have undo is not going to be a very +/// good text editor we aint trying to be ed here +pub const PieceTable = struct { + const Self = @This(); + const Alloc = std.mem.Allocator; + + var base_piece: Piece = .none; + debug: bool = false, + pieces: std.ArrayList(Piece) = .empty, + actions: ActionList = .empty, + + // these are used to speed up writing continous text + last_index: usize = 0, + + // both a pointer to the last piece and the index of it + last_piece_index: usize = 0, + last_piece: *Piece = &base_piece, + + // i have this here because its easy + // total_len: usize = 0, + + pub fn init() Self { + return Self{}; + } + + /// self : piece table that is being operated on + /// alloc : allocator used for adding to the arraylists + /// piece : the piece to add + /// index : the index in the text where the new piece will be added + pub fn insert(self: *Self, alloc: Alloc, piece: Piece, index: usize) !void { + return self.insertWActionDisable(alloc, piece, index, false); + } + + /// will delete all from (index) to (index) non inclusive of "to" index + /// this function assumes when you delete from piece table you also delete from the input buffer + /// self : piece table that is being operated on + /// alloc : allocator used for adding the actions to the action list. + /// from : the index to be deleted from + /// to : the index the deletion will stop + pub fn delete(self: *Self, alloc: std.mem.Allocator, from: usize, to: usize) !void { + return self.deleteWActionDisable(alloc, from, to, false); + } + + fn deleteWActionDisable(self: *Self, alloc: std.mem.Allocator, from: usize, to: usize, action_disabled: bool) !void { + + // we know that we are just removing from the piece that has been added to sequentially + std.debug.print("{} == {} and {} - {} == 1\n", .{ + self.last_index, + from, + to, + from, + }); + if (self.last_index == from and to - from == 1) { + std.debug.print("delete sequentially\n", .{}); + if (!action_disabled) try self.actions.append(alloc, ActionGroup{ + .undo_action = .{ .delete_sequential = .{ + .old_length = self.last_piece.length, + .old_start = self.last_piece.start, + .piece_table_index = self.last_piece_index, + } }, + .redo_action = .{ .delete_sequential = .{ + .from = from, + .to = to, + } }, + }); + std.debug.print("last piece {f}\n", .{self.last_piece}); + self.last_index -|= 1; + self.last_piece.length -|= 1; + std.debug.print("last piece {f}\n", .{self.last_piece}); + + return; + } + + // when you delete text the input buffer of the keyboard becomes unaligned so just instead it will add a new piece + self.last_piece = &base_piece; + + var currnet_string_index: usize = 0; + var edited_piece_index: usize = 0; + var delete_actions: std.ArrayList(Action) = .empty; + std.debug.print("from : {}, to : {}\n", .{ from, to }); + + // from set + for (self.pieces.items, 0..) |p, i| { + // std.debug.print("piece {f}\n", .{p}); + // std.debug.print("currnet_string_index {} + p.length {} = {}\n", .{ currnet_string_index, p.length, currnet_string_index + p.length }); + std.debug.print("from {} , to {}\n", .{ currnet_string_index + p.length > from, currnet_string_index + p.length >= to }); + // find the index where the split occurs + if (currnet_string_index + p.length > from and currnet_string_index + p.length >= to) { + // we gotta split the piece + std.debug.print("split piece\n", .{}); + const pieces = [2]Piece{ + Piece{ + .text = p.text, + .start = p.start, + .length = from - currnet_string_index, + }, + Piece{ + .text = p.text, + .start = p.start + (to - currnet_string_index), + .length = p.length - (to - currnet_string_index), + }, + }; + + try self.pieces.replaceRange(alloc, i, 1, &pieces); + + if (!action_disabled) try self.actions.append(alloc, ActionGroup{ + .undo_action = .{ .delete_splits_piece = .{ + .old_length = p.length, + .old_start = p.start, + .piece_table_index = i, + } }, + .redo_action = .{ .delete_splits_piece = .{ + .from = from, + .to = to, + } }, + }); + + // since it splits the current piece, the piece that was added is actually at index i + 1 + + return; + } + + if (currnet_string_index + p.length > from and from > currnet_string_index) { + std.debug.print("trim\n", .{}); + // already handled the split condtion so now it should just be a simple change in length + // std.debug.print("splt\n", .{}); + var current_piece = &self.pieces.items[i]; + + std.debug.print("current_piece : {f}\n", .{current_piece}); + + if (!action_disabled) try delete_actions.append( + alloc, + Action{ + .piece_table_index = i, + .old_start = current_piece.start, + .old_length = current_piece.length, + }, + ); + + current_piece.length -= from - currnet_string_index; + edited_piece_index = i + 1; + currnet_string_index += p.length; + std.debug.print("from {} - currnet_string_index{}\n", .{ from, currnet_string_index }); + std.debug.print("current_piece : {f}\n", .{current_piece}); + + break; + } + if (currnet_string_index + p.length <= from) currnet_string_index += p.length; + } + + // to set + std.debug.print("currnet_string_index : {}, edited_piece_index : {}\n", .{ currnet_string_index, edited_piece_index }); + // self.debug = true; + // std.debug.print("edited_piece_index : {}\n", .{edited_piece_index}); + // std.debug.print("first delete half : {f}\n", .{self}); + // self.debug = false; + + for (self.pieces.items[edited_piece_index..], edited_piece_index..) |p, i| { + // std.debug.print("currnet_string_index {} + p.length {} <= to {} = {}\n", .{ currnet_string_index, p.length, to, currnet_string_index + p.length <= to }); + std.debug.print("{} piece[{}] {f}\n", .{ edited_piece_index, i, p }); + if (currnet_string_index + p.length <= to) { + // std.debug.print("found piece to shrink\n", .{}); + std.debug.print("i = {}\n", .{i}); + var current_piece = &self.pieces.items[i]; + std.debug.print("current_piece : {f}\n", .{current_piece}); + + if (!action_disabled) try delete_actions.append( + alloc, + Action{ + .piece_table_index = i, + .old_start = current_piece.start, + .old_length = current_piece.length, + }, + ); + + current_piece.length = 0; + currnet_string_index += p.length; + // std.debug.print("current_piece : {f}\n", .{current_piece}); + continue; + } + + std.debug.print("currnet_string_index : {} + p.length : {} > to : {} = {}\n", .{ currnet_string_index, p.length, to, currnet_string_index + p.length > to }); + std.debug.print("current_piece : {f}\n", .{p}); + if (currnet_string_index + p.length > to) { + var current_piece = &self.pieces.items[i]; + + if (!action_disabled) try delete_actions.append( + alloc, + Action{ + .piece_table_index = i, + .old_start = current_piece.start, + .old_length = current_piece.length, + }, + ); + + std.debug.print("piece {f}\n", .{current_piece}); + // shrink it + current_piece.start += to - currnet_string_index; + current_piece.length -|= to - currnet_string_index; + std.debug.print("piece {f}\n", .{current_piece}); + + break; + } + } + + if (!action_disabled) try self.actions.append(alloc, ActionGroup{ + .undo_action = .{ .delete = delete_actions }, + .redo_action = .{ .delete = .{ .from = from, .to = to } }, + }); + } + + fn insertWActionDisable(self: *Self, alloc: Alloc, piece: Piece, index: usize, action_disabled: bool) !void { + var currnet_start: usize = 0; + // checks if we have just inserted + + std.debug.print("last : {}, index : {}\n", .{ self.last_index, index }); + std.debug.print("last : {ptr}, text : {ptr}\n", .{ self.last_piece.text, piece.text }); + if (index == self.last_index + 1 and self.last_piece.text == piece.text) { + std.debug.print("sequaintal keystroke\n", .{}); + self.last_piece.length += 1; + self.last_index = index; + + if (!action_disabled) try self.actions.append(alloc, ActionGroup{ + .undo_action = .{ + .insert_sequential = self.last_piece_index, + }, + .redo_action = .{ + .insert_sequential = .{ + .piece = piece, + .index = index, + }, + }, + }); + + return; + } + + for (self.pieces.items, 0..) |p, i| { + // find the index where the split occurs + + if (currnet_start + p.length > index) { + // we gotta split the piece + + const pieces: [3]Piece = [3]Piece{ + Piece{ + .text = p.text, + .start = p.start, + .length = index - currnet_start, + }, + piece, + Piece{ + .text = p.text, + .start = p.start + (index - currnet_start), + .length = p.length - (index - currnet_start), + }, + }; + + try self.pieces.replaceRange(alloc, i, 1, &pieces); + if (!action_disabled) try self.actions.append(alloc, ActionGroup{ + .undo_action = .{ + .insert_splits_piece = Action{ + .piece_table_index = i, + .old_length = p.length, + .old_start = p.start, + }, + }, + .redo_action = .{ .insert_splits_piece = .{ + .piece = piece, + .index = index, + } }, + }); + // since it splits the current piece, the piece that was added is actually at index i + 1 + self.last_index = index; + self.last_piece = &self.pieces.items[i + 1]; + self.last_piece_index = i + 1; + return; + } + if (currnet_start + p.length == index) { + try self.pieces.insert(alloc, i + 1, piece); + if (!action_disabled) try self.actions.append(alloc, ActionGroup{ + .undo_action = .{ .insert = i + 1 }, + .redo_action = .{ .insert = .{ + .piece = piece, + .index = index, + } }, + }); + + self.last_index = index; + self.last_piece = &self.pieces.items[i + 1]; + self.last_piece_index = i + 1; + + return; + } // just append after + if (currnet_start + p.length < index) currnet_start += p.length; + } + + // if there are no items this runs + try self.pieces.append(alloc, piece); + if (!action_disabled) try self.actions.append(alloc, ActionGroup{ + .undo_action = .append, + .redo_action = .{ .append = piece }, + }); + + self.last_index = index; + self.last_piece = &self.pieces.items[0]; + } + + pub fn redo(self: *Self, alloc: std.mem.Allocator) !void { + const action_group = self.actions.redo() orelse return; + + switch (action_group.redo_action) { + .append => |piece| { + try self.insertWActionDisable(alloc, piece, 0, true); + }, + .insert, .insert_splits_piece, .insert_sequential => |action| { + try self.insertWActionDisable(alloc, action.piece, action.index, true); + }, + .delete, .delete_splits_piece, .delete_sequential => |deletes| { + try self.deleteWActionDisable(alloc, deletes.from, deletes.to, true); + }, + } + } + + pub fn undo(self: *Self, alloc: std.mem.Allocator) !void { + var action_group = self.actions.undo() orelse return; + + // cant trust that when an undo occurs it wont mess with the input buffer + + switch (action_group.undo_action) { + .append => { + self.pieces.deinit(alloc); + self.pieces = .empty; + self.last_piece = &base_piece; + }, + .insert => |insert_index| { + _ = self.pieces.orderedRemove(insert_index); + self.last_piece = &base_piece; + }, + .insert_sequential => |insert_index| { + self.last_index -|= 1; + self.pieces.items[insert_index].length -|= 1; + std.debug.print("undo sequential\n", .{}); + }, + .insert_splits_piece => |action| { + + // remove the 2 addtional pieces + self.pieces.orderedRemoveMany(&.{ + action.piece_table_index + 1, + action.piece_table_index + 2, + }); + + const first_half_of_split_piece = &self.pieces.items[action.piece_table_index]; + first_half_of_split_piece.length = action.old_length; + first_half_of_split_piece.start = action.old_start; + self.last_piece = &base_piece; + }, + .delete => |deletes| { + for (deletes.items) |action| { + const piece = &self.pieces.items[action.piece_table_index]; + piece.length = action.old_length; + piece.start = action.old_start; + } + + action_group.undo_action.delete.deinit(alloc); + self.last_piece = &base_piece; + }, + .delete_splits_piece => |deletes| { + + // remove the added piece + _ = self.pieces.orderedRemove(deletes.piece_table_index + 1); + const piece = &self.pieces.items[deletes.piece_table_index]; + piece.length = deletes.old_length; + piece.start = deletes.old_start; + self.last_piece = &base_piece; + }, + .delete_sequential => { + self.last_index += 1; + self.last_piece.length += 1; + }, + } + } + + pub fn write(self: Self, writer: *std.Io.Writer) !void { + _ = try writer.write("pieces : {{\n"); + for (self.pieces.items, 0..) |p, i| { + try writer.print("{} : {f},\n", .{ i, p }); + } + _ = try writer.write("}}\noutput : \""); + try self.str(writer); + _ = try writer.write("\""); + } + + pub fn str(self: Self, writer: *std.Io.Writer) !void { + for (self.pieces.items) |p| { + _ = try writer.write(p.text.*[p.start .. p.start + p.length]); + } + } + + pub fn format(self: Self, writer: *std.Io.Writer) !void { + if (self.debug) { + _ = try self.write(writer); + return; + } + try self.str(writer); + } + + // pub fn undo(self: Self) !void {} + + pub fn deinit(self: *Self, alloc: std.mem.Allocator) void { + self.actions.deinit(alloc); + self.pieces.deinit(alloc); + } +}; + +const expect = std.testing.expect; + +// ========================================== insert ========================================== + +test "piece table insert in to empty table" { + const orignal_text: []const u8 = "damn these are some cool toads"; + + var piece_table = PieceTable.init(); + + try piece_table.insert(std.testing.allocator, .{ + .start = 0, + .length = orignal_text.len, + .text = &orignal_text, + }, 0); + + const text = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + + try expect(std.mem.eql(u8, text, orignal_text)); + + std.testing.allocator.free(text); + piece_table.deinit(std.testing.allocator); +} + +test "piece table insert another piece after first piece" { + const orignal_text: []const u8 = "damn these are some cool toads"; + const new_text: []const u8 = " and frogs"; + const expected_text: []const u8 = orignal_text ++ new_text; + + var piece_table = PieceTable.init(); + + try piece_table.insert(std.testing.allocator, .{ + .start = 0, + .length = orignal_text.len, + .text = &orignal_text, + }, 0); + + try piece_table.insert(std.testing.allocator, .{ + .start = 0, + .length = new_text.len, + .text = &new_text, + }, orignal_text.len); + + const text = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + + try expect(std.mem.eql(u8, text, expected_text)); + + std.testing.allocator.free(text); + piece_table.deinit(std.testing.allocator); +} + +test "piece table insert between pieces" { + const first_text: []const u8 = "damn these are some cool toads"; + const second_text: []const u8 = " and frogs"; + const new_text: []const u8 = " hat"; + + const expected_text: []const u8 = first_text ++ new_text ++ second_text; + + var piece_table = PieceTable.init(); + + try piece_table.insert(std.testing.allocator, .{ + .start = 0, + .length = first_text.len, + .text = &first_text, + }, 0); + + try piece_table.insert(std.testing.allocator, .{ + .start = 0, + .length = second_text.len, + .text = &second_text, + }, first_text.len); + + try piece_table.insert(std.testing.allocator, .{ + .start = 0, + .length = new_text.len, + .text = &new_text, + }, first_text.len); + + const text = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + + // std.debug.print("got \"{s}\"\n", .{text}); + // std.debug.print("wnt \"{s}\"\n", .{expected_text}); + // std.debug.print("eql {}\n", .{std.mem.eql(u8, text, expected_text)}); + + try expect(std.mem.eql(u8, text, expected_text)); + + defer std.testing.allocator.free(text); + defer piece_table.deinit(std.testing.allocator); +} + +test "piece table insert split pieces" { + const orignal_text: []const u8 = "damn these are some cool toads"; + const new_text: []const u8 = " not"; + const expected_text: []const u8 = "damn these are not some cool toads"; + + var piece_table = PieceTable.init(); + + try piece_table.insert(std.testing.allocator, .{ + .start = 0, + .length = orignal_text.len, + .text = &orignal_text, + }, 0); + + try piece_table.insert(std.testing.allocator, .{ + .start = 0, + .length = new_text.len, + .text = &new_text, + }, 14); + + const text = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + + // std.debug.print("got \"{s}\"\n", .{text}); + // std.debug.print("wnt \"{s}\"\n", .{expected_text}); + // std.debug.print("eql {}\n", .{std.mem.eql(u8, text, expected_text)}); + + try expect(std.mem.eql(u8, text, expected_text)); + + std.testing.allocator.free(text); + piece_table.deinit(std.testing.allocator); +} + +test "piece table insert increasing indeces with same text does not add any addtioanl pieces" { + const orignal_text: []const u8 = "damn these are some cool toads"; + const keyboard: []const u8 = " not"; + const expected_text = "damn these are not some cool toads"; + + var piece_table = PieceTable.init(); + + try piece_table.insert(std.testing.allocator, .{ + .start = 0, + .length = orignal_text.len, + .text = &orignal_text, + }, 0); + + for (keyboard, 0..) |_, i| { + try piece_table.insert(std.testing.allocator, .{ + .start = i, + .length = 1, + .text = &keyboard, + }, 14 + i); + } + + const text = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + + // std.debug.print("got \"{s}\"\n", .{text}); + // std.debug.print("wnt \"{s}\"\n", .{expected_text}); + // std.debug.print("eql {}\n", .{std.mem.eql(u8, text, expected_text)}); + + try expect(std.mem.eql(u8, text, expected_text)); + try expect(piece_table.pieces.items.len == 3); + + std.testing.allocator.free(text); + piece_table.deinit(std.testing.allocator); +} + +// ========================================== \insert ========================================== + +// ========================================== delete ========================================== + +test "piece table delete must split piece" { + const orignal_text: []const u8 = "damn these are some cool toads"; + const expected_text: []const u8 = "damn these are some toads"; + + var piece_table = PieceTable.init(); + + try piece_table.insert(std.testing.allocator, .{ + .start = 0, + .length = orignal_text.len, + .text = &orignal_text, + }, 0); + + try piece_table.delete(std.testing.allocator, 20, 25); + + const text = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + + std.debug.print("org \"{s}\"\n", .{orignal_text}); + std.debug.print("got \"{s}\"\n", .{text}); + std.debug.print("wnt \"{s}\"\n", .{expected_text}); + std.debug.print("eql {}\n", .{std.mem.eql(u8, text, expected_text)}); + + try expect(std.mem.eql(u8, text, expected_text)); + + std.testing.allocator.free(text); + piece_table.deinit(std.testing.allocator); +} + +test "piece table delete end of a piece" { + const orignal_text: []const u8 = "damn these are some cool toads"; + const expected_text: []const u8 = "damn these are some"; + + var piece_table = PieceTable.init(); + + try piece_table.insert(std.testing.allocator, .{ + .start = 0, + .length = orignal_text.len, + .text = &orignal_text, + }, 0); + + try piece_table.delete( + std.testing.allocator, + orignal_text.len - 11, + orignal_text.len, + ); + + const text = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + + std.debug.print("org \"{s}\"\n", .{orignal_text}); + std.debug.print("got \"{s}\"\n", .{text}); + std.debug.print("wnt \"{s}\"\n", .{expected_text}); + std.debug.print("eql {}\n", .{std.mem.eql(u8, text, expected_text)}); + + try expect(std.mem.eql(u8, text, expected_text)); + + std.testing.allocator.free(text); + piece_table.deinit(std.testing.allocator); +} + +test "piece table delete start of a piece" { + const orignal_text: []const u8 = "damn these are some cool toads"; + const expected_text: []const u8 = "cool toads"; + + var piece_table = PieceTable.init(); + + try piece_table.insert(std.testing.allocator, .{ + .start = 0, + .length = orignal_text.len, + .text = &orignal_text, + }, 0); + + try piece_table.delete( + std.testing.allocator, + 0, + 20, + ); + + const text = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + + std.debug.print("org \"{s}\"\n", .{orignal_text}); + std.debug.print("got \"{s}\"\n", .{text}); + std.debug.print("wnt \"{s}\"\n", .{expected_text}); + std.debug.print("eql {}\n", .{std.mem.eql(u8, text, expected_text)}); + + try expect(std.mem.eql(u8, text, expected_text)); + + std.testing.allocator.free(text); + piece_table.deinit(std.testing.allocator); +} + +test "piece table delete whole piece" { + const orignal_text: []const u8 = "damn these are some cool toads"; + const expected_text: []const u8 = ""; + + var piece_table = PieceTable.init(); + + try piece_table.insert(std.testing.allocator, .{ + .start = 0, + .length = orignal_text.len, + .text = &orignal_text, + }, 0); + + try piece_table.delete( + std.testing.allocator, + 0, + orignal_text.len, + ); + + const text = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + + std.debug.print("org \"{s}\"\n", .{orignal_text}); + std.debug.print("got \"{s}\"\n", .{text}); + std.debug.print("wnt \"{s}\"\n", .{expected_text}); + std.debug.print("eql {}\n", .{std.mem.eql(u8, text, expected_text)}); + + try expect(std.mem.eql(u8, text, expected_text)); + + std.testing.allocator.free(text); + piece_table.deinit(std.testing.allocator); +} + +test "piece table delete multiple whole pieces" { + const first_text: []const u8 = "damn these"; + const second_text: []const u8 = " are some"; + const third_text: []const u8 = " cool toads"; + + const expected_text: []const u8 = ""; + + var piece_table = PieceTable.init(); + + try piece_table.insert(std.testing.allocator, .{ + .start = 0, + .length = first_text.len, + .text = &first_text, + }, 0); + + try piece_table.insert(std.testing.allocator, .{ + .start = 0, + .length = second_text.len, + .text = &second_text, + }, first_text.len); + + try piece_table.insert(std.testing.allocator, .{ + .start = 0, + .length = third_text.len, + .text = &third_text, + }, first_text.len + second_text.len); + + const piece_together_text = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + + try piece_table.delete( + std.testing.allocator, + 0, + 30, + ); + + const text = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + + std.debug.print("org \"{s}\"\n", .{piece_together_text}); + std.debug.print("got \"{s}\"\n", .{text}); + std.debug.print("wnt \"{s}\"\n", .{expected_text}); + std.debug.print("eql {}\n", .{std.mem.eql(u8, text, expected_text)}); + + try expect(std.mem.eql(u8, text, expected_text)); + + std.testing.allocator.free(text); + std.testing.allocator.free(piece_together_text); + piece_table.deinit(std.testing.allocator); +} + +test "piece table delete part of two pieces" { + const first_text: []const u8 = "damn these"; + const second_text: []const u8 = " are some"; + const third_text: []const u8 = " cool toads"; + + const expected_text: []const u8 = "damn these are toads"; + + var piece_table = PieceTable.init(); + + try piece_table.insert(std.testing.allocator, .{ + .start = 0, + .length = first_text.len, + .text = &first_text, + }, 0); + + try piece_table.insert(std.testing.allocator, .{ + .start = 0, + .length = second_text.len, + .text = &second_text, + }, first_text.len); + + try piece_table.insert(std.testing.allocator, .{ + .start = 0, + .length = third_text.len, + .text = &third_text, + }, first_text.len + second_text.len); + + const piece_together_text = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + + try piece_table.delete( + std.testing.allocator, + 14, + 25, + ); + + piece_table.debug = true; + std.debug.print("table : {f}\n", .{piece_table}); + piece_table.debug = false; + + const text = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + + std.debug.print("org \"{s}\"\n", .{piece_together_text}); + std.debug.print("got \"{s}\"\n", .{text}); + std.debug.print("wnt \"{s}\"\n", .{expected_text}); + std.debug.print("eql {}\n", .{std.mem.eql(u8, text, expected_text)}); + + try expect(std.mem.eql(u8, text, expected_text)); + + std.testing.allocator.free(text); + std.testing.allocator.free(piece_together_text); + piece_table.deinit(std.testing.allocator); +} + +test "piece table delete part of two pieces with a whole piece" { + const first_text: []const u8 = "damn these"; + const second_text: []const u8 = " are some"; + const third_text: []const u8 = " cool toads"; + + const expected_text: []const u8 = "damn toads"; + + var piece_table = PieceTable.init(); + + try piece_table.insert(std.testing.allocator, .{ + .start = 0, + .length = first_text.len, + .text = &first_text, + }, 0); + + try piece_table.insert(std.testing.allocator, .{ + .start = 0, + .length = second_text.len, + .text = &second_text, + }, first_text.len); + + try piece_table.insert(std.testing.allocator, .{ + .start = 0, + .length = third_text.len, + .text = &third_text, + }, first_text.len + second_text.len); + + const piece_together_text = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + + try piece_table.delete( + std.testing.allocator, + 5, + 25, + ); + + piece_table.debug = true; + std.debug.print("table : {f}\n", .{piece_table}); + piece_table.debug = false; + + const text = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + + std.debug.print("org \"{s}\"\n", .{piece_together_text}); + std.debug.print("got \"{s}\"\n", .{text}); + std.debug.print("wnt \"{s}\"\n", .{expected_text}); + std.debug.print("eql {}\n", .{std.mem.eql(u8, text, expected_text)}); + + try expect(std.mem.eql(u8, text, expected_text)); + + std.testing.allocator.free(text); + std.testing.allocator.free(piece_together_text); + piece_table.deinit(std.testing.allocator); +} + +test "piece table delete one char" { + const orignal_text: []const u8 = "damn these are some cool toads"; + const expected_text: []const u8 = "damn these are some cool toad"; + + var piece_table = PieceTable.init(); + + try piece_table.insert(std.testing.allocator, .{ + .start = 0, + .length = orignal_text.len, + .text = &orignal_text, + }, 0); + + try piece_table.delete(std.testing.allocator, orignal_text.len - 1, orignal_text.len); + + const text = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + + std.debug.print("org \"{s}\"\n", .{orignal_text}); + std.debug.print("got \"{s}\"\n", .{text}); + std.debug.print("wnt \"{s}\"\n", .{expected_text}); + std.debug.print("eql {}\n", .{std.mem.eql(u8, text, expected_text)}); + + try expect(std.mem.eql(u8, text, expected_text)); + + std.testing.allocator.free(text); + piece_table.deinit(std.testing.allocator); +} + +test "piece table delete increasing indeces with same text does not add any addtional pieces" { + const orignal_text: []const u8 = "damn these are some cool toads"; + const keyboard: []const u8 = " not"; + const expected_text = "damn these are not some cool toads"; + + var piece_table = PieceTable.init(); + + try piece_table.insert(std.testing.allocator, .{ + .start = 0, + .length = orignal_text.len, + .text = &orignal_text, + }, 0); + + inline for (keyboard, 0..) |_, i| { + try piece_table.insert(std.testing.allocator, .{ + .start = 0, + .length = 1, + .text = &keyboard, + }, 14 + i); + } + + const text = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + try expect(std.mem.eql(u8, text, expected_text)); + try expect(piece_table.pieces.items.len == 3); + + inline for (keyboard, 0..) |_, i| { + try piece_table.delete(std.testing.allocator, 13 + keyboard.len - i, 13 + keyboard.len - i + 1); + } + + const text_deleted = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + + try expect(std.mem.eql(u8, text_deleted, orignal_text)); + try expect(piece_table.pieces.items.len == 3); + + std.testing.allocator.free(text); + std.testing.allocator.free(text_deleted); + piece_table.deinit(std.testing.allocator); +} + +// ========================================== \delete ========================================== + +// ========================================== insert undos ========================================== + +test "piece table undo insert in to empty table" { + const orignal_text: []const u8 = "damn these are some cool toads"; + + var piece_table = PieceTable.init(); + + try piece_table.insert(std.testing.allocator, .{ + .start = 0, + .length = orignal_text.len, + .text = &orignal_text, + }, 0); + + const text = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + + try expect(std.mem.eql(u8, text, orignal_text)); + + try piece_table.undo(std.testing.allocator); + const text_undid = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + + try expect(std.mem.eql(u8, text_undid, "")); + + try piece_table.redo(std.testing.allocator); + const text_redid = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + + try expect(std.mem.eql(u8, text_redid, orignal_text)); + + std.testing.allocator.free(text); + std.testing.allocator.free(text_undid); + std.testing.allocator.free(text_redid); + piece_table.deinit(std.testing.allocator); +} + +test "piece table undo insert another piece after first piece" { + const orignal_text: []const u8 = "damn these are some cool toads"; + const new_text: []const u8 = " and frogs"; + const expected_text: []const u8 = orignal_text ++ new_text; + + var piece_table = PieceTable.init(); + + try piece_table.insert(std.testing.allocator, .{ + .start = 0, + .length = orignal_text.len, + .text = &orignal_text, + }, 0); + + try piece_table.insert(std.testing.allocator, .{ + .start = 0, + .length = new_text.len, + .text = &new_text, + }, orignal_text.len); + + const text = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + + try expect(std.mem.eql(u8, text, expected_text)); + + try piece_table.undo(std.testing.allocator); + const text_undid = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + + try expect(std.mem.eql(u8, text_undid, orignal_text)); + + try piece_table.redo(std.testing.allocator); + const text_redid = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + + try expect(std.mem.eql(u8, text_redid, expected_text)); + + std.testing.allocator.free(text); + std.testing.allocator.free(text_undid); + std.testing.allocator.free(text_redid); + piece_table.deinit(std.testing.allocator); +} + +test "piece table undo insert between pieces" { + const first_text: []const u8 = "damn these are some cool toads"; + const second_text: []const u8 = " and frogs"; + const new_text: []const u8 = " hat"; + + const expected_text: []const u8 = first_text ++ new_text ++ second_text; + + var piece_table = PieceTable.init(); + + try piece_table.insert(std.testing.allocator, .{ + .start = 0, + .length = first_text.len, + .text = &first_text, + }, 0); + + try piece_table.insert(std.testing.allocator, .{ + .start = 0, + .length = second_text.len, + .text = &second_text, + }, first_text.len); + + try piece_table.insert(std.testing.allocator, .{ + .start = 0, + .length = new_text.len, + .text = &new_text, + }, first_text.len); + + // std.debug.print("got \"{s}\"\n", .{text}); + // std.debug.print("wnt \"{s}\"\n", .{expected_text}); + // std.debug.print("eql {}\n", .{std.mem.eql(u8, text, expected_text)}); + + const text = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + + try expect(std.mem.eql(u8, text, expected_text)); + + try piece_table.undo(std.testing.allocator); + const text_undid = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + + try expect(std.mem.eql(u8, text_undid, first_text ++ second_text)); + + try piece_table.redo(std.testing.allocator); + const text_redid = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + + try expect(std.mem.eql(u8, text_redid, expected_text)); + + std.testing.allocator.free(text); + std.testing.allocator.free(text_undid); + std.testing.allocator.free(text_redid); + defer piece_table.deinit(std.testing.allocator); +} + +test "piece table undo insert split pieces" { + const orignal_text: []const u8 = "damn these are some cool toads"; + const new_text: []const u8 = " not"; + const expected_text: []const u8 = "damn these are not some cool toads"; + + var piece_table = PieceTable.init(); + + try piece_table.insert(std.testing.allocator, .{ + .start = 0, + .length = orignal_text.len, + .text = &orignal_text, + }, 0); + + try piece_table.insert(std.testing.allocator, .{ + .start = 0, + .length = new_text.len, + .text = &new_text, + }, 14); + + const text = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + + try expect(std.mem.eql(u8, text, expected_text)); + + try piece_table.undo(std.testing.allocator); + const text_undid = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + + try expect(std.mem.eql(u8, text_undid, orignal_text)); + + try piece_table.redo(std.testing.allocator); + const text_redid = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + + try expect(std.mem.eql(u8, text_redid, expected_text)); + + std.testing.allocator.free(text); + std.testing.allocator.free(text_undid); + std.testing.allocator.free(text_redid); + piece_table.deinit(std.testing.allocator); +} + +test "piece table undo insert increasing indeces with same text does not add any addtioanl pieces" { + const orignal_text: []const u8 = "damn these are some cool toads"; + const keyboard: []const u8 = " not"; + const expected_text = "damn these are not some cool toads"; + + var piece_table = PieceTable.init(); + + try piece_table.insert(std.testing.allocator, .{ + .start = 0, + .length = orignal_text.len, + .text = &orignal_text, + }, 0); + + inline for (keyboard, 0..) |_, i| { + try piece_table.insert(std.testing.allocator, .{ + .start = 0, + .length = 1, + .text = &keyboard, + }, 14 + i); + // const text_pre_undo = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + + try piece_table.undo(std.testing.allocator); + try piece_table.redo(std.testing.allocator); + + // const text_redid = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + + // try expect(std.mem.eql(u8, text_pre_undo, text_redid)); + + // std.testing.allocator.free(text_pre_undo); + // std.testing.allocator.free(text_redid); + } + + const text = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + + std.debug.print("got \"{s}\"\n", .{text}); + std.debug.print("wnt \"{s}\"\n", .{expected_text}); + std.debug.print("eql {}\n", .{std.mem.eql(u8, text, expected_text)}); + + try expect(std.mem.eql(u8, text, expected_text)); + try expect(piece_table.pieces.items.len == 3); + + std.testing.allocator.free(text); + piece_table.deinit(std.testing.allocator); +} + +// ========================================== insert undos ========================================== + +// ========================================== delete undos ========================================== + +test "piece table undo delete must split piece" { + const orignal_text: []const u8 = "damn these are some cool toads"; + const expected_text: []const u8 = "damn these are some toads"; + + var piece_table = PieceTable.init(); + + try piece_table.insert(std.testing.allocator, .{ + .start = 0, + .length = orignal_text.len, + .text = &orignal_text, + }, 0); + + try piece_table.delete(std.testing.allocator, 20, 25); + + const text = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + + std.debug.print("org \"{s}\"\n", .{orignal_text}); + std.debug.print("got \"{s}\"\n", .{text}); + std.debug.print("wnt \"{s}\"\n", .{expected_text}); + std.debug.print("eql {}\n", .{std.mem.eql(u8, text, expected_text)}); + + try expect(std.mem.eql(u8, text, expected_text)); + + try piece_table.undo(std.testing.allocator); + + const text_undo = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + + // std.debug.print("undo got \"{s}\"\n", .{text_undo}); + // std.debug.print("undo wnt \"{s}\"\n", .{orignal_text}); + // std.debug.print("undo eql {}\n", .{std.mem.eql(u8, text, expected_text)}); + + try expect(std.mem.eql(u8, text_undo, orignal_text)); + + try piece_table.redo(std.testing.allocator); + + const text_redid = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + + // std.debug.print("redo got \"{s}\"\n", .{text_redid}); + // std.debug.print("redo wnt \"{s}\"\n", .{expected_text}); + + try expect(std.mem.eql(u8, text_redid, expected_text)); + + std.testing.allocator.free(text); + std.testing.allocator.free(text_undo); + std.testing.allocator.free(text_redid); + piece_table.deinit(std.testing.allocator); +} + +test "piece table undo delete end of a piece" { + const orignal_text: []const u8 = "damn these are some cool toads"; + const expected_text: []const u8 = "damn these are some"; + + var piece_table = PieceTable.init(); + + try piece_table.insert(std.testing.allocator, .{ + .start = 0, + .length = orignal_text.len, + .text = &orignal_text, + }, 0); + + try piece_table.delete( + std.testing.allocator, + orignal_text.len - 11, + orignal_text.len, + ); + + const text = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + + std.debug.print("org \"{s}\"\n", .{orignal_text}); + std.debug.print("got \"{s}\"\n", .{text}); + std.debug.print("wnt \"{s}\"\n", .{expected_text}); + std.debug.print("eql {}\n", .{std.mem.eql(u8, text, expected_text)}); + + try expect(std.mem.eql(u8, text, expected_text)); + + std.testing.allocator.free(text); + piece_table.deinit(std.testing.allocator); +} + +// test "piece table undo delete start of a piece" { +// const orignal_text: []const u8 = "damn these are some cool toads"; +// const expected_text: []const u8 = "cool toads"; + +// var piece_table = PieceTable.init(); + +// try piece_table.insert(std.testing.allocator, .{ +// .start = 0, +// .length = orignal_text.len, +// .text = &orignal_text, +// }, 0); + +// try piece_table.delete( +// std.testing.allocator, +// 0, +// 20, +// ); + +// const text = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + +// std.debug.print("org \"{s}\"\n", .{orignal_text}); +// std.debug.print("got \"{s}\"\n", .{text}); +// std.debug.print("wnt \"{s}\"\n", .{expected_text}); +// std.debug.print("eql {}\n", .{std.mem.eql(u8, text, expected_text)}); + +// try expect(std.mem.eql(u8, text, expected_text)); + +// std.testing.allocator.free(text); +// piece_table.deinit(std.testing.allocator); +// } + +// test "piece table undo delete whole piece" { +// const orignal_text: []const u8 = "damn these are some cool toads"; +// const expected_text: []const u8 = ""; + +// var piece_table = PieceTable.init(); + +// try piece_table.insert(std.testing.allocator, .{ +// .start = 0, +// .length = orignal_text.len, +// .text = &orignal_text, +// }, 0); + +// try piece_table.delete( +// std.testing.allocator, +// 0, +// orignal_text.len, +// ); + +// const text = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + +// std.debug.print("org \"{s}\"\n", .{orignal_text}); +// std.debug.print("got \"{s}\"\n", .{text}); +// std.debug.print("wnt \"{s}\"\n", .{expected_text}); +// std.debug.print("eql {}\n", .{std.mem.eql(u8, text, expected_text)}); + +// try expect(std.mem.eql(u8, text, expected_text)); + +// std.testing.allocator.free(text); +// piece_table.deinit(std.testing.allocator); +// } + +// test "piece table undo delete multiple whole pieces" { +// const first_text: []const u8 = "damn these"; +// const second_text: []const u8 = " are some"; +// const third_text: []const u8 = " cool toads"; + +// const expected_text: []const u8 = ""; + +// var piece_table = PieceTable.init(); + +// try piece_table.insert(std.testing.allocator, .{ +// .start = 0, +// .length = first_text.len, +// .text = &first_text, +// }, 0); + +// try piece_table.insert(std.testing.allocator, .{ +// .start = 0, +// .length = second_text.len, +// .text = &second_text, +// }, first_text.len); + +// try piece_table.insert(std.testing.allocator, .{ +// .start = 0, +// .length = third_text.len, +// .text = &third_text, +// }, first_text.len + second_text.len); + +// const piece_together_text = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + +// try piece_table.delete( +// std.testing.allocator, +// 0, +// 30, +// ); + +// const text = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + +// std.debug.print("org \"{s}\"\n", .{piece_together_text}); +// std.debug.print("got \"{s}\"\n", .{text}); +// std.debug.print("wnt \"{s}\"\n", .{expected_text}); +// std.debug.print("eql {}\n", .{std.mem.eql(u8, text, expected_text)}); + +// try expect(std.mem.eql(u8, text, expected_text)); + +// std.testing.allocator.free(text); +// std.testing.allocator.free(piece_together_text); +// piece_table.deinit(std.testing.allocator); +// } + +// test "piece table undo delete part of two pieces" { +// const first_text: []const u8 = "damn these"; +// const second_text: []const u8 = " are some"; +// const third_text: []const u8 = " cool toads"; + +// const expected_text: []const u8 = "damn these are toads"; + +// var piece_table = PieceTable.init(); + +// try piece_table.insert(std.testing.allocator, .{ +// .start = 0, +// .length = first_text.len, +// .text = &first_text, +// }, 0); + +// try piece_table.insert(std.testing.allocator, .{ +// .start = 0, +// .length = second_text.len, +// .text = &second_text, +// }, first_text.len); + +// try piece_table.insert(std.testing.allocator, .{ +// .start = 0, +// .length = third_text.len, +// .text = &third_text, +// }, first_text.len + second_text.len); + +// const piece_together_text = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + +// try piece_table.delete( +// std.testing.allocator, +// 14, +// 25, +// ); + +// piece_table.debug = true; +// std.debug.print("table : {f}\n", .{piece_table}); +// piece_table.debug = false; + +// const text = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + +// std.debug.print("org \"{s}\"\n", .{piece_together_text}); +// std.debug.print("got \"{s}\"\n", .{text}); +// std.debug.print("wnt \"{s}\"\n", .{expected_text}); +// std.debug.print("eql {}\n", .{std.mem.eql(u8, text, expected_text)}); + +// try expect(std.mem.eql(u8, text, expected_text)); + +// std.testing.allocator.free(text); +// std.testing.allocator.free(piece_together_text); +// piece_table.deinit(std.testing.allocator); +// } + +// test "piece table undo delete part of two pieces with a whole piece" { +// const first_text: []const u8 = "damn these"; +// const second_text: []const u8 = " are some"; +// const third_text: []const u8 = " cool toads"; + +// const expected_text: []const u8 = "damn toads"; + +// var piece_table = PieceTable.init(); + +// try piece_table.insert(std.testing.allocator, .{ +// .start = 0, +// .length = first_text.len, +// .text = &first_text, +// }, 0); + +// try piece_table.insert(std.testing.allocator, .{ +// .start = 0, +// .length = second_text.len, +// .text = &second_text, +// }, first_text.len); + +// try piece_table.insert(std.testing.allocator, .{ +// .start = 0, +// .length = third_text.len, +// .text = &third_text, +// }, first_text.len + second_text.len); + +// const piece_together_text = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + +// try piece_table.delete( +// std.testing.allocator, +// 5, +// 25, +// ); + +// piece_table.debug = true; +// std.debug.print("table : {f}\n", .{piece_table}); +// piece_table.debug = false; + +// const text = try std.fmt.allocPrint(std.testing.allocator, "{f}", .{piece_table}); + +// std.debug.print("org \"{s}\"\n", .{piece_together_text}); +// std.debug.print("got \"{s}\"\n", .{text}); +// std.debug.print("wnt \"{s}\"\n", .{expected_text}); +// std.debug.print("eql {}\n", .{std.mem.eql(u8, text, expected_text)}); + +// try expect(std.mem.eql(u8, text, expected_text)); + +// std.testing.allocator.free(text); +// std.testing.allocator.free(piece_together_text); +// piece_table.deinit(std.testing.allocator); +// } + +// test "PieceTable" { +// const orignal_text: []const u8 = "damn these are some cool toads"; +// const new_text: []const u8 = "frogs and "; +// const even_newer_text: []const u8 = "cats but not "; +// const keyboard_input: []const u8 = "hellful "; + +// var piece_table = PieceTable.init(); + +// try piece_table.insert(std.testing.allocator, .{ +// .start = 0, +// .length = orignal_text.len, +// .text = &orignal_text, +// }, 0); +// std.debug.print("{f}\n", .{piece_table}); + +// try piece_table.insert(std.testing.allocator, .{ +// .text = &new_text, +// .start = 0, +// .length = new_text.len, +// }, 20); +// std.debug.print("{f}\n", .{piece_table}); + +// try piece_table.delete(std.testing.allocator, 20, 20 + new_text.len); + +// std.debug.print("{f}\n", .{piece_table}); + +// try piece_table.insert(std.testing.allocator, .{ +// .text = &even_newer_text, +// .start = 0, +// .length = even_newer_text.len, +// }, 20); +// std.debug.print("{f}\n", .{piece_table}); + +// try piece_table.undo(std.testing.allocator); + +// std.debug.print("{f}\n", .{piece_table}); + +// try piece_table.redo(std.testing.allocator); + +// std.debug.print("{f}\n", .{piece_table}); + +// for (0..keyboard_input.len) |i| { +// try piece_table.insert(std.testing.allocator, .{ +// .text = &keyboard_input, +// .start = 0, +// .length = 1, +// }, 19 + i); +// std.debug.print("{} {f}\n", .{ i, piece_table }); +// } + +// std.debug.print("{f}\n", .{piece_table}); + +// // try piece_table.undo(std.testing.allocator); +// // std.debug.print("{f}\n", .{piece_table}); +// // try piece_table.undo(std.testing.allocator); +// // std.debug.print("{f}\n", .{piece_table}); +// // try piece_table.undo(std.testing.allocator); +// // std.debug.print("{f}\n", .{piece_table}); +// // try piece_table.undo(std.testing.allocator); +// // std.debug.print("{f}\n", .{piece_table}); +// // try piece_table.undo(std.testing.allocator); +// // std.debug.print("{f}\n", .{piece_table}); +// // try piece_table.undo(std.testing.allocator); +// // std.debug.print("{f}\n", .{piece_table}); +// // try piece_table.undo(std.testing.allocator); +// // std.debug.print("{f}\n", .{piece_table}); + +// piece_table.deinit(std.testing.allocator); +// } diff --git a/src/root.zig b/src/root.zig new file mode 100644 index 0000000..5a71250 --- /dev/null +++ b/src/root.zig @@ -0,0 +1,18 @@ +//! By convention, root.zig is the root source file when making a package. +const std = @import("std"); +const Io = std.Io; + +/// This is a documentation comment to explain the `printAnotherMessage` function below. +/// +/// Accepting an `Io.Writer` instance is a handy way to write reusable code. +pub fn printAnotherMessage(writer: *Io.Writer) Io.Writer.Error!void { + try writer.print("Run `zig build test` to run the tests.\n", .{}); +} + +pub fn add(a: i32, b: i32) i32 { + return a + b; +} + +test "basic add functionality" { + try std.testing.expect(add(3, 7) == 10); +}