void JumpGarbageBuffer(BSet *set, String buffer_name = "") {
    if (buffer_name.len == 0) {
        String current_dir = ChopLastSlash(set->buffer->name);
        buffer_name = GetUniqueBufferName(current_dir, "temp");
    }
    set->view = WindowOpenBufferView(set->window, buffer_name);
    set->buffer = GetBuffer(set->view->active_buffer);
    set->buffer->garbage = true;
}

void Command_BeginJump(BSet *set, BufferID buffer_id = NullBufferID) {
    set->buffer = GetBuffer(buffer_id);
    set->view = WindowOpenBufferView(set->window, set->buffer->name);
}

void Command_EndJump(BSet set) {
    Int pos = XYToPos(set.buffer, {0, set.buffer->line_starts.len - 1});
    set.view->carets[0] = MakeCaret(pos);
    UpdateScroll(set.window, true);
}

Int ScreenSpaceToBufferPos(Window *window, View *view, Buffer *buffer, Vec2I mouse) {
    Vec2I mworld = mouse - window->document_rect.min + view->scroll;
    double px = (double)mworld.x / (double)window->font->char_spacing;
    double py = (double)mworld.y / (double)window->font->line_spacing;
    XY    xy     = {(Int)round(px), (Int)floor(py)};
    Int   result = XYToPosWithoutNL(buffer, xy);
    return result;
}

Int ScreenSpaceToBufferPosErrorOutOfBounds(Window *window, View *view, Buffer *buffer, Vec2I mouse) {
    Vec2I mworld = mouse - window->document_rect.min + view->scroll;
    double px = (double)mworld.x / (double)window->font->char_spacing;
    double py = (double)mworld.y / (double)window->font->line_spacing;
    XY    xy     = {(Int)round(px), (Int)floor(py)};
    Int   result = XYToPosErrorOutOfBounds(buffer, xy);
    return result;
}

void MouseLoadWord(Event event, String meta = "") {
    Vec2I mouse  = MouseVec2I();
    BSet  active = GetActiveSet();

    bool mouse_in_document = AreOverlapping(mouse, active.window->document_rect);
    if (mouse_in_document) {
        Int p = ScreenSpaceToBufferPosErrorOutOfBounds(active.window, active.view, active.buffer, mouse);
        if (p != -1) {
            Range enclose = EncloseLoadWord(active.buffer, p);
            if (InBounds(active.view->carets[0].range, p)) enclose = active.view->carets[0].range;
            String16 string = GetString(active.buffer, enclose);

            active.view->carets.len = 1;
            active.view->carets[0]  = MakeCaret(p);
            Command_Open(string, meta);
        }
    }
}

View *GetViewForFixingWhenBufferCommand(Buffer *buffer, bool *is_active = NULL) {
    View *view = NULL;
    if (is_active) {
        *is_active = false;
    }

    Window *active_window = GetWindow(ActiveWindow);
    View *active_view = GetView(active_window->active_view);
    if (active_view->active_buffer == buffer->id) {
        if (is_active) {
            *is_active = true;
        }
        return active_view;
    }

    For(Views) {
        if (it->active_buffer != buffer->id) {
            continue;
        }
        view = it;
        break;
    }

    if (!view) {
        view = CreateView(buffer->id);
    }

    return view;
}

void ReplaceWithoutMovingCarets(Buffer *buffer, Range range, String16 string) {
    View *view = GetViewForFixingWhenBufferCommand(buffer);
    Array<Caret> carets = Copy(GetSystemAllocator(), view->carets);

    Scratch scratch;
    Command_SelectRangeOneCursor(view, range);
    Command_ReplaceEx(scratch, view, string);

    Dealloc(&view->carets);
    view->carets = carets;
}

// @todo: revamp interface since it scrolls ALL VIEWS??? or maybe not??
void Command_Append(View *view, String16 string, bool scroll_to_end_if_cursor_on_last_line) {
    Scratch scratch;
    Buffer *buffer = GetBuffer(view->active_buffer);

    struct ViewInfo {
        View *view;
        Array<Caret> carets;
        bool scroll_to_end;
    };

    Array<ViewInfo> view_info = {scratch};
    ForItem(it_view, Views) {
        if (it_view->active_buffer != buffer->id) {
            continue;
        }

        ViewInfo vi = {it_view};
        if (scroll_to_end_if_cursor_on_last_line) {
            Int line = PosToLine(buffer, GetFront(it_view->carets[0]));
            if (line == buffer->line_starts.len - 1) {
                vi.scroll_to_end = true;
            }
        }

        if (!vi.scroll_to_end) {
            vi.carets = Copy(GetSystemAllocator(), it_view->carets);
        }

        Add(&view_info, vi);
    }

    Command_SelectRangeOneCursor(view, GetBufferEndAsRange(buffer));
    Command_Replace(view, string);

    For (view_info) {
        if (it.scroll_to_end) {
            it.view->carets[0] = MakeCaret(GetBufferEndAsRange(buffer).min);
        } else {
            Dealloc(&it.view->carets);
            it.view->carets = it.carets;
        }
    }
}

void Command_Append(View *view, String string, bool scroll_to_end_if_cursor_on_last_line) {
    Scratch  scratch;
    String16 string16 = ToString16(scratch, string);
    Command_Append(view, string16, scroll_to_end_if_cursor_on_last_line);
}

void Command_Appendf(View *view, const char *fmt, ...) {
    Scratch scratch;
    STRING_FORMAT(scratch, fmt, string);
    Command_Append(view, string, true);
}

void ReportErrorf(const char *fmt, ...) {
    Scratch scratch;
    STRING_FORMAT(scratch, fmt, string);
    SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Error!", string.data, NULL);
    View *view = GetView(NullViewID);
    if (view) {
        Command_Appendf(view, "%S\n", string);
        ActiveWindow = NullWindowID;
    }
}

void ReportConsolef(const char *fmt, ...) {
    Scratch scratch;
    STRING_FORMAT(scratch, fmt, string);
    View *view = GetView(NullViewID);
    Command_Appendf(view, "%S\n", string);
}

void ReportWarningf(const char *fmt, ...) {
    Scratch scratch;
    STRING_FORMAT(scratch, fmt, string);
    View *null_view = GetView(NullViewID);
    Command_Appendf(null_view, "%S\n", string);
}

void ReportDebugf(const char *fmt, ...) {
    Scratch scratch;
    STRING_FORMAT(scratch, fmt, string);
    Command_Appendf(TraceView, "%S\n", string);
}

void Command_MoveCursorsByPageSize(Window *window, int direction, bool shift = false) {
    Assert(direction == DIR_UP || direction == DIR_DOWN);
    BSet set = GetBSet(window);

    Rect2I visible_cells_rect = GetVisibleCells(window);
    Int    y                  = GetSize(visible_cells_rect).y - 2;
    if (direction == DIR_UP) y = -y;

    For(set.view->carets) {
        XY xy = PosToXY(set.buffer, GetFront(it));
        if (direction == DIR_DOWN && xy.line == set.buffer->line_starts.len - 1) {
            Range line_range = GetLineRange(set.buffer, xy.line);
            xy.col           = line_range.max - line_range.min;
        } else if (direction == DIR_UP && xy.line == 0) {
            xy.col = 0;
        }
        xy.line += y;

        Int pos = XYToPos(set.buffer, xy);
        if (shift) {
            it = SetFront(it, pos);
        } else {
            it = MakeCaret(pos);
        }
    }
}

void Command_MoveCursorsToSide(View *view, int direction, bool shift = false) {
    Assert(direction == DIR_LEFT || direction == DIR_RIGHT);
    Buffer *buffer = GetBuffer(view->active_buffer);

    For(view->carets) {
        Int pos = GetFront(it);
        if (direction == DIR_RIGHT) {
            pos = GetLineEnd(buffer, pos);
        } else {
            Int indent  = GetIndentAtPos(buffer, pos);
            Int new_pos = GetLineStart(buffer, pos);
            if (new_pos + indent != pos) {
                pos = new_pos + indent;
            } else {
                pos = new_pos;
            }
        }

        if (shift) {
            it = SetFront(it, pos);
        } else {
            it.range.max = it.range.min = pos;
        }
    }
}

Caret MoveCaret(Buffer *buffer, Caret it, int direction, bool ctrl = false, bool shift = false) {
    Int front      = GetFront(it);
    Int range_size = GetSize(it.range);
    switch (direction) {
    case DIR_UP: {
        if (ctrl && shift) {
            Int pos = GetPrevEmptyLineStart(buffer, front);
            it      = SetFront(it, pos);
        } else if (ctrl) {
            Int pos = GetPrevEmptyLineStart(buffer, it.range.min);
            it      = MakeCaret(pos);
        } else if (shift) {
            if (PosToLine(buffer, front) == 0) {
                it = SetFront(it, 0);
            } else {
                Int pos = OffsetByLine(buffer, front, -1);
                it      = SetFront(it, pos);
            }
        } else {
            if (range_size == 0) {
                Int pos = OffsetByLine(buffer, it.range.min, -1);
                it      = MakeCaret(pos);
            } else {
                it = MakeCaret(it.range.min);
            }
        }
    } break;
    case DIR_DOWN: {
        if (ctrl && shift) {
            Int pos = GetNextEmptyLineStart(buffer, front);
            it      = SetFront(it, pos);
        } else if (ctrl) {
            Int pos = GetNextEmptyLineStart(buffer, it.range.max);
            it      = MakeCaret(pos);
        } else if (shift) {
            if (LastLine(buffer) == PosToLine(buffer, front)) {
                it = SetFront(it, buffer->len);
            } else {
                Int pos = OffsetByLine(buffer, front, 1);
                it      = SetFront(it, pos);
            }
        } else {
            if (range_size == 0) {
                Int pos = OffsetByLine(buffer, it.range.max, 1);
                it      = MakeCaret(pos);
            } else {
                it = MakeCaret(it.range.max);
            }
        }
    } break;
    case DIR_LEFT: {
        if (ctrl && shift) {
            Int pos = GetPrevWordStart(buffer, front);
            it      = SetFront(it, pos);
        } else if (ctrl) {
            if (range_size != 0 && front != it.range.min) {
                it = MakeCaret(it.range.min);
            } else {
                Int pos = GetPrevWordStart(buffer, it.range.min);
                it      = MakeCaret(pos);
            }
        } else if (shift) {
            Int pos = GetPrevChar(buffer, front);
            it      = SetFront(it, pos);
        } else {
            if (range_size == 0) {
                Int pos = GetPrevChar(buffer, it.range.min);
                it      = MakeCaret(pos);
            } else {
                it = MakeCaret(it.range.min);
            }
        }
    } break;
    case DIR_RIGHT: {
        if (ctrl && shift) {
            Int pos = GetNextWordEnd(buffer, front);
            it      = SetFront(it, pos);
        } else if (ctrl) {
            if (range_size != 0 && front != it.range.max) {
                it = MakeCaret(it.range.max);
            } else {
                Int pos = GetNextWordEnd(buffer, it.range.max);
                it      = MakeCaret(pos);
            }
        } else if (shift) {
            Int pos = GetNextChar(buffer, front);
            it      = SetFront(it, pos);
        } else {
            if (range_size == 0) {
                Int pos = GetNextChar(buffer, it.range.max);
                it      = MakeCaret(pos);
            } else {
                it = MakeCaret(it.range.max);
            }
        }
    } break;
    }
    return it;
}

void Command_Move(View *view, int direction, bool ctrl = false, bool shift = false) {
    Assert(direction < DIR_COUNT);
    Buffer *buffer = GetBuffer(view->active_buffer);
    For(view->carets) {
        it = MoveCaret(buffer, it, direction, ctrl, shift);
    }
}

void Command_MoveLine(View *view, int direction) {
    Assert(direction == DIR_DOWN || direction == DIR_UP);
    Scratch scratch;

    // @todo: this doesn't work well at the end of buffer
    struct XYPair {
        XY front;
        XY back;
    };

    Buffer     *buffer = GetBuffer(view->active_buffer);
    Array<Edit> edits  = BeginEdit(scratch, buffer, view->carets);
    MergeCarets(buffer, &view->carets);
    Array<XYPair> saved_xy = {scratch};
    For(view->carets) {
        Int eof_current = 0;
        Range lines_to_move_range = {GetFullLineStart(buffer, it.range.min), GetFullLineEnd(buffer, it.range.max, &eof_current)};
        if (lines_to_move_range.min == 0 && direction == DIR_UP) {
            continue;
        }

        Int eof = 0;
        Int next_line_start = lines_to_move_range.max;
        Int next_line_end   = GetFullLineEnd(buffer, next_line_start, &eof);
        Int prev_line_end   = lines_to_move_range.min - 1;
        Int prev_line_start = GetFullLineStart(buffer, prev_line_end);

        if (direction == DIR_DOWN && eof) {
            continue;
        } else if (direction == DIR_UP && eof_current) {
            continue;
        }

        String16 string = Copy16(scratch, GetString(buffer, lines_to_move_range));

        AddEdit(&edits, lines_to_move_range, {});
        if (direction == DIR_DOWN) {
            AddEdit(&edits, MakeRange(next_line_end), string);
        } else {
            AddEdit(&edits, MakeRange(prev_line_start), string);
        }

        Add(&saved_xy, {PosToXY(buffer, GetFront(it)), PosToXY(buffer, GetBack(it))});
    }
    EndEdit(buffer, &edits, &view->carets, !KILL_SELECTION);

    Int line_offset = direction == DIR_UP ? -1 : +1;
    for (Int i = 0; i < saved_xy.len; i += 1) {
        Caret  &caret  = view->carets[i];
        XYPair &xypair = saved_xy[i];
        xypair.front.line += line_offset;
        xypair.back.line += line_offset;
        Int front = XYToPos(buffer, xypair.front);
        Int back  = XYToPos(buffer, xypair.back);

        caret = MakeCaret(front, back);
    }
}

Array<Edit> Command_ReplaceEx(Allocator scratch, View *view, String16 string) {
    Buffer     *buffer = GetBuffer(view->active_buffer);
    Array<Edit> edits  = BeginEdit(scratch, buffer, view->carets);
    MergeCarets(buffer, &view->carets);
    For(view->carets) AddEdit(&edits, it.range, string);
    EndEdit(buffer, &edits, &view->carets, KILL_SELECTION);
    return edits;
}

void Command_Replace(View *view, String16 string) {
    Scratch scratch;
    Command_ReplaceEx(scratch, view, string);
}

void Command_DuplicateLine(View *view, int direction) {
    Assert(direction == DIR_UP || direction == DIR_DOWN);
    Scratch scratch;

    Buffer *buffer = GetBuffer(view->active_buffer);
    BeginEdit(scratch, buffer, view->carets);
    MergeCarets(buffer, &view->carets);

    Array<Edit> edits = {scratch};
    For(view->carets) {
        Int eof = 0;
        Range range = {};
        range.max = GetFullLineEnd(buffer, it.range.max, &eof);
        range.min = GetFullLineStart(buffer, it.range.min);
        range.min -= Clamp(eof, (Int)0, buffer->len);
        String16 string = Copy16(scratch, GetString(buffer, range));

        Int pos = direction == DIR_UP ? range.min : range.max;
        AddEdit(&edits, MakeRange(pos), string);
    }
    EndEdit(buffer, &edits, &view->carets, !KILL_SELECTION);

    Int coef = direction == DIR_UP ? -1 : 1;
    for (Int i = 0; i < edits.len; i += 1) {
        Caret *caret = view->carets.data + i;

        XY xymin = PosToXY(buffer, caret->range.min);
        XY xymax = PosToXY(buffer, caret->range.max);
        Int line_count = xymax.line - xymin.line + 1;

        xymin.line += coef * line_count;
        xymax.line += coef * line_count;

        caret->range.min = XYToPos(buffer, xymin);
        caret->range.max = XYToPos(buffer, xymax);
    }
}

Array<Range> GetSelectedLinesSorted(Allocator allocator, View *view) {
    Scratch      scratch(allocator);
    Buffer      *buffer     = GetBuffer(view->active_buffer);
    Array<Caret> caret_copy = TightCopy(scratch, view->carets);
    Array<Caret> temp       = TightCopy(scratch, view->carets);
    if (view->carets.len > 1) MergeSort(view->carets.len, caret_copy.data, temp.data);

    Array<Range> result = {allocator};
    For(caret_copy) {
        Int   min_line   = PosToLine(buffer, it.range.min);
        Int   max_line   = PosToLine(buffer, it.range.max);
        Range line_range = {min_line, max_line + 1};

        if (result.len == 0) {
            Add(&result, line_range);
            continue;
        }

        Range *last = GetLast(result);
        if (AreOverlapping(*last, line_range)) {
            last->max = Max(last->max, line_range.max);
        } else {
            Add(&result, line_range);
        }
    }
    return result;
}

void Command_IndentSelectedLines(View *view, bool shift = false) {
    Scratch scratch;
    Buffer *buffer = GetBuffer(view->active_buffer);

    Array<Edit> edits = BeginEdit(scratch, buffer, view->carets);
    MergeCarets(buffer, &view->carets);

    Array<Range> line_ranges_to_indent = GetSelectedLinesSorted(scratch, view);
    For(line_ranges_to_indent) {
        for (Int i = it.min; i < it.max; i += 1) {
            Range pos_range_of_line = GetLineRange(buffer, i);

            if (!shift) {
                String16 whitespace_string = {u"                                      ", StyleIndentSize};
                AddEdit(&edits, {pos_range_of_line.min, pos_range_of_line.min}, whitespace_string);
            } else {
                String16 string         = GetString(buffer, pos_range_of_line);
                Int      whitespace_len = 0;
                for (Int i = 0; i < StyleIndentSize && i < string.len && string.data[i] == ' '; i += 1) {
                    whitespace_len += 1;
                }

                AddEdit(&edits, {pos_range_of_line.min, pos_range_of_line.min + whitespace_len}, u"");
            }
        }
    }
    EndEdit(buffer, &edits, &view->carets, !KILL_SELECTION);
    view->update_scroll = false;
}

void TrimTrailingWhitespace(Buffer *buffer, bool trim_lines_with_caret = false) {
    Scratch scratch;

    bool is_active_view = false;
    View *view = GetViewForFixingWhenBufferCommand(buffer, &is_active_view);
    if (!is_active_view && !trim_lines_with_caret) {
        trim_lines_with_caret = true;
    }

    Array<Edit> edits = BeginEdit(scratch, buffer, view->carets);
    MergeCarets(buffer, &view->carets);

    Array<Range> lines_to_skip_triming = {};
    if (!trim_lines_with_caret) {
        lines_to_skip_triming = GetSelectedLinesSorted(scratch, view);
    }

    for (Int i = 0; i < buffer->line_starts.len; i += 1) {
        Int range_index = FindRangeByPos(&lines_to_skip_triming, i);
        if (range_index != -1) continue;

        Range range          = GetLineRangeWithoutNL(buffer, i);
        Int   whitespace_end = range.max;
        for (; whitespace_end > range.min; whitespace_end -= 1) {
            U16  w             = buffer->data[whitespace_end - 1];
            bool is_whitespace = w == ' ' || w == '\t' || w == '\v' || w == '\r';
            if (!is_whitespace) break;
        }

        Range whitespace_range = {whitespace_end, range.max};
        AddEdit(&edits, whitespace_range, u"");
    }

    EndEdit(buffer, &edits, &view->carets, !KILL_SELECTION);
    view->update_scroll = false;
}

int Lua_TrimTrailingWhitespace(lua_State *L) {
    lua_Integer buffer_id = luaL_checkinteger(L, 1);
    int trim_lines_with_caret = lua_toboolean(L, 2);
    lua_pop(L, 2);
    Buffer *buffer = GetBuffer({buffer_id});
    TrimTrailingWhitespace(buffer, trim_lines_with_caret);
    return 0;
}

void ConvertLineEndingsToLF(Buffer *buffer, bool trim_lines_with_caret = false) {
    Scratch scratch;

    bool is_active_view = false;
    View *view = GetViewForFixingWhenBufferCommand(buffer, &is_active_view);
    if (!is_active_view && !trim_lines_with_caret) {
        trim_lines_with_caret = true;
    }

    Array<Edit> edits = BeginEdit(scratch, buffer, view->carets);
    MergeCarets(buffer, &view->carets);

    Array<Range> lines_to_skip_triming = {};
    if (!trim_lines_with_caret) {
        lines_to_skip_triming = GetSelectedLinesSorted(scratch, view);
    }

    for (Int i = 0; i < buffer->line_starts.len; i += 1) {
        Int range_index = FindRangeByPos(&lines_to_skip_triming, i);
        if (range_index != -1) continue;

        Range   range = GetLineRangeWithoutNL(buffer, i);
        char16_t cr   = GetChar(buffer, range.max - 1);
        char16_t lf   = GetChar(buffer, range.max);
        if (cr == u'\r' && lf == u'\n') {
            AddEdit(&edits, {range.max - 1, range.max}, u"");
        }
    }
    EndEdit(buffer, &edits, &view->carets, !KILL_SELECTION);
    view->update_scroll = false;
}

int Lua_ConvertLineEndingsToLF(lua_State *L) {
    lua_Integer buffer_id = luaL_checkinteger(L, 1);
    int trim_lines_with_caret = lua_toboolean(L, 2);
    lua_pop(L, 2);
    Buffer *buffer = GetBuffer({buffer_id});
    ConvertLineEndingsToLF(buffer, trim_lines_with_caret);
    return 0;
}

void ApplyClangFormat(Buffer *buffer) {
    Scratch scratch;
    String  string      = AllocCharString(scratch, buffer);
    Buffer *temp_buffer = ExecAndWait(scratch, "clang-format", GetDir(buffer), string);
    ReplaceWithoutMovingCarets(buffer, GetRange(buffer), {temp_buffer->str, temp_buffer->len});
}

int Lua_ApplyClangFormat(lua_State *L) {
    lua_Integer buffer_id = luaL_checkinteger(L, 1);
    lua_pop(L, 1);
    Buffer *buffer = GetBuffer({buffer_id});
    ApplyClangFormat(buffer);
    return 0;
}

int Lua_GetBufferNameByID(lua_State *L) {
    lua_Integer buffer_id = luaL_checkinteger(L, 1);
    lua_pop(L, 1);
    Buffer *buffer = GetBuffer({buffer_id});
    lua_pushlstring(L, buffer->name.data, buffer->name.len);
    return 1;
}

void SaveBuffer(Buffer *buffer) {
    CallOnSave(buffer->id);

    Scratch scratch;
    String  string  = AllocCharString(scratch, buffer);
    bool    success = WriteFile(buffer->name, string);

    if (success) {
        buffer->file_mod_time = GetFileModTime(buffer->name);
        buffer->dirty         = false;
        buffer->garbage       = false;
    } else {
        ReportWarningf("Failed to save file with name: %S", buffer->name);
    }
}
void Command_Save() {
    BSet set = GetLastActiveLayoutSet();
    SaveBuffer(set.buffer);
}
int Lua_Save(lua_State *L) {
    Command_Save();
    return 0;
}

void Command_SaveAll() {
    For(Buffers) {
        if (it->file_mod_time) {
            SaveBuffer(it);
        }
    }
}
int Lua_SaveAll(lua_State *L) {
    Command_SaveAll();
    return 0;
}

void Command_KillSelectedLines(View *view) {
    Scratch scratch;
    Buffer *buffer = GetBuffer(view->active_buffer);
    SaveCaretHistoryBeforeBeginEdit(buffer, view->carets);

    For (view->carets) {
        Int eof = 0;
        it.range.max = GetFullLineEnd(buffer, it.range.max, &eof);
        it.range.min = GetFullLineStart(buffer, it.range.min);
        it.range.min -= Clamp(eof, (Int)0, buffer->len);
    }
    Command_Replace(view, u"");
}

void EncloseLine(View *view) {
    Buffer *buffer = GetBuffer(view->active_buffer);
    For (view->carets) {
        Int eof = 0;
        it.range.max = GetFullLineEnd(buffer, it.range.max, &eof);
        it.range.min = GetFullLineStart(buffer, it.range.min);
    }
}

void EncloseScope(View *view) {
    Buffer *buffer = GetBuffer(view->active_buffer);
    For (view->carets) {
        it.range = EncloseScope(buffer, it.range.min - 1, it.range.max + 1, u'(', u')');
        it.range.min = Clamp(buffer, it.range.min + 1);
        it.range.max = Clamp(buffer, it.range.max - 1);
    }
}

void EncloseSpace(View *view) {
    Buffer *buffer = GetBuffer(view->active_buffer);
    For (view->carets) {
        it.range.min = GetPrevEmptyLineStart(buffer, it.range.min);
        it.range.max = GetNextEmptyLineStart(buffer, it.range.max);
    }
}

void Command_Delete(View *view, int direction, bool ctrl = false) {
    Assert(direction == DIR_LEFT || direction == DIR_RIGHT);
    Scratch scratch;

    Buffer     *buffer = GetBuffer(view->active_buffer);
    Array<Edit> edits  = BeginEdit(scratch, buffer, view->carets);

    // Select things to delete
    For(view->carets) {
        if (GetSize(it.range)) continue;
        if (direction == DIR_LEFT) {

            // Delete indent in multiple of IndentSize
            Range indent_range = GetIndentRangeAtPos(buffer, it.range.min);
            if (ctrl == false && it.range.min > indent_range.min && it.range.max <= indent_range.max) {
                Int offset    = it.range.min - indent_range.min;
                Int to_delete = (offset % (StyleIndentSize));
                if (to_delete == 0) to_delete = StyleIndentSize;
                to_delete = Clamp(to_delete, (Int)1, StyleIndentSize);
                for (Int i = 0; i < to_delete; i += 1) {
                    it = MoveCaret(buffer, it, direction, false, SHIFT_PRESS);
                }

            } else {
                it = MoveCaret(buffer, it, direction, ctrl, SHIFT_PRESS);
            }
        } else {
            it = MoveCaret(buffer, it, direction, ctrl, SHIFT_PRESS);
        }
    }

    MergeCarets(buffer, &view->carets);
    For(view->carets) AddEdit(&edits, it.range, {});
    EndEdit(buffer, &edits, &view->carets, true);
}

void Command_SelectAll(View *view, String16 needle) {
    Buffer  *buffer        = GetBuffer(view->active_buffer);
    String16 string_buffer = GetString(buffer);

    for (Int pos = 0;;) {
        Int      index  = 0;
        String16 medium = Skip(string_buffer, pos);
        if (!Seek(medium, needle, &index)) {
            break;
        }

        Add(&view->carets, MakeCaret(pos + index + needle.len, pos + index));
        pos += needle.len;
    }
    MergeCarets(buffer, &view->carets);
}

void Command_CreateCursorVertical(View *view, int direction) {
    Assert(direction == DIR_UP || direction == DIR_DOWN);
    Buffer *buffer = GetBuffer(view->active_buffer);

    Int line_offset = direction == DIR_UP ? -1 : 1;

    Scratch      scratch;
    Array<Caret> arr = {scratch};
    For(view->carets) {
        if (PosToLine(buffer, it.range.min) == PosToLine(buffer, it.range.max)) {
            Int f = OffsetByLine(buffer, GetFront(it), line_offset);
            Int b = OffsetByLine(buffer, GetBack(it), line_offset);
            Add(&arr, MakeCaret(f, b));
        } else {
            Int   pos   = direction == DIR_UP ? it.range.min : it.range.max;
            Caret caret = MakeCaret(pos);
            caret       = MoveCaret(buffer, caret, direction);
            Add(&arr, caret);
        }
    }
    For(arr) Add(&view->carets, it);
    MergeCarets(buffer, &view->carets);
}

void Command_SelectRangeOneCursor(View *view, Caret caret) {
    view->carets.len = 1;
    view->carets[0]  = caret;
}

void Command_SelectRangeOneCursor(View *view, Range range) {
    Command_SelectRangeOneCursor(view, MakeCaret(range.min, range.max));
}

void Command_SelectEntireBuffer(View *view) {
    Buffer *buffer = GetBuffer(view->active_buffer);
    Command_SelectRangeOneCursor(view, GetRange(buffer));
}

Caret FindPrev(Buffer *buffer, String16 needle, Caret caret) {
    Int      pos    = GetFront(caret);
    String16 medium = GetString(buffer, {0, pos});

    Caret result = caret;
    Int   index  = 0;
    if (Seek(medium, needle, &index, SeekFlag_MatchFindLast)) {
        result = MakeCaret(index, index + needle.len);
    } else {
        medium = GetString(buffer);
        if (Seek(medium, needle, &index, SeekFlag_MatchFindLast)) {
            result = MakeCaret(index, index + needle.len);
        }
    }

    return result;
}

Caret FindNext(Buffer *buffer, String16 needle, Caret caret) {
    Int      pos    = GetFront(caret);
    String16 medium = GetString(buffer, {pos, INT64_MAX});

    Caret result = caret;
    Int   index  = 0;
    if (Seek(medium, needle, &index)) {
        result = MakeCaret(pos + index + needle.len, pos + index);
    } else {
        medium = GetString(buffer);
        if (Seek(medium, needle, &index)) {
            result = MakeCaret(index + needle.len, index);
        }
    }

    return result;
}

void Command_IdentedNewLine(View *view) {
    Buffer     *buffer = GetBuffer(view->active_buffer);
    Scratch     scratch;
    Array<Edit> edits = BeginEdit(scratch, buffer, view->carets);
    MergeCarets(buffer, &view->carets);
    For(view->carets) {
        Int      front    = GetFront(it);
        Int      line     = PosToLine(buffer, front);
        Int      indent   = GetLineIndent(buffer, line);
        String   string   = Format(scratch, "\n%.*s", (int)indent, "                                                       ");
        String16 string16 = ToString16(scratch, string);
        AddEdit(&edits, it.range, string16);
    }
    EndEdit(buffer, &edits, &view->carets, KILL_SELECTION);
}

void Command_Find(View *seek_view, String16 needle, bool forward = true) {
    Buffer *seek_buffer = GetBuffer(seek_view->active_buffer);
    Caret   caret       = seek_view->carets[0];
    if (forward) caret = FindNext(seek_buffer, needle, caret);
    if (!forward) caret = FindPrev(seek_buffer, needle, caret);
    Command_SelectRangeOneCursor(seek_view, caret);

    IF_DEBUG(AssertRanges(seek_view->carets));
}

void Command_FuzzySort(View *view, String16 needle) {
    Buffer *buffer = GetBuffer(view->active_buffer);

    Scratch          scratch;
    Array<FuzzyPair> ratings = FuzzySearchLines(scratch, buffer, 0, buffer->line_starts.len, needle);

    Buffer *temp_buffer = CreateTempBuffer(scratch, buffer->cap);
    For(ratings) {
        String16 s = GetLineStringWithoutNL(buffer, it.index);
        if (s.len == 0) continue;
        RawReplaceText(temp_buffer, GetBufferEndAsRange(temp_buffer), s);
        RawReplaceText(temp_buffer, GetBufferEndAsRange(temp_buffer), u"\n");
    }

    Command_SelectEntireBuffer(view);
    Command_Replace(view, GetString(temp_buffer));
    Command_SelectRangeOneCursor(view, MakeRange(0));
}

void ReopenBuffer(Buffer *buffer) {
    Scratch scratch;
    String string = ReadFile(scratch, buffer->name);
    if (string.len == 0) {
        return;
    }

    String16 string16 = ToUnixString16(scratch, string);
    ReplaceWithoutMovingCarets(buffer, GetRange(buffer), string16);
    buffer->file_mod_time = GetFileModTime(buffer->name);
    buffer->changed_on_disk = false;
    buffer->dirty = false;
}

void Command_Reopen() {
    BSet set = GetLastActiveLayoutSet();
    ReopenBuffer(set.buffer);
    ActiveWindow = set.window->id;
}

int Lua_Reopen(lua_State *L) {
    Command_Reopen();
    return 0;
}

void New(Window *window, String name = "") {
    View *view = GetView(window->active_view);
    Buffer *buffer = GetBuffer(view->active_buffer);

    Scratch scratch;
    String dir  = GetDir(buffer);
    if (name != "") {
        if (!IsAbsolute(name)) {
            name = Format(scratch, "%S/%S", dir, name);
        }
        name = GetAbsolutePath(scratch, name);
    } else {
        name = GetUniqueBufferName(dir, "new");
    }
    WindowOpenBufferView(window, name);
}

void Command_New(String name = "") {
    BSet main = GetLastActiveLayoutSet();
    New(main.window, name);
}

int Lua_New(lua_State *L) {
    String name = lua_tostring(L, 1);
    lua_pop(L, 1);
    Command_New(name);
    return 0;
}

void NewDir(Window *window, String name = "") {
    View *view = GetView(window->active_view);
    Buffer *buffer = GetBuffer(view->active_buffer);

    Scratch scratch;
    String dir  = GetDir(buffer);
    if (name != "") {
        if (!IsAbsolute(name)) {
            name = Format(scratch, "%S/%S", dir, name);
        }
        name = GetAbsolutePath(scratch, name);
    } else {
        name = GetUniqueBufferName(dir, "new");
    }

    MakeDir(name);
    Command_Open(name);
}

int Lua_NewDir(lua_State *L) {
    String name = lua_tostring(L, 1);
    lua_pop(L, 1);
    BSet main = GetLastActiveLayoutSet();
    NewDir(main.window, name);
    return 0;
}

void Command_ToggleFullscreen() {
    if (IsInFullscreen) {
        SDL_SetWindowSize(SDLWindow, FullScreenSizeX, FullScreenSizeY);
        SDL_SetWindowPosition(SDLWindow, FullScreenPositionX, FullScreenPositionY);
    } else {
        SDL_GetWindowSize(SDLWindow, &FullScreenSizeX, &FullScreenSizeY);
        SDL_GetWindowPosition(SDLWindow, &FullScreenPositionX, &FullScreenPositionY);

        SDL_DisplayID          display = SDL_GetDisplayForWindow(SDLWindow);
        const SDL_DisplayMode *dm      = SDL_GetCurrentDisplayMode(display);
        SDL_SetWindowSize(SDLWindow, dm->w, dm->h);
        SDL_SetWindowPosition(SDLWindow, 0, 0);
    }

    IsInFullscreen = !IsInFullscreen;
}

int Lua_ToggleFullscreen(lua_State *L) {
    Command_ToggleFullscreen();
    return 0;
}

void ListFilesRecursive(Buffer *buffer, String dir) {
    Scratch scratch(buffer->line_starts.allocator);
    for (FileIter it = IterateFiles(scratch, dir); IsValid(it); Advance(&it)) {
        if (it.filename == ".git") {
            continue;
        }
        if (it.is_directory) {
            ListFilesRecursive(buffer, it.absolute_path);
        } else {
            bool good = CallIsCode(it.absolute_path);
            if (!good) {
                continue;
            }
            RawAppendf(buffer, "%-80S || %S\n", it.filename, it.absolute_path);
        }
    }
}

void Command_ListCode(String dir = WorkDir) {
    BSet main = GetLastActiveLayoutSet();
    JumpGarbageBuffer(&main);
    ListFilesRecursive(main.buffer, dir);
    main.view->fuzzy_search = true;
    main.view->update_scroll = true;
    Command_SelectRangeOneCursor(main.view, GetBufferEndAsRange(main.buffer));
}

int Lua_ListCode(lua_State *L) {
    String string = lua_tostring(L, 1);
    lua_pop(L, 1);
    if (string.len == 0) {
        string = WorkDir;
    }
    Command_ListCode(string);
    return 0;
}

View *Command_ExecHidden(String buffer_name, String cmd, String working_dir) {
    View *view = OpenBufferView(buffer_name);
    Exec(view->id, true, cmd, working_dir);
    return view;
}

BSet Command_Exec(String cmd, String working_dir, bool set_active = true) {
    BSet set = GetLastActiveLayoutSet();
    if (set_active) ActiveWindow = set.window->id;
    JumpGarbageBuffer(&set);
    Exec(set.view->id, true, cmd, working_dir);
    return set;
}

int Lua_C(lua_State *L) {
    String string = lua_tostring(L, 1);
    lua_pop(L, 1);
    Command_Exec(string, Command_GetMainDir());
    return 0;
}

BSet Command_Open(Window *window, String path, String meta, bool set_active = true) {
    Scratch scratch;
    BSet set = GetBSet(window);
    path = Trim(path);
    OnOpenResult ores = CallOnOpen(scratch, path, meta);
    if (ores.kind == "text") {
        if (set_active) {
            ActiveWindow = set.window->id;
        }
        if (IsDir(ores.file_path)) {
            JumpGarbageBuffer(&set, GetUniqueBufferName(ores.file_path, "temp", ".dirlisting"));
            Command_Appendf(set.view, "..\n");
            for (FileIter it = IterateFiles(scratch, ores.file_path); IsValid(it); Advance(&it)) {
                Command_Appendf(set.view, "%S\n", it.filename);
            }
        } else {
            View   *view   = WindowOpenBufferView(set.window, ores.file_path);
            Buffer *buffer = GetBuffer(view->active_buffer);
            if (ores.line != -1) {
                if (ores.col == -1) ores.col = 1;
                Int pos         = XYToPos(buffer, {ores.col - 1, ores.line - 1});
                view->carets[0] = MakeCaret(pos);
            }
        }
        UpdateScroll(set.window, true);
    } else if (ores.kind == "exec") {
        if (set_active) {
            ActiveWindow = set.window->id;
        }
        JumpGarbageBuffer(&set);
        Exec(set.view->id, true, ores.cmd, ores.working_dir);
    } else if (ores.kind == "exec_console") {
        // this shouldn't change the focus/window/view
        Exec(NullViewID, true, ores.cmd, ores.working_dir);
    } else if (ores.kind == "skip") {
        return {};
    } else {
        ReportWarningf("Failed to match any of OnOpen results!");
    }

    set = GetBSet(window);
    return set;
}

BSet Command_Open(String path, String meta) {
    BSet main = GetLastActiveLayoutSet();
    main = Command_Open(main.window, path, meta);
    return main;
}

BSet Command_Open(String16 path, String meta) {
    Scratch scratch;
    String  string = ToString(scratch, path);
    return Command_Open(string, meta);
}

int Lua_Open(lua_State *L) {
    Scratch scratch;
    String  path = luaL_checkstring(L, 1);
    lua_pop(L, 1);
    Command_Open(path);
    return 0;
}

int Lua_Cmd(lua_State *L) {
    if (!lua_istable(L, -1)) luaL_error(L, "expected a table as argument");
    defer { lua_pop(L, 1); };

    lua_getfield(L, -1, "working_dir");
    String working_dir = lua_tostring(L, -1);
    lua_pop(L, 1);
    if (working_dir == "") {
        working_dir = Command_GetMainDir();
    }

    lua_getfield(L, -1, "cmd");
    if (!lua_isstring(L, -1)) luaL_error(L, "expected a string for cmd param");
    String cmd = lua_tostring(L, -1);
    lua_pop(L, 1);

    lua_getfield(L, -1, "kind");
    String kind = lua_tostring(L, -1);
    lua_pop(L, 1);

    BSet main = GetLastActiveLayoutSet();
    if (kind == "console") {
        BSet set = GetConsoleSet();
        Command_SelectRangeOneCursor(set.view, MakeRange(set.buffer->len));
        Command_BeginJump(&set);
        Exec(set.view->id, true, cmd, working_dir);
        Command_EndJump(set);
    } else if (kind == "fuzzy") {
        JumpGarbageBuffer(&main);
        Exec(main.view->id, true, cmd, working_dir);
        main.view->fuzzy_search = true;
        ActiveWindow = main.window->id;
    } else {
        JumpGarbageBuffer(&main);
        Exec(main.view->id, true, cmd, working_dir);
        ActiveWindow = main.window->id;
    }

    return 0;
}

void Command_ListBuffers() {
    BSet main = GetActiveSet();
    ActiveWindow = main.window->id;
    JumpGarbageBuffer(&main);
    For(Buffers) {
        RawAppendf(main.buffer, "%-80S || %S\n", SkipToLastSlash(it->name), it->name);
    }
    main.view->fuzzy_search = true;
    main.view->update_scroll = true;
    Command_SelectRangeOneCursor(main.view, GetBufferEndAsRange(main.buffer));
}

int Lua_ListBuffers(lua_State *L) {
    Command_ListBuffers();
    return 0;
}

void Command_ListViews() {
    BSet main = GetLastActiveLayoutSet();
    ActiveWindow = main.window->id;
    JumpGarbageBuffer(&main);
    For(Views) {
        Buffer *buffer = GetBuffer(it->active_buffer);
        Command_Appendf(main.view, "%d %S\n", (int)it->id.id, buffer->name);
    }
}

int Lua_ListViews(lua_State *L) {
    Command_ListViews();
    return 0;
}

void Command_Eval(String string) {
    if (luaL_dostring(LuaState, string.data) != LUA_OK) {
        const char *error_message = lua_tostring(LuaState, -1);
        ReportWarningf("Execution error! %s", error_message);
        lua_pop(LuaState, 1);
    }
}

void Command_Eval(String16 string) {
    Scratch scratch;
    Command_Eval(ToString(scratch, string));
}

int Lua_Eval(lua_State *L) {
    String string = lua_tostring(L, 1);
    lua_pop(L, 1);
    Command_Eval(string);

    return 0;
}

void SetProjectFile(Buffer *buffer) {
    WorkDir = ChopLastSlash(buffer->name);
    LuaProjectBuffer = buffer;
    LuaProjectBuffer->user_change_id = -1;
}

int Lua_SetProjectFile(lua_State *L) {
    BSet set = GetLastActiveLayoutSet();
    SetProjectFile(set.buffer);
    return 0;
}

int Lua_SetWorkDir(lua_State *L) {
    String dir = lua_tostring(L, -1);
    if (dir.len == 0) {
        BSet set = GetLastActiveLayoutSet();
        WorkDir = ChopLastSlash(set.buffer->name);
    } else {
        WorkDir = dir;
    }
    return 0;
}

int Lua_ListCommands(lua_State *L) {
    BSet main = GetLastActiveLayoutSet();
    Command_BeginJump(&main);
    for (int i = 0; LuaFunctions[i].name != NULL; i += 1) {
        Command_Appendf(main.view, "%20s() ", LuaFunctions[i].name);
        if (((i + 1) % 6) == 0) {
            Command_Appendf(main.view, "\n");
        }
    }
    Command_EndJump(main);
    ActiveWindow = main.window->id;
    return 0;
}

int Lua_GetBufferList(lua_State *L) {
    lua_createtable(L, 0, (int)Buffers.len);

    int i = 1;
    For(Buffers) {
        lua_pushinteger(L, i++);
        lua_pushlstring(L, it->name.data, it->name.len);
        lua_settable(L, -3); /* 3rd element from the stack top */
    }
    /* We still have table left on top of the Lua stack. */
    return 1;
}

Window *GetOverlappingWindow(Vec2I p, Window *default_window = NULL) {
    For(Windows) {
        if (AreOverlapping(p, it->total_rect)) {
            return it;
        }
    }
    return default_window;
}

Vec2I GetSideOfWindow(Window *window, int direction) {
    Vec2I p = {};
    Rect2I rect = window->total_rect;
    float resizer_size = (float)window->font->char_spacing*0.5f; // @check_codebase_when_changing
    if (direction == DIR_LEFT) {
        p.x = rect.min.x - (Int)(resizer_size + window->font->char_spacing);
        p.y = rect.min.y + (rect.max.y / 2);
    } else if (direction == DIR_RIGHT) {
        p.x = rect.max.x + (Int)(resizer_size + window->font->char_spacing);
        p.y = rect.min.y + (rect.max.y / 2);
    } else if (direction == DIR_UP) {
        p.x = rect.min.x + (rect.max.x / 2);
        p.y = rect.min.y - (Int)(resizer_size + window->font->line_spacing);
    } else {
        Assert(direction == DIR_DOWN);
        p.x = rect.min.x + (rect.max.x / 2);
        p.y = rect.max.y + (Int)(resizer_size + window->font->line_spacing);
    }
    return p;
}

Window *SwitchWindow(int direction) {
    Window *window = GetWindow(ActiveWindow);
    Vec2I p = GetSideOfWindow(window, direction);
    Window *result = GetOverlappingWindow(p, window);
    return result;
}

String16 FetchLoadWord(void) {
    BSet active = GetActiveSet();
    Caret caret = active.view->carets[0];
    Range range = caret.range;
    if (GetSize(caret.range) == 0) range = EncloseLoadWord(active.buffer, GetFront(caret));
    String16 string = GetString(active.buffer, range);
    return string;
}
