Compare commits
18 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6eb240a0c4 | |||
| 4c402f5ef3 | |||
| a8abda4b87 | |||
| 7347556aa2 | |||
| 289e155c98 | |||
| 147a52f3d4 | |||
| dda7541e2f | |||
| 2408f5494c | |||
| 2542690eca | |||
| cc0c187481 | |||
| a8dcfbec58 | |||
| 65705e3354 | |||
| e1f9a9eb6a | |||
| c9f34003f2 | |||
| f450ef825c | |||
| f6f0c11be4 | |||
| 657c9bbc19 | |||
| 3493695165 |
1
.idea/codeStyles/codeStyleConfig.xml
generated
1
.idea/codeStyles/codeStyleConfig.xml
generated
@@ -1,5 +1,6 @@
|
||||
<component name="ProjectCodeStyleConfiguration">
|
||||
<state>
|
||||
<option name="USE_PER_PROJECT_SETTINGS" value="true" />
|
||||
<option name="PREFERRED_PROJECT_CODE_STYLE" value="sccl" />
|
||||
</state>
|
||||
</component>
|
||||
3
.idea/editor.xml
generated
3
.idea/editor.xml
generated
@@ -19,7 +19,7 @@
|
||||
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppBoostFormatTooManyArgs/@EntryIndexedValue" value="WARNING" type="string" />
|
||||
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppCStyleCast/@EntryIndexedValue" value="SUGGESTION" type="string" />
|
||||
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppCVQualifierCanNotBeAppliedToReference/@EntryIndexedValue" value="WARNING" type="string" />
|
||||
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppClassCanBeFinal/@EntryIndexedValue" value="HINT" type="string" />
|
||||
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppClassCanBeFinal/@EntryIndexedValue" value="DO_NOT_SHOW" type="string" />
|
||||
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppClassIsIncomplete/@EntryIndexedValue" value="WARNING" type="string" />
|
||||
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppClassNeedsConstructorBecauseOfUninitializedMember/@EntryIndexedValue" value="WARNING" type="string" />
|
||||
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppClassNeverUsed/@EntryIndexedValue" value="WARNING" type="string" />
|
||||
@@ -58,6 +58,7 @@
|
||||
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDefaultInitializationWithNoUserConstructor/@EntryIndexedValue" value="WARNING" type="string" />
|
||||
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDefaultIsUsedAsIdentifier/@EntryIndexedValue" value="WARNING" type="string" />
|
||||
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDefaultedSpecialMemberFunctionIsImplicitlyDeleted/@EntryIndexedValue" value="WARNING" type="string" />
|
||||
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDefinitionsOrder/@EntryIndexedValue" value="HINT" type="string" />
|
||||
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDeletingVoidPointer/@EntryIndexedValue" value="WARNING" type="string" />
|
||||
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDependentTemplateWithoutTemplateKeyword/@EntryIndexedValue" value="WARNING" type="string" />
|
||||
<option name="/Default/CodeInspection/Highlighting/InspectionSeverities/=CppDependentTypeWithoutTypenameKeyword/@EntryIndexedValue" value="WARNING" type="string" />
|
||||
|
||||
2
.idea/kte.iml
generated
2
.idea/kte.iml
generated
@@ -1,5 +1,5 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module classpath="CMake" type="CPP_MODULE" version="4">
|
||||
<module classpath="CIDR" type="CPP_MODULE" version="4">
|
||||
<component name="FacetManager">
|
||||
<facet type="Python" name="Python facet">
|
||||
<configuration sdkName="" />
|
||||
|
||||
65
Buffer.cc
65
Buffer.cc
@@ -292,28 +292,29 @@ Buffer::OpenFromFile(const std::string &path, std::string &err)
|
||||
bool
|
||||
Buffer::Save(std::string &err) const
|
||||
{
|
||||
if (!is_file_backed_ || filename_.empty()) {
|
||||
err = "Buffer is not file-backed; use SaveAs()";
|
||||
return false;
|
||||
}
|
||||
std::ofstream out(filename_, std::ios::out | std::ios::binary | std::ios::trunc);
|
||||
if (!out) {
|
||||
err = "Failed to open for write: " + filename_ + ". Error: " + std::string(std::strerror(errno));
|
||||
return false;
|
||||
}
|
||||
// Write the entire buffer in a single block to minimize I/O calls.
|
||||
const char *data = content_.Data();
|
||||
const auto size = static_cast<std::streamsize>(content_.Size());
|
||||
if (data != nullptr && size > 0) {
|
||||
out.write(data, size);
|
||||
}
|
||||
if (!out.good()) {
|
||||
err = "Write error: " + filename_ + ". Error: " + std::string(std::strerror(errno));
|
||||
return false;
|
||||
}
|
||||
// Note: const method cannot change dirty_. Intentionally const to allow UI code
|
||||
// to decide when to flip dirty flag after successful save.
|
||||
return true;
|
||||
if (!is_file_backed_ || filename_.empty()) {
|
||||
err = "Buffer is not file-backed; use SaveAs()";
|
||||
return false;
|
||||
}
|
||||
std::ofstream out(filename_, std::ios::out | std::ios::binary | std::ios::trunc);
|
||||
if (!out) {
|
||||
err = "Failed to open for write: " + filename_ + ". Error: " + std::string(std::strerror(errno));
|
||||
return false;
|
||||
}
|
||||
// Stream the content directly from the piece table to avoid relying on
|
||||
// full materialization, which may yield an empty pointer when size > 0.
|
||||
if (content_.Size() > 0) {
|
||||
content_.WriteToStream(out);
|
||||
}
|
||||
// Ensure data hits the OS buffers
|
||||
out.flush();
|
||||
if (!out.good()) {
|
||||
err = "Write error: " + filename_ + ". Error: " + std::string(std::strerror(errno));
|
||||
return false;
|
||||
}
|
||||
// Note: const method cannot change dirty_. Intentionally const to allow UI code
|
||||
// to decide when to flip dirty flag after successful save.
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -345,16 +346,16 @@ Buffer::SaveAs(const std::string &path, std::string &err)
|
||||
err = "Failed to open for write: " + out_path + ". Error: " + std::string(std::strerror(errno));
|
||||
return false;
|
||||
}
|
||||
// Write whole content in a single I/O operation
|
||||
const char *data = content_.Data();
|
||||
const auto size = static_cast<std::streamsize>(content_.Size());
|
||||
if (data != nullptr && size > 0) {
|
||||
out.write(data, size);
|
||||
}
|
||||
if (!out.good()) {
|
||||
err = "Write error: " + out_path + ". Error: " + std::string(std::strerror(errno));
|
||||
return false;
|
||||
}
|
||||
// Stream content without forcing full materialization
|
||||
if (content_.Size() > 0) {
|
||||
content_.WriteToStream(out);
|
||||
}
|
||||
// Ensure data hits the OS buffers
|
||||
out.flush();
|
||||
if (!out.good()) {
|
||||
err = "Write error: " + out_path + ". Error: " + std::string(std::strerror(errno));
|
||||
return false;
|
||||
}
|
||||
|
||||
filename_ = out_path;
|
||||
is_file_backed_ = true;
|
||||
|
||||
@@ -4,7 +4,7 @@ project(kte)
|
||||
include(GNUInstallDirs)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 20)
|
||||
set(KTE_VERSION "1.5.1")
|
||||
set(KTE_VERSION "1.5.8")
|
||||
|
||||
# Default to terminal-only build to avoid SDL/OpenGL dependency by default.
|
||||
# Enable with -DBUILD_GUI=ON when SDL2/OpenGL/Freetype are available.
|
||||
@@ -63,7 +63,7 @@ endif ()
|
||||
|
||||
message(STATUS "Build system: ${CMAKE_HOST_SYSTEM_NAME}")
|
||||
|
||||
if (${BUILD_GUI})
|
||||
if (BUILD_GUI)
|
||||
include(cmake/imgui.cmake)
|
||||
endif ()
|
||||
|
||||
@@ -208,6 +208,7 @@ set(FONT_HEADERS
|
||||
fonts/Syne.h
|
||||
fonts/Triplicate.h
|
||||
fonts/Unispace.h
|
||||
fonts/BerkeleyMono.h
|
||||
)
|
||||
|
||||
set(COMMON_HEADERS
|
||||
@@ -255,6 +256,7 @@ if (BUILD_GUI)
|
||||
ImGuiFrontend.h
|
||||
ImGuiInputHandler.h
|
||||
ImGuiRenderer.h
|
||||
fonts/BerkeleyMono.h
|
||||
)
|
||||
endif ()
|
||||
endif ()
|
||||
@@ -292,30 +294,39 @@ install(TARGETS kte
|
||||
install(FILES docs/kte.1 DESTINATION ${CMAKE_INSTALL_MANDIR}/man1)
|
||||
|
||||
if (BUILD_TESTS)
|
||||
# test_undo executable for testing undo/redo system
|
||||
add_executable(test_undo
|
||||
test_undo.cc
|
||||
${COMMON_SOURCES}
|
||||
${COMMON_HEADERS}
|
||||
# Unified unit test runner
|
||||
add_executable(kte_tests
|
||||
tests/TestRunner.cc
|
||||
tests/Test.h
|
||||
tests/test_buffer_io.cc
|
||||
tests/test_piece_table.cc
|
||||
tests/test_search.cc
|
||||
|
||||
# minimal engine sources required by Buffer
|
||||
PieceTable.cc
|
||||
Buffer.cc
|
||||
OptimizedSearch.cc
|
||||
UndoNode.cc
|
||||
UndoTree.cc
|
||||
UndoSystem.cc
|
||||
${SYNTAX_SOURCES}
|
||||
)
|
||||
|
||||
if (KTE_UNDO_DEBUG)
|
||||
target_compile_definitions(test_undo PRIVATE KTE_UNDO_DEBUG=1)
|
||||
endif ()
|
||||
# Allow tests to include project headers like "Buffer.h"
|
||||
target_include_directories(kte_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
|
||||
|
||||
target_link_libraries(test_undo ${CURSES_LIBRARIES})
|
||||
# Keep tests free of ncurses/GUI deps
|
||||
if (KTE_ENABLE_TREESITTER)
|
||||
if (TREESITTER_INCLUDE_DIR)
|
||||
target_include_directories(test_undo PRIVATE ${TREESITTER_INCLUDE_DIR})
|
||||
target_include_directories(kte_tests PRIVATE ${TREESITTER_INCLUDE_DIR})
|
||||
endif ()
|
||||
if (TREESITTER_LIBRARY)
|
||||
target_link_libraries(test_undo ${TREESITTER_LIBRARY})
|
||||
target_link_libraries(kte_tests ${TREESITTER_LIBRARY})
|
||||
endif ()
|
||||
endif ()
|
||||
endif ()
|
||||
|
||||
if (${BUILD_GUI})
|
||||
if (BUILD_GUI)
|
||||
# ImGui::CreateContext();
|
||||
# ImGuiIO& io = ImGui::GetIO();
|
||||
|
||||
@@ -370,12 +381,18 @@ if (${BUILD_GUI})
|
||||
${CMAKE_CURRENT_BINARY_DIR}/kge-Info.plist
|
||||
@ONLY)
|
||||
|
||||
# Ensure proper macOS bundle properties and RPATH so our bundled
|
||||
# frameworks are preferred over system/Homebrew ones.
|
||||
set_target_properties(kge PROPERTIES
|
||||
MACOSX_BUNDLE TRUE
|
||||
MACOSX_BUNDLE_GUI_IDENTIFIER ${KGE_BUNDLE_ID}
|
||||
MACOSX_BUNDLE_BUNDLE_NAME "kge"
|
||||
MACOSX_BUNDLE_ICON_FILE ${MACOSX_BUNDLE_ICON_FILE}
|
||||
MACOSX_BUNDLE_INFO_PLIST "${CMAKE_CURRENT_BINARY_DIR}/kge-Info.plist")
|
||||
MACOSX_BUNDLE_INFO_PLIST "${CMAKE_CURRENT_BINARY_DIR}/kge-Info.plist"
|
||||
# Prefer the app's bundled frameworks at runtime
|
||||
INSTALL_RPATH "@executable_path/../Frameworks"
|
||||
BUILD_WITH_INSTALL_RPATH TRUE
|
||||
)
|
||||
|
||||
add_dependencies(kge kte)
|
||||
add_custom_command(TARGET kge POST_BUILD
|
||||
@@ -399,4 +416,20 @@ if (${BUILD_GUI})
|
||||
# Install kge man page only when GUI is built
|
||||
install(FILES docs/kge.1 DESTINATION ${CMAKE_INSTALL_MANDIR}/man1)
|
||||
install(FILES kge.png DESTINATION ${CMAKE_INSTALL_PREFIX}/share/icons)
|
||||
|
||||
# Optional post-build bundle fixup (can also be run from scripts).
|
||||
# This provides a CMake target to run BundleUtilities' fixup_bundle on the
|
||||
# built app, useful after macdeployqt to ensure non-Qt dylibs are internalized.
|
||||
if (APPLE AND TARGET kge)
|
||||
get_target_property(IS_BUNDLE kge MACOSX_BUNDLE)
|
||||
if (IS_BUNDLE)
|
||||
add_custom_target(kge_fixup_bundle ALL
|
||||
COMMAND ${CMAKE_COMMAND}
|
||||
-DAPP_BUNDLE=${CMAKE_CURRENT_BINARY_DIR}/$<TARGET_PROPERTY:kge,MACOSX_BUNDLE_BUNDLE_NAME>.app
|
||||
-P ${CMAKE_CURRENT_LIST_DIR}/cmake/fix_bundle.cmake
|
||||
COMMENT "Running fixup_bundle on kge.app to internalize non-Qt dylibs"
|
||||
VERBATIM)
|
||||
add_dependencies(kge_fixup_bundle kge)
|
||||
endif ()
|
||||
endif ()
|
||||
endif ()
|
||||
|
||||
349
Command.cc
349
Command.cc
@@ -237,8 +237,8 @@ extract_region_text(const Buffer &buf, std::size_t sx, std::size_t sy, std::size
|
||||
{
|
||||
const auto &line = rows[sy];
|
||||
std::size_t xs = std::min(sx, line.size());
|
||||
out += line.substr(xs);
|
||||
out += '\n';
|
||||
out += line.substr(xs);
|
||||
out += '\n';
|
||||
}
|
||||
// middle lines full
|
||||
for (std::size_t y = sy + 1; y < ey; ++y) {
|
||||
@@ -249,7 +249,7 @@ extract_region_text(const Buffer &buf, std::size_t sx, std::size_t sy, std::size
|
||||
{
|
||||
const auto &line = rows[ey];
|
||||
std::size_t xe = std::min(ex, line.size());
|
||||
out += line.substr(0, xe);
|
||||
out += line.substr(0, xe);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -277,7 +277,7 @@ delete_region(Buffer &buf, std::size_t sx, std::size_t sy, std::size_t ex, std::
|
||||
buf.delete_text(static_cast<int>(sy), static_cast<int>(xs), xe - xs);
|
||||
} else {
|
||||
// Multi-line: delete from (sx,sy) to (ex,ey)
|
||||
// Strategy:
|
||||
// Strategy:
|
||||
// 1. Save suffix of last line (from ex to end)
|
||||
// 2. Delete tail of first line (from sx to end)
|
||||
// 3. Delete all lines from sy+1 to ey (inclusive)
|
||||
@@ -1585,6 +1585,19 @@ cmd_buffer_close(const CommandContext &ctx)
|
||||
}
|
||||
|
||||
|
||||
// Create a new empty, unnamed buffer and switch to it
|
||||
static bool
|
||||
cmd_buffer_new(const CommandContext &ctx)
|
||||
{
|
||||
// Create an empty buffer and add it to the editor
|
||||
Buffer empty;
|
||||
std::size_t idx = ctx.editor.AddBuffer(std::move(empty));
|
||||
ctx.editor.SwitchTo(idx);
|
||||
ctx.editor.SetStatus("New buffer");
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
// --- Editing ---
|
||||
static bool
|
||||
cmd_insert_text(CommandContext &ctx)
|
||||
@@ -1909,7 +1922,7 @@ cmd_insert_text(CommandContext &ctx)
|
||||
// If in search mode, treat printable input as query update
|
||||
if (ctx.editor.SearchActive()) {
|
||||
std::string q = ctx.editor.SearchQuery();
|
||||
q += ctx.arg; // arg already printable text
|
||||
q += ctx.arg; // arg already printable text
|
||||
ctx.editor.SetSearchQuery(q);
|
||||
|
||||
// Recompute matches and move cursor to current index
|
||||
@@ -1955,24 +1968,29 @@ cmd_insert_text(CommandContext &ctx)
|
||||
return false;
|
||||
}
|
||||
ensure_at_least_one_line(*buf);
|
||||
auto &rows = buf->Rows();
|
||||
std::size_t y = buf->Cury();
|
||||
std::size_t x = buf->Curx();
|
||||
if (y >= rows.size()) {
|
||||
rows.resize(y + 1);
|
||||
}
|
||||
int repeat = ctx.count > 0 ? ctx.count : 1;
|
||||
std::size_t y = buf->Cury();
|
||||
std::size_t x = buf->Curx();
|
||||
std::size_t ins_y = y;
|
||||
std::size_t ins_x = x; // remember insertion start for undo positioning
|
||||
int repeat = ctx.count > 0 ? ctx.count : 1;
|
||||
|
||||
// Apply edits to the underlying PieceTable through Buffer::insert_text,
|
||||
// not directly to the legacy rows_ cache. This ensures Save() persists text.
|
||||
for (int i = 0; i < repeat; ++i) {
|
||||
rows[y].insert(x, ctx.arg);
|
||||
buf->insert_text(static_cast<int>(y), static_cast<int>(x), std::string_view(ctx.arg));
|
||||
x += ctx.arg.size();
|
||||
}
|
||||
buf->SetDirty(true);
|
||||
// Record undo after buffer modification but before cursor update
|
||||
// Record undo for this contiguous insert at the original insertion point
|
||||
if (auto *u = buf->Undo()) {
|
||||
// Position cursor at insertion start for the undo record
|
||||
buf->SetCursor(ins_x, ins_y);
|
||||
u->Begin(UndoType::Insert);
|
||||
for (int i = 0; i < repeat; ++i) {
|
||||
u->Append(std::string_view(ctx.arg));
|
||||
}
|
||||
// Finalize this contiguous insert as a single undoable action
|
||||
u->commit();
|
||||
}
|
||||
buf->SetCursor(x, y);
|
||||
ensure_cursor_visible(ctx.editor, *buf);
|
||||
@@ -2307,48 +2325,53 @@ cmd_newline(CommandContext &ctx)
|
||||
// Save original cursor to restore after operations
|
||||
std::size_t orig_x = buf->Curx();
|
||||
std::size_t orig_y = buf->Cury();
|
||||
auto &rows = buf->Rows();
|
||||
std::size_t total = 0;
|
||||
UndoSystem *u = buf->Undo();
|
||||
if (u)
|
||||
u->commit(); // end any pending batch
|
||||
for (std::size_t y = 0; y < rows.size(); ++y) {
|
||||
for (std::size_t y = 0; y < buf->Rows().size(); ++y) {
|
||||
std::size_t pos = 0;
|
||||
while (!find.empty()) {
|
||||
pos = rows[y].find(find, pos);
|
||||
if (pos == std::string::npos)
|
||||
while (true) {
|
||||
const auto &rows_view = buf->Rows();
|
||||
if (y >= rows_view.size())
|
||||
break;
|
||||
// Perform delete of matched segment
|
||||
rows[y].erase(pos, find.size());
|
||||
std::string line = static_cast<std::string>(rows_view[y]);
|
||||
if (find.empty())
|
||||
break;
|
||||
std::size_t p = line.find(find, pos);
|
||||
if (p == std::string::npos)
|
||||
break;
|
||||
// Delete matched segment from the piece table
|
||||
buf->delete_text(static_cast<int>(y), static_cast<int>(p), find.size());
|
||||
if (u) {
|
||||
buf->SetCursor(pos, y);
|
||||
buf->SetCursor(p, y);
|
||||
u->Begin(UndoType::Delete);
|
||||
u->Append(std::string_view(find));
|
||||
}
|
||||
// Insert replacement
|
||||
// Insert replacement if provided
|
||||
if (!with.empty()) {
|
||||
rows[y].insert(pos, with);
|
||||
buf->insert_text(static_cast<int>(y), static_cast<int>(p),
|
||||
std::string_view(with));
|
||||
if (u) {
|
||||
buf->SetCursor(pos, y);
|
||||
buf->SetCursor(p, y);
|
||||
u->Begin(UndoType::Insert);
|
||||
u->Append(std::string_view(with));
|
||||
}
|
||||
pos += with.size();
|
||||
}
|
||||
++total;
|
||||
if (with.empty()) {
|
||||
// Avoid infinite loop when replacing with empty
|
||||
// pos remains the same; move forward by 1 to continue search
|
||||
if (pos < rows[y].size())
|
||||
pos = p + with.size();
|
||||
} else {
|
||||
// When replacing with empty, continue after the deletion point to avoid re-matching
|
||||
pos = p;
|
||||
if (pos < static_cast<std::size_t>(buf->Rows()[y].size()))
|
||||
++pos;
|
||||
else
|
||||
break;
|
||||
}
|
||||
++total;
|
||||
}
|
||||
}
|
||||
buf->SetDirty(true);
|
||||
// Restore original cursor
|
||||
if (orig_y < rows.size())
|
||||
if (orig_y < buf->Rows().size())
|
||||
buf->SetCursor(orig_x, orig_y);
|
||||
ensure_cursor_visible(ctx.editor, *buf);
|
||||
char msg[128];
|
||||
@@ -2383,6 +2406,10 @@ cmd_newline(CommandContext &ctx)
|
||||
ctx.editor.SetStatus(err.empty() ? std::string("Failed to open ") + value : err);
|
||||
} else {
|
||||
ctx.editor.SetStatus(std::string("Opened ") + value);
|
||||
// Center the view on the cursor (e.g. if the buffer restored a cursor position)
|
||||
cmd_center_on_cursor(ctx);
|
||||
// Close the prompt so subsequent typing edits the buffer, not the prompt
|
||||
ctx.editor.CancelPrompt();
|
||||
}
|
||||
} else if (kind == Editor::PromptKind::BufferSwitch) {
|
||||
// Resolve to a buffer index by exact match against path or basename;
|
||||
@@ -2452,6 +2479,8 @@ cmd_newline(CommandContext &ctx)
|
||||
ctx.editor.SetStatus("Saved as " + value);
|
||||
if (auto *u = buf->Undo())
|
||||
u->mark_saved();
|
||||
// Close the prompt on successful save-as
|
||||
ctx.editor.CancelPrompt();
|
||||
// If a close-after-save was requested (from closing a dirty, unnamed buffer),
|
||||
// close the buffer now.
|
||||
if (ctx.editor.CloseAfterSave()) {
|
||||
@@ -2516,9 +2545,13 @@ cmd_newline(CommandContext &ctx)
|
||||
" Now: ")
|
||||
+ (cur ? buffer_display_name(*cur) : std::string("")));
|
||||
}
|
||||
// Close the prompt after successful confirmation
|
||||
ctx.editor.CancelPrompt();
|
||||
}
|
||||
} else {
|
||||
ctx.editor.SetStatus("Save canceled");
|
||||
// Close the prompt after negative confirmation
|
||||
ctx.editor.CancelPrompt();
|
||||
}
|
||||
ctx.editor.ClearPendingOverwritePath();
|
||||
// Regardless of answer, end any close-after-save pending state for safety.
|
||||
@@ -2705,13 +2738,15 @@ cmd_newline(CommandContext &ctx)
|
||||
ctx.editor.SetSearchIndex(-1);
|
||||
return true;
|
||||
}
|
||||
auto &rows = buf->Rows();
|
||||
std::size_t changed = 0;
|
||||
for (auto &line: rows) {
|
||||
std::string before = static_cast<std::string>(line);
|
||||
// Iterate by index to allow modifications via PieceTable helpers
|
||||
for (std::size_t y = 0; y < buf->Rows().size(); ++y) {
|
||||
std::string before = static_cast<std::string>(buf->Rows()[y]);
|
||||
std::string after = std::regex_replace(before, rx, repl);
|
||||
if (after != before) {
|
||||
line = after;
|
||||
// Replace entire line y with 'after' using PieceTable ops
|
||||
buf->delete_row(static_cast<int>(y));
|
||||
buf->insert_row(static_cast<int>(y), std::string_view(after));
|
||||
++changed;
|
||||
}
|
||||
}
|
||||
@@ -2746,26 +2781,17 @@ cmd_newline(CommandContext &ctx)
|
||||
return false;
|
||||
}
|
||||
ensure_at_least_one_line(*buf);
|
||||
auto &rows = buf->Rows();
|
||||
std::size_t y = buf->Cury();
|
||||
std::size_t x = buf->Curx();
|
||||
int repeat = ctx.count > 0 ? ctx.count : 1;
|
||||
for (int i = 0; i < repeat; ++i) {
|
||||
if (y >= rows.size())
|
||||
rows.resize(y + 1);
|
||||
auto &line = rows[y];
|
||||
std::string tail;
|
||||
if (x < line.size()) {
|
||||
tail = line.substr(x);
|
||||
line.erase(x);
|
||||
}
|
||||
rows.insert(rows.begin() + static_cast<std::ptrdiff_t>(y + 1), Buffer::Line(tail));
|
||||
buf->split_line(static_cast<int>(y), static_cast<int>(x));
|
||||
// Move to start of next line
|
||||
y += 1;
|
||||
x = 0;
|
||||
}
|
||||
buf->SetCursor(x, y);
|
||||
buf->SetDirty(true);
|
||||
// Record newline after buffer modification; commit immediately for single-step undo
|
||||
if (auto *u = buf->Undo()) {
|
||||
u->Begin(UndoType::Newline);
|
||||
u->commit();
|
||||
@@ -2828,44 +2854,42 @@ cmd_backspace(CommandContext &ctx)
|
||||
return false;
|
||||
}
|
||||
ensure_at_least_one_line(*buf);
|
||||
auto &rows = buf->Rows();
|
||||
std::size_t y = buf->Cury();
|
||||
std::size_t x = buf->Curx();
|
||||
UndoSystem *u = buf->Undo();
|
||||
int repeat = ctx.count > 0 ? ctx.count : 1;
|
||||
for (int i = 0; i < repeat; ++i) {
|
||||
// Refresh a read-only view of lines for char capture/lengths
|
||||
const auto &rows_view = buf->Rows();
|
||||
if (x > 0) {
|
||||
// Delete character before cursor
|
||||
char deleted = rows[y][x - 1];
|
||||
rows[y].erase(x - 1, 1);
|
||||
--x;
|
||||
// Update buffer cursor BEFORE Begin so batching sees correct cursor for backspace
|
||||
char deleted = '\0';
|
||||
if (y < rows_view.size() && x - 1 < rows_view[y].size())
|
||||
deleted = rows_view[y][x - 1];
|
||||
buf->delete_text(static_cast<int>(y), static_cast<int>(x - 1), 1);
|
||||
x -= 1;
|
||||
buf->SetCursor(x, y);
|
||||
// Record undo after deletion and cursor update
|
||||
if (u) {
|
||||
u->Begin(UndoType::Delete);
|
||||
u->Append(deleted);
|
||||
if (deleted != '\0')
|
||||
u->Append(deleted);
|
||||
}
|
||||
} else if (y > 0) {
|
||||
// join with previous line
|
||||
std::size_t prev_len = rows[y - 1].size();
|
||||
rows[y - 1] += rows[y];
|
||||
rows.erase(rows.begin() + static_cast<std::ptrdiff_t>(y));
|
||||
// Compute previous line length before join
|
||||
std::size_t prev_len = 0;
|
||||
if (y - 1 < rows_view.size())
|
||||
prev_len = rows_view[y - 1].size();
|
||||
buf->join_lines(static_cast<int>(y - 1));
|
||||
y = y - 1;
|
||||
x = prev_len;
|
||||
// Update cursor to the join point BEFORE Begin to keep invariants consistent
|
||||
buf->SetCursor(x, y);
|
||||
// Record a newline deletion that joined lines; commit immediately
|
||||
if (u) {
|
||||
u->Begin(UndoType::Newline);
|
||||
u->commit();
|
||||
}
|
||||
} else {
|
||||
// at very start; nothing to do
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Ensure buffer cursor reflects final x,y
|
||||
buf->SetCursor(x, y);
|
||||
buf->SetDirty(true);
|
||||
ensure_cursor_visible(ctx.editor, *buf);
|
||||
@@ -2882,28 +2906,23 @@ cmd_delete_char(CommandContext &ctx)
|
||||
return false;
|
||||
}
|
||||
ensure_at_least_one_line(*buf);
|
||||
auto &rows = buf->Rows();
|
||||
std::size_t y = buf->Cury();
|
||||
std::size_t x = buf->Curx();
|
||||
UndoSystem *u = buf->Undo();
|
||||
int repeat = ctx.count > 0 ? ctx.count : 1;
|
||||
for (int i = 0; i < repeat; ++i) {
|
||||
if (y >= rows.size())
|
||||
const auto &rows_view = buf->Rows();
|
||||
if (y >= rows_view.size())
|
||||
break;
|
||||
if (x < rows[y].size()) {
|
||||
// Forward delete at cursor
|
||||
char deleted = rows[y][x];
|
||||
rows[y].erase(x, 1);
|
||||
// Record undo after deletion (cursor stays at same position)
|
||||
if (x < rows_view[y].size()) {
|
||||
char deleted = rows_view[y][x];
|
||||
buf->delete_text(static_cast<int>(y), static_cast<int>(x), 1);
|
||||
if (u) {
|
||||
u->Begin(UndoType::Delete);
|
||||
u->Append(deleted);
|
||||
}
|
||||
} else if (y + 1 < rows.size()) {
|
||||
// join next line
|
||||
rows[y] += rows[y + 1];
|
||||
rows.erase(rows.begin() + static_cast<std::ptrdiff_t>(y + 1));
|
||||
// Record newline deletion at end of this line; commit immediately
|
||||
} else if (y + 1 < rows_view.size()) {
|
||||
buf->join_lines(static_cast<int>(y));
|
||||
if (u) {
|
||||
u->Begin(UndoType::Newline);
|
||||
u->commit();
|
||||
@@ -2965,23 +2984,23 @@ cmd_kill_to_eol(CommandContext &ctx)
|
||||
return false;
|
||||
}
|
||||
ensure_at_least_one_line(*buf);
|
||||
auto &rows = buf->Rows();
|
||||
std::size_t y = buf->Cury();
|
||||
std::size_t x = buf->Curx();
|
||||
int repeat = ctx.count > 0 ? ctx.count : 1;
|
||||
std::string killed_total;
|
||||
for (int i = 0; i < repeat; ++i) {
|
||||
if (y >= rows.size())
|
||||
const auto &rows_view = buf->Rows();
|
||||
if (y >= rows_view.size())
|
||||
break;
|
||||
if (x < rows[y].size()) {
|
||||
if (x < rows_view[y].size()) {
|
||||
// delete from cursor to end of line
|
||||
killed_total += rows[y].substr(x);
|
||||
rows[y].erase(x);
|
||||
} else if (y + 1 < rows.size()) {
|
||||
killed_total += rows_view[y].substr(x);
|
||||
std::size_t len = rows_view[y].size() - x;
|
||||
buf->delete_text(static_cast<int>(y), static_cast<int>(x), len);
|
||||
} else if (y + 1 < rows_view.size()) {
|
||||
// at EOL: delete the newline (join with next line)
|
||||
killed_total += "\n";
|
||||
rows[y] += rows[y + 1];
|
||||
rows.erase(rows.begin() + static_cast<std::ptrdiff_t>(y + 1));
|
||||
buf->join_lines(static_cast<int>(y));
|
||||
} else {
|
||||
// nothing to delete
|
||||
break;
|
||||
@@ -3009,32 +3028,35 @@ cmd_kill_line(CommandContext &ctx)
|
||||
return false;
|
||||
}
|
||||
ensure_at_least_one_line(*buf);
|
||||
auto &rows = buf->Rows();
|
||||
std::size_t y = buf->Cury();
|
||||
std::size_t x = buf->Curx();
|
||||
(void) x; // cursor x will be reset to 0
|
||||
int repeat = ctx.count > 0 ? ctx.count : 1;
|
||||
std::string killed_total;
|
||||
for (int i = 0; i < repeat; ++i) {
|
||||
if (rows.empty())
|
||||
const auto &rows_view = buf->Rows();
|
||||
if (rows_view.empty())
|
||||
break;
|
||||
if (rows.size() == 1) {
|
||||
if (rows_view.size() == 1) {
|
||||
// last remaining line: clear its contents
|
||||
killed_total += static_cast<std::string>(rows[0]);
|
||||
rows[0].Clear();
|
||||
killed_total += static_cast<std::string>(rows_view[0]);
|
||||
if (!rows_view[0].empty())
|
||||
buf->delete_text(0, 0, rows_view[0].size());
|
||||
y = 0;
|
||||
} else if (y < rows.size()) {
|
||||
} else if (y < rows_view.size()) {
|
||||
// erase current line; keep y pointing at the next line
|
||||
killed_total += static_cast<std::string>(rows[y]);
|
||||
killed_total += static_cast<std::string>(rows_view[y]);
|
||||
killed_total += "\n";
|
||||
rows.erase(rows.begin() + static_cast<std::ptrdiff_t>(y));
|
||||
if (y >= rows.size()) {
|
||||
buf->delete_row(static_cast<int>(y));
|
||||
const auto &rows_after = buf->Rows();
|
||||
if (y >= rows_after.size()) {
|
||||
// deleted last line; move to previous
|
||||
y = rows.size() - 1;
|
||||
y = rows_after.empty() ? 0 : rows_after.size() - 1;
|
||||
}
|
||||
} else {
|
||||
// out of range
|
||||
y = rows.empty() ? 0 : rows.size() - 1;
|
||||
const auto &rows2 = buf->Rows();
|
||||
y = rows2.empty() ? 0 : rows2.size() - 1;
|
||||
}
|
||||
}
|
||||
buf->SetCursor(0, y);
|
||||
@@ -3097,9 +3119,9 @@ cmd_move_file_end(CommandContext &ctx)
|
||||
if (!buf)
|
||||
return false;
|
||||
ensure_at_least_one_line(*buf);
|
||||
auto &rows = buf->Rows();
|
||||
std::size_t y = rows.empty() ? 0 : rows.size() - 1;
|
||||
std::size_t x = rows.empty() ? 0 : rows[y].size();
|
||||
const auto &rows = buf->Rows();
|
||||
std::size_t y = rows.empty() ? 0 : rows.size() - 1;
|
||||
std::size_t x = rows.empty() ? 0 : rows[y].size();
|
||||
buf->SetCursor(x, y);
|
||||
ensure_cursor_visible(ctx.editor, *buf);
|
||||
return true;
|
||||
@@ -3796,34 +3818,9 @@ cmd_delete_word_prev(CommandContext &ctx)
|
||||
break;
|
||||
--x;
|
||||
}
|
||||
// Now delete from (x, y) to (start_x, start_y)
|
||||
std::string deleted;
|
||||
if (y == start_y) {
|
||||
// same line
|
||||
if (x < start_x) {
|
||||
deleted = rows[y].substr(x, start_x - x);
|
||||
rows[y].erase(x, start_x - x);
|
||||
}
|
||||
} else {
|
||||
// spans multiple lines
|
||||
// First, collect text from (x, y) to end of line y
|
||||
deleted = rows[y].substr(x);
|
||||
rows[y].erase(x);
|
||||
// Then collect complete lines between y and start_y
|
||||
for (std::size_t ly = y + 1; ly < start_y; ++ly) {
|
||||
deleted += "\n";
|
||||
deleted += static_cast<std::string>(rows[ly]);
|
||||
}
|
||||
// Finally, collect from beginning of start_y to start_x
|
||||
if (start_y < rows.size()) {
|
||||
deleted += "\n";
|
||||
deleted += rows[start_y].substr(0, start_x);
|
||||
rows[y] += rows[start_y].substr(start_x);
|
||||
// Remove lines from y+1 to start_y inclusive
|
||||
rows.erase(rows.begin() + static_cast<std::ptrdiff_t>(y + 1),
|
||||
rows.begin() + static_cast<std::ptrdiff_t>(start_y + 1));
|
||||
}
|
||||
}
|
||||
// Now delete from (x, y) to (start_x, start_y) using PieceTable
|
||||
std::string deleted = extract_region_text(*buf, x, y, start_x, start_y);
|
||||
delete_region(*buf, x, y, start_x, start_y);
|
||||
// Prepend to killed_total (since we're deleting backwards)
|
||||
killed_total = deleted + killed_total;
|
||||
}
|
||||
@@ -3850,10 +3847,10 @@ cmd_delete_word_next(CommandContext &ctx)
|
||||
if (auto *u = buf->Undo())
|
||||
u->commit();
|
||||
ensure_at_least_one_line(*buf);
|
||||
auto &rows = buf->Rows();
|
||||
std::size_t y = buf->Cury();
|
||||
std::size_t x = buf->Curx();
|
||||
int repeat = ctx.count > 0 ? ctx.count : 1;
|
||||
const auto &rows = buf->Rows();
|
||||
std::size_t y = buf->Cury();
|
||||
std::size_t x = buf->Curx();
|
||||
int repeat = ctx.count > 0 ? ctx.count : 1;
|
||||
std::string killed_total;
|
||||
for (int i = 0; i < repeat; ++i) {
|
||||
if (y >= rows.size())
|
||||
@@ -3892,37 +3889,11 @@ cmd_delete_word_next(CommandContext &ctx)
|
||||
continue;
|
||||
}
|
||||
}
|
||||
// Now delete from (start_x, start_y) to (x, y)
|
||||
std::string deleted;
|
||||
if (start_y == y) {
|
||||
// same line
|
||||
if (start_x < x) {
|
||||
deleted = rows[y].substr(start_x, x - start_x);
|
||||
rows[y].erase(start_x, x - start_x);
|
||||
x = start_x;
|
||||
}
|
||||
} else {
|
||||
// spans multiple lines
|
||||
// First, collect text from start_x to end of line start_y
|
||||
deleted = rows[start_y].substr(start_x);
|
||||
rows[start_y].erase(start_x);
|
||||
// Then collect complete lines between start_y and y
|
||||
for (std::size_t ly = start_y + 1; ly < y; ++ly) {
|
||||
deleted += "\n";
|
||||
deleted += static_cast<std::string>(rows[ly]);
|
||||
}
|
||||
// Finally, collect from beginning of y to x
|
||||
if (y < rows.size()) {
|
||||
deleted += "\n";
|
||||
deleted += rows[y].substr(0, x);
|
||||
rows[start_y] += rows[y].substr(x);
|
||||
// Remove lines from start_y+1 to y inclusive
|
||||
rows.erase(rows.begin() + static_cast<std::ptrdiff_t>(start_y + 1),
|
||||
rows.begin() + static_cast<std::ptrdiff_t>(y + 1));
|
||||
}
|
||||
y = start_y;
|
||||
x = start_x;
|
||||
}
|
||||
// Now delete from (start_x, start_y) to (x, y) using PieceTable
|
||||
std::string deleted = extract_region_text(*buf, start_x, start_y, x, y);
|
||||
delete_region(*buf, start_x, start_y, x, y);
|
||||
y = start_y;
|
||||
x = start_x;
|
||||
killed_total += deleted;
|
||||
}
|
||||
buf->SetCursor(x, y);
|
||||
@@ -3954,9 +3925,8 @@ cmd_indent_region(CommandContext &ctx)
|
||||
ctx.editor.SetStatus("No region to indent");
|
||||
return false;
|
||||
}
|
||||
auto &rows = buf->Rows();
|
||||
for (std::size_t y = sy; y <= ey && y < rows.size(); ++y) {
|
||||
rows[y].insert(0, "\t");
|
||||
for (std::size_t y = sy; y <= ey && y < buf->Rows().size(); ++y) {
|
||||
buf->insert_text(static_cast<int>(y), 0, std::string_view("\t"));
|
||||
}
|
||||
buf->SetDirty(true);
|
||||
buf->ClearMark();
|
||||
@@ -3980,19 +3950,21 @@ cmd_unindent_region(CommandContext &ctx)
|
||||
ctx.editor.SetStatus("No region to unindent");
|
||||
return false;
|
||||
}
|
||||
auto &rows = buf->Rows();
|
||||
for (std::size_t y = sy; y <= ey && y < rows.size(); ++y) {
|
||||
auto &line = rows[y];
|
||||
for (std::size_t y = sy; y <= ey && y < buf->Rows().size(); ++y) {
|
||||
const auto &rows_view = buf->Rows();
|
||||
if (y >= rows_view.size())
|
||||
break;
|
||||
const std::string line = static_cast<std::string>(rows_view[y]);
|
||||
if (!line.empty()) {
|
||||
if (line[0] == '\t') {
|
||||
line.erase(0, 1);
|
||||
buf->delete_text(static_cast<int>(y), 0, 1);
|
||||
} else if (line[0] == ' ') {
|
||||
std::size_t spaces = 0;
|
||||
while (spaces < line.size() && spaces < 8 && line[spaces] == ' ') {
|
||||
++spaces;
|
||||
}
|
||||
if (spaces > 0)
|
||||
line.erase(0, spaces);
|
||||
buf->delete_text(static_cast<int>(y), 0, spaces);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4125,8 +4097,8 @@ cmd_reflow_paragraph(CommandContext &ctx)
|
||||
line.push_back(' ');
|
||||
++cur_len;
|
||||
}
|
||||
line += wrd;
|
||||
cur_len += wrd.size();
|
||||
line += wrd;
|
||||
cur_len += wrd.size();
|
||||
first_word_on_line = false;
|
||||
}
|
||||
if (!line.empty())
|
||||
@@ -4230,10 +4202,18 @@ cmd_reflow_paragraph(CommandContext &ctx)
|
||||
if (new_lines.empty())
|
||||
new_lines.push_back("");
|
||||
|
||||
rows.erase(rows.begin() + static_cast<std::ptrdiff_t>(para_start),
|
||||
rows.begin() + static_cast<std::ptrdiff_t>(para_end + 1));
|
||||
rows.insert(rows.begin() + static_cast<std::ptrdiff_t>(para_start),
|
||||
new_lines.begin(), new_lines.end());
|
||||
// Replace paragraph lines via PieceTable-backed operations
|
||||
for (std::size_t i = para_end; i + 1 > para_start; --i) {
|
||||
buf->delete_row(static_cast<int>(i));
|
||||
if (i == 0)
|
||||
break; // prevent wrap on size_t
|
||||
}
|
||||
// Insert new lines starting at para_start
|
||||
std::size_t insert_y = para_start;
|
||||
for (const auto &ln: new_lines) {
|
||||
buf->insert_row(static_cast<int>(insert_y), std::string_view(ln));
|
||||
insert_y += 1;
|
||||
}
|
||||
|
||||
// Place cursor at the end of the paragraph
|
||||
std::size_t new_last_y = para_start + (new_lines.empty() ? 0 : new_lines.size() - 1);
|
||||
@@ -4251,6 +4231,9 @@ cmd_reload_buffer(CommandContext &ctx)
|
||||
Buffer *buf = ctx.editor.CurrentBuffer();
|
||||
if (!buf)
|
||||
return false;
|
||||
// Remember the current cursor position so we can attempt to restore it
|
||||
const std::size_t old_x = buf->Curx();
|
||||
const std::size_t old_y = buf->Cury();
|
||||
const std::string &filename = buf->Filename();
|
||||
if (filename.empty()) {
|
||||
ctx.editor.SetStatus("Cannot reload unnamed buffer");
|
||||
@@ -4261,6 +4244,19 @@ cmd_reload_buffer(CommandContext &ctx)
|
||||
ctx.editor.SetStatus(std::string("Reload failed: ") + err);
|
||||
return false;
|
||||
}
|
||||
// Try to restore the cursor to its previous position if still valid; otherwise clamp
|
||||
{
|
||||
auto &rows = buf->Rows();
|
||||
const std::size_t nrows = rows.size();
|
||||
if (nrows == 0) {
|
||||
buf->SetCursor(0, 0);
|
||||
} else {
|
||||
const std::size_t new_y = old_y < nrows ? old_y : (nrows - 1);
|
||||
const std::size_t line_len = rows[new_y].size();
|
||||
const std::size_t new_x = old_x < line_len ? old_x : line_len;
|
||||
buf->SetCursor(new_x, new_y);
|
||||
}
|
||||
}
|
||||
ctx.editor.SetStatus(std::string("Reloaded ") + filename);
|
||||
ensure_cursor_visible(ctx.editor, *buf);
|
||||
return true;
|
||||
@@ -4378,6 +4374,7 @@ InstallDefaultCommands()
|
||||
CommandId::BufferSwitchStart, "buffer-switch-start", "Begin buffer switch prompt",
|
||||
cmd_buffer_switch_start, false, false
|
||||
});
|
||||
CommandRegistry::Register({CommandId::BufferNew, "buffer-new", "Open new empty buffer", cmd_buffer_new});
|
||||
CommandRegistry::Register({CommandId::BufferNext, "buffer-next", "Switch to next buffer", cmd_buffer_next});
|
||||
CommandRegistry::Register({CommandId::BufferPrev, "buffer-prev", "Switch to previous buffer", cmd_buffer_prev});
|
||||
CommandRegistry::Register({
|
||||
@@ -4569,4 +4566,4 @@ Execute(Editor &ed, const std::string &name, const std::string &arg, int count)
|
||||
return false;
|
||||
CommandContext ctx{ed, arg, count};
|
||||
return cmd->handler ? cmd->handler(ctx) : false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,6 +31,7 @@ enum class CommandId {
|
||||
VisualFontPickerToggle,
|
||||
// Buffers
|
||||
BufferSwitchStart, // begin buffer switch prompt
|
||||
BufferNew, // create a new empty, unnamed buffer (C-k i)
|
||||
BufferClose,
|
||||
BufferNext,
|
||||
BufferPrev,
|
||||
|
||||
14
Editor.cc
14
Editor.cc
@@ -197,9 +197,11 @@ Editor::OpenFile(const std::string &path, std::string &err)
|
||||
eng->InvalidateFrom(0);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
// Defensive: ensure any active prompt is closed after a successful open
|
||||
CancelPrompt();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
Buffer b;
|
||||
if (!b.OpenFromFile(path, err)) {
|
||||
@@ -237,8 +239,10 @@ Editor::OpenFile(const std::string &path, std::string &err)
|
||||
}
|
||||
// Add as a new buffer and switch to it
|
||||
std::size_t idx = AddBuffer(std::move(b));
|
||||
SwitchTo(idx);
|
||||
return true;
|
||||
SwitchTo(idx);
|
||||
// Defensive: ensure any active prompt is closed after a successful open
|
||||
CancelPrompt();
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -31,6 +31,7 @@ HelpText::Text()
|
||||
" C-k c Close current buffer\n"
|
||||
" C-k d Kill to end of line\n"
|
||||
" C-k e Open file (prompt)\n"
|
||||
" C-k i New empty buffer\n"
|
||||
" C-k f Flush kill ring\n"
|
||||
" C-k g Jump to line\n"
|
||||
" C-k h Show this help\n"
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
#include "GUITheme.h"
|
||||
#include "fonts/Font.h" // embedded default font (DefaultFont)
|
||||
#include "fonts/FontRegistry.h"
|
||||
#include "fonts/IosevkaExtended.h"
|
||||
#include "syntax/HighlighterRegistry.h"
|
||||
#include "syntax/NullHighlighter.h"
|
||||
|
||||
@@ -261,11 +262,11 @@ GUIFrontend::Step(Editor &ed, bool &running)
|
||||
|
||||
// Update editor logical rows/cols using current ImGui metrics and display size
|
||||
{
|
||||
ImGuiIO &io = ImGui::GetIO();
|
||||
float line_h = ImGui::GetTextLineHeightWithSpacing();
|
||||
float ch_w = ImGui::CalcTextSize("M").x;
|
||||
if (line_h <= 0.0f)
|
||||
line_h = 16.0f;
|
||||
ImGuiIO &io = ImGui::GetIO();
|
||||
float row_h = ImGui::GetTextLineHeightWithSpacing();
|
||||
float ch_w = ImGui::CalcTextSize("M").x;
|
||||
if (row_h <= 0.0f)
|
||||
row_h = 16.0f;
|
||||
if (ch_w <= 0.0f)
|
||||
ch_w = 8.0f;
|
||||
// Prefer ImGui IO display size; fall back to cached SDL window size
|
||||
@@ -273,20 +274,20 @@ GUIFrontend::Step(Editor &ed, bool &running)
|
||||
float disp_h = io.DisplaySize.y > 0 ? io.DisplaySize.y : static_cast<float>(height_);
|
||||
|
||||
// Account for the GUI window padding and the status bar height used in ImGuiRenderer.
|
||||
// ImGuiRenderer pushes WindowPadding = (6,6) every frame, so use the same constants here
|
||||
// to avoid mismatches that would cause premature scrolling.
|
||||
const float pad_x = 6.0f;
|
||||
const float pad_y = 6.0f;
|
||||
// Status bar reserves one frame height (with spacing) inside the window
|
||||
float status_h = ImGui::GetFrameHeightWithSpacing();
|
||||
|
||||
float avail_w = std::max(0.0f, disp_w - 2.0f * pad_x);
|
||||
float avail_h = std::max(0.0f, disp_h - 2.0f * pad_y - status_h);
|
||||
// Use the same logic as ImGuiRenderer for available height and status bar reservation.
|
||||
float wanted_bar_h = ImGui::GetFrameHeight();
|
||||
float total_avail_h = std::max(0.0f, disp_h - 2.0f * pad_y);
|
||||
float actual_avail_h = std::floor((total_avail_h - wanted_bar_h) / row_h) * row_h;
|
||||
|
||||
// Visible content rows inside the scroll child
|
||||
auto content_rows = static_cast<std::size_t>(std::floor(avail_h / line_h));
|
||||
auto content_rows = static_cast<std::size_t>(std::max(0.0f, std::floor(actual_avail_h / row_h)));
|
||||
// Editor::Rows includes the status line; add 1 back for it.
|
||||
std::size_t rows = std::max<std::size_t>(1, content_rows + 1);
|
||||
std::size_t rows = content_rows + 1;
|
||||
|
||||
float avail_w = std::max(0.0f, disp_w - 2.0f * pad_x);
|
||||
std::size_t cols = static_cast<std::size_t>(std::max(1.0f, std::floor(avail_w / ch_w)));
|
||||
|
||||
// Only update if changed to avoid churn
|
||||
@@ -357,14 +358,32 @@ GUIFrontend::LoadGuiFont_(const char * /*path*/, const float size_px)
|
||||
{
|
||||
const ImGuiIO &io = ImGui::GetIO();
|
||||
io.Fonts->Clear();
|
||||
const ImFont *font = io.Fonts->AddFontFromMemoryCompressedTTF(
|
||||
|
||||
ImFontConfig config;
|
||||
config.MergeMode = false;
|
||||
|
||||
// Load Basic Latin + Latin Supplement
|
||||
io.Fonts->AddFontFromMemoryCompressedTTF(
|
||||
kte::Fonts::DefaultFontData,
|
||||
kte::Fonts::DefaultFontSize,
|
||||
size_px);
|
||||
if (!font) {
|
||||
font = io.Fonts->AddFontDefault();
|
||||
}
|
||||
(void) font;
|
||||
size_px,
|
||||
&config,
|
||||
io.Fonts->GetGlyphRangesDefault());
|
||||
|
||||
// Merge Greek and Mathematical symbols from IosevkaExtended
|
||||
config.MergeMode = true;
|
||||
static const ImWchar extended_ranges[] = {
|
||||
0x0370, 0x03FF, // Greek and Coptic
|
||||
0x2200, 0x22FF, // Mathematical Operators
|
||||
0,
|
||||
};
|
||||
io.Fonts->AddFontFromMemoryCompressedTTF(
|
||||
kte::Fonts::IosevkaExtended::DefaultFontRegularCompressedData,
|
||||
kte::Fonts::IosevkaExtended::DefaultFontRegularCompressedSize,
|
||||
size_px,
|
||||
&config,
|
||||
extended_ranges);
|
||||
|
||||
io.Fonts->Build();
|
||||
return true;
|
||||
}
|
||||
@@ -158,16 +158,17 @@ map_key(const SDL_Keycode key,
|
||||
ascii_key = static_cast<int>(key);
|
||||
}
|
||||
bool ctrl2 = (mod & KMOD_CTRL) != 0;
|
||||
// If user typed a literal 'C' (or '^') as a control qualifier, keep k-prefix active
|
||||
if (ascii_key == 'C' || ascii_key == 'c' || ascii_key == '^') {
|
||||
k_ctrl_pending = true;
|
||||
// Keep waiting for the next suffix; show status and suppress ensuing TEXTINPUT
|
||||
if (ed)
|
||||
ed->SetStatus("C-k C _");
|
||||
suppress_textinput_once = true;
|
||||
out.hasCommand = false;
|
||||
return true;
|
||||
}
|
||||
// If user typed a literal 'C' (uppercase) or '^' as a control qualifier, keep k-prefix active
|
||||
// Do NOT treat lowercase 'c' as a qualifier; 'c' is a valid k-command (BufferClose).
|
||||
if (ascii_key == 'C' || ascii_key == '^') {
|
||||
k_ctrl_pending = true;
|
||||
// Keep waiting for the next suffix; show status and suppress ensuing TEXTINPUT
|
||||
if (ed)
|
||||
ed->SetStatus("C-k C _");
|
||||
suppress_textinput_once = true;
|
||||
out.hasCommand = false;
|
||||
return true;
|
||||
}
|
||||
// Otherwise, consume the k-prefix now for the actual suffix
|
||||
k_prefix = false;
|
||||
if (ascii_key != 0) {
|
||||
@@ -472,16 +473,16 @@ ImGuiInputHandler::ProcessSDLEvent(const SDL_Event &e)
|
||||
ascii_key = static_cast<int>(c0);
|
||||
}
|
||||
if (ascii_key != 0) {
|
||||
// Qualifier via TEXTINPUT: 'C' or '^'
|
||||
if (ascii_key == 'C' || ascii_key == 'c' || ascii_key == '^') {
|
||||
k_ctrl_pending_ = true;
|
||||
if (ed_)
|
||||
ed_->SetStatus("C-k C _");
|
||||
// Keep k-prefix active; do not emit a command
|
||||
k_prefix_ = true;
|
||||
produced = true;
|
||||
break;
|
||||
}
|
||||
// Qualifier via TEXTINPUT: uppercase 'C' or '^' only
|
||||
if (ascii_key == 'C' || ascii_key == '^') {
|
||||
k_ctrl_pending_ = true;
|
||||
if (ed_)
|
||||
ed_->SetStatus("C-k C _");
|
||||
// Keep k-prefix active; do not emit a command
|
||||
k_prefix_ = true;
|
||||
produced = true;
|
||||
break;
|
||||
}
|
||||
// Map via k-prefix table; do not pass Ctrl for TEXTINPUT case
|
||||
CommandId id;
|
||||
bool pass_ctrl = k_ctrl_pending_;
|
||||
|
||||
233
ImGuiRenderer.cc
233
ImGuiRenderer.cc
@@ -94,8 +94,17 @@ ImGuiRenderer::Draw(Editor &ed)
|
||||
ImGui::SetNextWindowScroll(ImVec2(target_x, target_y));
|
||||
}
|
||||
|
||||
// Reserve space for status bar at bottom
|
||||
ImGui::BeginChild("scroll", ImVec2(0, -ImGui::GetFrameHeightWithSpacing()), false,
|
||||
// Reserve space for status bar at bottom.
|
||||
// We calculate a height that is an exact multiple of the line height
|
||||
// to avoid partial lines and "scroll past end" jitter.
|
||||
float total_avail_h = ImGui::GetContentRegionAvail().y;
|
||||
float wanted_bar_h = ImGui::GetFrameHeight();
|
||||
float child_h_plan = std::max(0.0f, std::floor((total_avail_h - wanted_bar_h) / row_h) * row_h);
|
||||
float real_bar_h = total_avail_h - child_h_plan;
|
||||
|
||||
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));
|
||||
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0));
|
||||
ImGui::BeginChild("scroll", ImVec2(0, child_h_plan), false,
|
||||
ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_NoScrollWithMouse);
|
||||
|
||||
// Get child window position and scroll for click handling
|
||||
@@ -138,90 +147,6 @@ ImGuiRenderer::Draw(Editor &ed)
|
||||
}
|
||||
prev_buf_rowoffs = buf_rowoffs;
|
||||
prev_buf_coloffs = buf_coloffs;
|
||||
|
||||
// Synchronize cursor and scrolling.
|
||||
// Ensure the cursor is visible, but avoid aggressive centering so that
|
||||
// the same lines remain visible until the cursor actually goes off-screen.
|
||||
{
|
||||
// Compute visible row range using the child window height
|
||||
float child_h = ImGui::GetWindowHeight();
|
||||
long first_row = static_cast<long>(scroll_y / row_h);
|
||||
long vis_rows = static_cast<long>(child_h / row_h);
|
||||
if (vis_rows < 1)
|
||||
vis_rows = 1;
|
||||
long last_row = first_row + vis_rows - 1;
|
||||
|
||||
long cyr = static_cast<long>(cy);
|
||||
if (cyr < first_row) {
|
||||
// Scroll just enough to bring the cursor line to the top
|
||||
float target = static_cast<float>(cyr) * row_h;
|
||||
if (target < 0.f)
|
||||
target = 0.f;
|
||||
float max_y = ImGui::GetScrollMaxY();
|
||||
if (max_y >= 0.f && target > max_y)
|
||||
target = max_y;
|
||||
ImGui::SetScrollY(target);
|
||||
scroll_y = ImGui::GetScrollY();
|
||||
first_row = static_cast<long>(scroll_y / row_h);
|
||||
last_row = first_row + vis_rows - 1;
|
||||
} else if (cyr > last_row) {
|
||||
// Scroll just enough to bring the cursor line to the bottom
|
||||
long new_first = cyr - vis_rows + 1;
|
||||
if (new_first < 0)
|
||||
new_first = 0;
|
||||
float target = static_cast<float>(new_first) * row_h;
|
||||
float max_y = ImGui::GetScrollMaxY();
|
||||
if (target < 0.f)
|
||||
target = 0.f;
|
||||
if (max_y >= 0.f && target > max_y)
|
||||
target = max_y;
|
||||
ImGui::SetScrollY(target);
|
||||
scroll_y = ImGui::GetScrollY();
|
||||
first_row = static_cast<long>(scroll_y / row_h);
|
||||
last_row = first_row + vis_rows - 1;
|
||||
}
|
||||
|
||||
// Horizontal scroll: ensure cursor column is visible
|
||||
float child_w = ImGui::GetWindowWidth();
|
||||
long vis_cols = static_cast<long>(child_w / space_w);
|
||||
if (vis_cols < 1)
|
||||
vis_cols = 1;
|
||||
long first_col = static_cast<long>(scroll_x / space_w);
|
||||
long last_col = first_col + vis_cols - 1;
|
||||
|
||||
// Compute cursor's rendered X position (accounting for tabs)
|
||||
std::size_t cursor_rx = 0;
|
||||
if (cy < lines.size()) {
|
||||
std::string cur_line = static_cast<std::string>(lines[cy]);
|
||||
const std::size_t tabw = 8;
|
||||
for (std::size_t i = 0; i < cx && i < cur_line.size(); ++i) {
|
||||
if (cur_line[i] == '\t') {
|
||||
cursor_rx += tabw - (cursor_rx % tabw);
|
||||
} else {
|
||||
cursor_rx += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
long cxr = static_cast<long>(cursor_rx);
|
||||
if (cxr < first_col || cxr > last_col) {
|
||||
float target_x = static_cast<float>(cxr) * space_w;
|
||||
// Center horizontally if possible
|
||||
target_x -= (child_w / 2.0f);
|
||||
if (target_x < 0.f)
|
||||
target_x = 0.f;
|
||||
float max_x = ImGui::GetScrollMaxX();
|
||||
if (max_x >= 0.f && target_x > max_x)
|
||||
target_x = max_x;
|
||||
ImGui::SetScrollX(target_x);
|
||||
scroll_x = ImGui::GetScrollX();
|
||||
}
|
||||
// Phase 3: prefetch visible viewport highlights and warm around in background
|
||||
if (buf->SyntaxEnabled() && buf->Highlighter() && buf->Highlighter()->HasHighlighter()) {
|
||||
int fr = static_cast<int>(std::max(0L, first_row));
|
||||
int rc = static_cast<int>(std::max(1L, vis_rows));
|
||||
buf->Highlighter()->PrefetchViewport(*buf, fr, rc, buf->Version());
|
||||
}
|
||||
}
|
||||
// Cache current horizontal offset in rendered columns for click handling
|
||||
const std::size_t coloffs_now = buf->Coloffs();
|
||||
|
||||
@@ -489,23 +414,98 @@ ImGuiRenderer::Draw(Editor &ed)
|
||||
ImGui::GetWindowDrawList()->AddRectFilled(p0, p1, col);
|
||||
}
|
||||
}
|
||||
// Synchronize cursor and scrolling after rendering all lines so content size is known.
|
||||
{
|
||||
float child_h_actual = ImGui::GetWindowHeight();
|
||||
float child_w_actual = ImGui::GetWindowWidth();
|
||||
float scroll_y_now = ImGui::GetScrollY();
|
||||
float scroll_x_now = ImGui::GetScrollX();
|
||||
|
||||
long first_row = static_cast<long>(scroll_y_now / row_h);
|
||||
long vis_rows = static_cast<long>(std::round(child_h_actual / row_h));
|
||||
if (vis_rows < 1)
|
||||
vis_rows = 1;
|
||||
long last_row = first_row + vis_rows - 1;
|
||||
|
||||
long cyr = static_cast<long>(cy);
|
||||
if (cyr < first_row) {
|
||||
float target = static_cast<float>(cyr) * row_h;
|
||||
if (target < 0.f)
|
||||
target = 0.f;
|
||||
float max_y = ImGui::GetScrollMaxY();
|
||||
if (max_y >= 0.f && target > max_y)
|
||||
target = max_y;
|
||||
ImGui::SetScrollY(target);
|
||||
first_row = static_cast<long>(target / row_h);
|
||||
last_row = first_row + vis_rows - 1;
|
||||
} else if (cyr > last_row) {
|
||||
long new_first = cyr - vis_rows + 1;
|
||||
if (new_first < 0)
|
||||
new_first = 0;
|
||||
float target = static_cast<float>(new_first) * row_h;
|
||||
float max_y = ImGui::GetScrollMaxY();
|
||||
if (target < 0.f)
|
||||
target = 0.f;
|
||||
if (max_y >= 0.f && target > max_y)
|
||||
target = max_y;
|
||||
ImGui::SetScrollY(target);
|
||||
first_row = static_cast<long>(target / row_h);
|
||||
last_row = first_row + vis_rows - 1;
|
||||
}
|
||||
|
||||
// Horizontal scroll: ensure cursor column is visible
|
||||
long vis_cols = static_cast<long>(std::round(child_w_actual / space_w));
|
||||
if (vis_cols < 1)
|
||||
vis_cols = 1;
|
||||
long first_col = static_cast<long>(scroll_x_now / space_w);
|
||||
long last_col = first_col + vis_cols - 1;
|
||||
|
||||
std::size_t cursor_rx = 0;
|
||||
if (cy < lines.size()) {
|
||||
std::string cur_line = static_cast<std::string>(lines[cy]);
|
||||
const std::size_t tabw = 8;
|
||||
for (std::size_t i = 0; i < cx && i < cur_line.size(); ++i) {
|
||||
if (cur_line[i] == '\t') {
|
||||
cursor_rx += tabw - (cursor_rx % tabw);
|
||||
} else {
|
||||
cursor_rx += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
long cxr = static_cast<long>(cursor_rx);
|
||||
if (cxr < first_col || cxr > last_col) {
|
||||
float target_x = static_cast<float>(cxr) * space_w;
|
||||
target_x -= (child_w_actual / 2.0f);
|
||||
if (target_x < 0.f)
|
||||
target_x = 0.f;
|
||||
float max_x = ImGui::GetScrollMaxX();
|
||||
if (max_x >= 0.f && target_x > max_x)
|
||||
target_x = max_x;
|
||||
ImGui::SetScrollX(target_x);
|
||||
}
|
||||
|
||||
if (buf->SyntaxEnabled() && buf->Highlighter() && buf->Highlighter()->HasHighlighter()) {
|
||||
int fr = static_cast<int>(std::max(0L, first_row));
|
||||
int rc = static_cast<int>(std::max(1L, vis_rows));
|
||||
buf->Highlighter()->PrefetchViewport(*buf, fr, rc, buf->Version());
|
||||
}
|
||||
}
|
||||
ImGui::EndChild();
|
||||
ImGui::PopStyleVar(2); // WindowPadding, ItemSpacing
|
||||
|
||||
// Status bar spanning full width
|
||||
ImGui::Separator();
|
||||
|
||||
// Compute full content width and draw a filled background rectangle
|
||||
// Status bar area starting right after the scroll child
|
||||
ImVec2 win_pos = ImGui::GetWindowPos();
|
||||
ImVec2 cr_min = ImGui::GetWindowContentRegionMin();
|
||||
ImVec2 cr_max = ImGui::GetWindowContentRegionMax();
|
||||
float x0 = win_pos.x + cr_min.x;
|
||||
float x1 = win_pos.x + cr_max.x;
|
||||
ImVec2 cursor = ImGui::GetCursorScreenPos();
|
||||
float bar_h = ImGui::GetFrameHeight();
|
||||
ImVec2 p0(x0, cursor.y);
|
||||
ImVec2 p1(x1, cursor.y + bar_h);
|
||||
ImVec2 win_sz = ImGui::GetWindowSize();
|
||||
float x0 = win_pos.x;
|
||||
float x1 = win_pos.x + win_sz.x;
|
||||
float y0 = ImGui::GetCursorScreenPos().y;
|
||||
float bar_h = real_bar_h;
|
||||
|
||||
ImVec2 p0(x0, y0);
|
||||
ImVec2 p1(x1, y0 + bar_h);
|
||||
ImU32 bg_col = ImGui::GetColorU32(ImGuiCol_HeaderActive);
|
||||
ImGui::GetWindowDrawList()->AddRectFilled(p0, p1, bg_col);
|
||||
|
||||
// If a prompt is active, replace the entire status bar with the prompt text
|
||||
if (ed.PromptActive()) {
|
||||
std::string label = ed.PromptLabel();
|
||||
@@ -560,7 +560,7 @@ ImGuiRenderer::Draw(Editor &ed)
|
||||
(size_t) std::max<size_t>(
|
||||
1, (size_t) (tail.size() / 4)))
|
||||
: 1;
|
||||
start += skip;
|
||||
start += skip;
|
||||
std::string candidate = tail.substr(start);
|
||||
ImVec2 cand_sz = ImGui::CalcTextSize(candidate.c_str());
|
||||
if (cand_sz.x <= avail_px) {
|
||||
@@ -591,11 +591,9 @@ ImGuiRenderer::Draw(Editor &ed)
|
||||
|
||||
ImVec2 msg_sz = ImGui::CalcTextSize(final_msg.c_str());
|
||||
ImGui::PushClipRect(ImVec2(p0.x, p0.y), ImVec2(p1.x, p1.y), true);
|
||||
ImGui::SetCursorScreenPos(ImVec2(left_x, p0.y + (bar_h - msg_sz.y) * 0.5f));
|
||||
ImGui::SetCursorScreenPos(ImVec2(left_x, y0 + (bar_h - msg_sz.y) * 0.5f));
|
||||
ImGui::TextUnformatted(final_msg.c_str());
|
||||
ImGui::PopClipRect();
|
||||
// Advance cursor to after the bar to keep layout consistent
|
||||
ImGui::Dummy(ImVec2(x1 - x0, bar_h));
|
||||
} else {
|
||||
// Build left text
|
||||
std::string left;
|
||||
@@ -618,11 +616,11 @@ ImGuiRenderer::Draw(Editor &ed)
|
||||
std::size_t total = ed.BufferCount();
|
||||
if (total > 0) {
|
||||
std::size_t idx1 = ed.CurrentBufferIndex() + 1; // 1-based for display
|
||||
left += "[";
|
||||
left += std::to_string(static_cast<unsigned long long>(idx1));
|
||||
left += "/";
|
||||
left += std::to_string(static_cast<unsigned long long>(total));
|
||||
left += "] ";
|
||||
left += "[";
|
||||
left += std::to_string(static_cast<unsigned long long>(idx1));
|
||||
left += "/";
|
||||
left += std::to_string(static_cast<unsigned long long>(total));
|
||||
left += "] ";
|
||||
}
|
||||
}
|
||||
left += fname;
|
||||
@@ -631,9 +629,9 @@ ImGuiRenderer::Draw(Editor &ed)
|
||||
// Append total line count as "<n>L"
|
||||
{
|
||||
unsigned long lcount = static_cast<unsigned long>(buf->Rows().size());
|
||||
left += " ";
|
||||
left += std::to_string(lcount);
|
||||
left += "L";
|
||||
left += " ";
|
||||
left += std::to_string(lcount);
|
||||
left += "L";
|
||||
}
|
||||
|
||||
// Build right text (cursor/mark)
|
||||
@@ -671,20 +669,21 @@ ImGuiRenderer::Draw(Editor &ed)
|
||||
float max_left = std::max(0.0f, right_x - left_x - pad);
|
||||
if (max_left < left_sz.x && max_left > 10.0f) {
|
||||
// Render a clipped left using a child region
|
||||
ImGui::SetCursorScreenPos(ImVec2(left_x, p0.y + (bar_h - left_sz.y) * 0.5f));
|
||||
ImGui::PushClipRect(ImVec2(left_x, p0.y), ImVec2(right_x - pad, p1.y), true);
|
||||
ImGui::SetCursorScreenPos(ImVec2(left_x, y0 + (bar_h - left_sz.y) * 0.5f));
|
||||
ImGui::PushClipRect(ImVec2(left_x, y0), ImVec2(right_x - pad, y0 + bar_h),
|
||||
true);
|
||||
ImGui::TextUnformatted(left.c_str());
|
||||
ImGui::PopClipRect();
|
||||
}
|
||||
} else {
|
||||
// Draw left normally
|
||||
ImGui::SetCursorScreenPos(ImVec2(left_x, p0.y + (bar_h - left_sz.y) * 0.5f));
|
||||
ImGui::SetCursorScreenPos(ImVec2(left_x, y0 + (bar_h - left_sz.y) * 0.5f));
|
||||
ImGui::TextUnformatted(left.c_str());
|
||||
}
|
||||
|
||||
// Draw right
|
||||
ImGui::SetCursorScreenPos(ImVec2(std::max(right_x, left_x),
|
||||
p0.y + (bar_h - right_sz.y) * 0.5f));
|
||||
y0 + (bar_h - right_sz.y) * 0.5f));
|
||||
ImGui::TextUnformatted(right.c_str());
|
||||
|
||||
// Draw middle message centered in remaining space
|
||||
@@ -696,14 +695,12 @@ ImGuiRenderer::Draw(Editor &ed)
|
||||
ImVec2 msg_sz = ImGui::CalcTextSize(msg.c_str());
|
||||
float msg_x = mid_left + std::max(0.0f, (mid_w - msg_sz.x) * 0.5f);
|
||||
// Clip to middle region
|
||||
ImGui::PushClipRect(ImVec2(mid_left, p0.y), ImVec2(mid_right, p1.y), true);
|
||||
ImGui::SetCursorScreenPos(ImVec2(msg_x, p0.y + (bar_h - msg_sz.y) * 0.5f));
|
||||
ImGui::PushClipRect(ImVec2(mid_left, y0), ImVec2(mid_right, y0 + bar_h), true);
|
||||
ImGui::SetCursorScreenPos(ImVec2(msg_x, y0 + (bar_h - msg_sz.y) * 0.5f));
|
||||
ImGui::TextUnformatted(msg.c_str());
|
||||
ImGui::PopClipRect();
|
||||
}
|
||||
}
|
||||
// Advance cursor to after the bar to keep layout consistent
|
||||
ImGui::Dummy(ImVec2(x1 - x0, bar_h));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -42,6 +42,9 @@ KLookupKCommand(const int ascii_key, const bool ctrl, CommandId &out) -> bool
|
||||
case 'a':
|
||||
out = CommandId::MarkAllAndJumpEnd;
|
||||
return true;
|
||||
case 'i':
|
||||
out = CommandId::BufferNew; // C-k i new empty buffer
|
||||
return true;
|
||||
case 'k':
|
||||
out = CommandId::CenterOnCursor; // C-k k center current line
|
||||
return true;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#include <algorithm>
|
||||
#include <utility>
|
||||
#include <limits>
|
||||
#include <ostream>
|
||||
|
||||
#include "PieceTable.h"
|
||||
|
||||
@@ -757,3 +758,17 @@ PieceTable::Find(const std::string &needle, std::size_t start) const
|
||||
find_cache_.result = pos;
|
||||
return pos;
|
||||
}
|
||||
|
||||
|
||||
void
|
||||
PieceTable::WriteToStream(std::ostream &out) const
|
||||
{
|
||||
// Stream the content piece-by-piece without forcing full materialization
|
||||
for (const auto &p : pieces_) {
|
||||
if (p.len == 0)
|
||||
continue;
|
||||
const std::string &src = (p.src == Source::Original) ? original_ : add_;
|
||||
const char *base = src.data() + static_cast<std::ptrdiff_t>(p.start);
|
||||
out.write(base, static_cast<std::streamsize>(p.len));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <ostream>
|
||||
#include <vector>
|
||||
#include <limits>
|
||||
|
||||
@@ -100,6 +101,9 @@ public:
|
||||
// Simple search utility; returns byte offset or npos
|
||||
[[nodiscard]] std::size_t Find(const std::string &needle, std::size_t start = 0) const;
|
||||
|
||||
// Stream out content without materializing the entire buffer
|
||||
void WriteToStream(std::ostream &out) const;
|
||||
|
||||
// Heuristic configuration
|
||||
void SetConsolidationParams(std::size_t piece_limit,
|
||||
std::size_t small_piece_threshold,
|
||||
|
||||
@@ -142,13 +142,13 @@ protected:
|
||||
p.save();
|
||||
p.setClipRect(viewport);
|
||||
|
||||
// Iterate visible lines
|
||||
for (std::size_t i = rowoffs, vis_idx = 0; i < last_row; ++i, ++vis_idx) {
|
||||
// Materialize the Buffer::Line into a std::string for
|
||||
// regex/iterator usage and general string ops.
|
||||
const std::string line = static_cast<std::string>(lines[i]);
|
||||
const int y = viewport.y() + static_cast<int>(vis_idx) * line_h;
|
||||
const int baseline = y + fm.ascent();
|
||||
// Iterate visible lines
|
||||
for (std::size_t i = rowoffs, vis_idx = 0; i < last_row; ++i, ++vis_idx) {
|
||||
// Materialize the Buffer::Line into a std::string for
|
||||
// regex/iterator usage and general string ops.
|
||||
const std::string line = static_cast<std::string>(lines[i]);
|
||||
const int y = viewport.y() + static_cast<int>(vis_idx) * line_h;
|
||||
const int baseline = y + fm.ascent();
|
||||
|
||||
// Helper: convert src col -> rx with tab expansion
|
||||
auto src_to_rx_line = [&](std::size_t src_col) -> std::size_t {
|
||||
@@ -453,11 +453,11 @@ protected:
|
||||
std::size_t total = ed_->BufferCount();
|
||||
if (total > 0) {
|
||||
std::size_t idx1 = ed_->CurrentBufferIndex() + 1; // 1-based
|
||||
left += QStringLiteral(" [");
|
||||
left += QString::number(static_cast<qlonglong>(idx1));
|
||||
left += QStringLiteral("/");
|
||||
left += QString::number(static_cast<qlonglong>(total));
|
||||
left += QStringLiteral("] ");
|
||||
left += QStringLiteral(" [");
|
||||
left += QString::number(static_cast<qlonglong>(idx1));
|
||||
left += QStringLiteral("/");
|
||||
left += QString::number(static_cast<qlonglong>(total));
|
||||
left += QStringLiteral("] ");
|
||||
} else {
|
||||
left += QStringLiteral(" ");
|
||||
}
|
||||
@@ -477,9 +477,9 @@ protected:
|
||||
|
||||
// total lines suffix " <n>L"
|
||||
unsigned long lcount = static_cast<unsigned long>(buf->Rows().size());
|
||||
left += QStringLiteral(" ");
|
||||
left += QString::number(static_cast<qlonglong>(lcount));
|
||||
left += QStringLiteral("L");
|
||||
left += QStringLiteral(" ");
|
||||
left += QString::number(static_cast<qlonglong>(lcount));
|
||||
left += QStringLiteral("L");
|
||||
}
|
||||
|
||||
// Build right segment: cursor and mark
|
||||
@@ -602,12 +602,12 @@ protected:
|
||||
int d_cols = 0;
|
||||
if (std::fabs(v_scroll_accum_) >= 1.0 && (!horiz_mode || std::fabs(v_scroll_accum_) > std::fabs(
|
||||
h_scroll_accum_))) {
|
||||
d_rows = static_cast<int>(v_scroll_accum_);
|
||||
d_rows = static_cast<int>(v_scroll_accum_);
|
||||
v_scroll_accum_ -= d_rows;
|
||||
}
|
||||
if (std::fabs(h_scroll_accum_) >= 1.0 && (horiz_mode || std::fabs(h_scroll_accum_) >= std::fabs(
|
||||
v_scroll_accum_))) {
|
||||
d_cols = static_cast<int>(h_scroll_accum_);
|
||||
d_cols = static_cast<int>(h_scroll_accum_);
|
||||
h_scroll_accum_ -= d_cols;
|
||||
}
|
||||
|
||||
|
||||
@@ -73,6 +73,7 @@ TerminalFrontend::Init(Editor &ed)
|
||||
have_old_sigint_ = true;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -120,4 +121,4 @@ TerminalFrontend::Shutdown()
|
||||
have_old_sigint_ = false;
|
||||
}
|
||||
endwin();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -178,14 +178,15 @@ map_key_to_command(const int ch,
|
||||
ctrl = true;
|
||||
ascii_key = 'a' + (ch - 1);
|
||||
}
|
||||
// If user typed literal 'C'/'c' or '^' as a qualifier, keep k-prefix and set pending
|
||||
if (ascii_key == 'C' || ascii_key == 'c' || ascii_key == '^') {
|
||||
k_ctrl_pending = true;
|
||||
if (ed)
|
||||
ed->SetStatus("C-k C _");
|
||||
out.hasCommand = false;
|
||||
return true;
|
||||
}
|
||||
// If user typed literal 'C' or '^' as a qualifier, keep k-prefix and set pending
|
||||
// Note: Do NOT treat lowercase 'c' as a qualifier, since 'c' is a valid C-k command (BufferClose).
|
||||
if (ascii_key == 'C' || ascii_key == '^') {
|
||||
k_ctrl_pending = true;
|
||||
if (ed)
|
||||
ed->SetStatus("C-k C _");
|
||||
out.hasCommand = false;
|
||||
return true;
|
||||
}
|
||||
// For actual suffix, consume the k-prefix
|
||||
k_prefix = false;
|
||||
// Do NOT lowercase here; KLookupKCommand handles case-sensitive bindings
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
#include <clocale>
|
||||
#define _XOPEN_SOURCE_EXTENDED 1
|
||||
#include <cwchar>
|
||||
#include <algorithm>
|
||||
#include <cstdio>
|
||||
#include <filesystem>
|
||||
@@ -157,35 +160,52 @@ TerminalRenderer::Draw(Editor &ed)
|
||||
// Map to simple attributes; search highlight uses A_STANDOUT which takes precedence below
|
||||
attrset(A_NORMAL);
|
||||
switch (k) {
|
||||
case kte::TokenKind::Keyword:
|
||||
case kte::TokenKind::Type:
|
||||
case kte::TokenKind::Constant:
|
||||
case kte::TokenKind::Function:
|
||||
attron(A_BOLD);
|
||||
break;
|
||||
case kte::TokenKind::Comment:
|
||||
attron(A_DIM);
|
||||
break;
|
||||
case kte::TokenKind::String:
|
||||
case kte::TokenKind::Char:
|
||||
case kte::TokenKind::Number:
|
||||
// standout a bit using A_UNDERLINE if available
|
||||
attron(A_UNDERLINE);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
case kte::TokenKind::Keyword:
|
||||
case kte::TokenKind::Type:
|
||||
case kte::TokenKind::Constant:
|
||||
case kte::TokenKind::Function:
|
||||
attron(A_BOLD);
|
||||
break;
|
||||
case kte::TokenKind::Comment:
|
||||
attron(A_DIM);
|
||||
break;
|
||||
case kte::TokenKind::String:
|
||||
case kte::TokenKind::Char:
|
||||
case kte::TokenKind::Number:
|
||||
// standout a bit using A_UNDERLINE if available
|
||||
attron(A_UNDERLINE);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
};
|
||||
while (written < cols) {
|
||||
char ch = ' ';
|
||||
bool from_src = false;
|
||||
wchar_t wch = L' ';
|
||||
int wch_len = 1;
|
||||
int disp_w = 1;
|
||||
|
||||
if (src_i < line.size()) {
|
||||
unsigned char c = static_cast<unsigned char>(line[src_i]);
|
||||
if (c == '\t') {
|
||||
// Decode UTF-8
|
||||
std::mbstate_t state = std::mbstate_t();
|
||||
size_t res = std::mbrtowc(
|
||||
&wch, &line[src_i], line.size() - src_i, &state);
|
||||
if (res == (size_t) -1 || res == (size_t) -2) {
|
||||
// Invalid or incomplete; treat as single byte
|
||||
wch = static_cast<unsigned char>(line[src_i]);
|
||||
wch_len = 1;
|
||||
} else if (res == 0) {
|
||||
wch = L'\0';
|
||||
wch_len = 1;
|
||||
} else {
|
||||
wch_len = static_cast<int>(res);
|
||||
}
|
||||
|
||||
if (wch == L'\t') {
|
||||
std::size_t next_tab = tabw - (render_col % tabw);
|
||||
if (render_col + next_tab <= coloffs) {
|
||||
render_col += next_tab;
|
||||
++src_i;
|
||||
src_i += wch_len;
|
||||
continue;
|
||||
}
|
||||
// Emit spaces for tab
|
||||
@@ -194,7 +214,7 @@ TerminalRenderer::Draw(Editor &ed)
|
||||
std::size_t to_skip = std::min<std::size_t>(
|
||||
next_tab, coloffs - render_col);
|
||||
render_col += to_skip;
|
||||
next_tab -= to_skip;
|
||||
next_tab -= to_skip;
|
||||
}
|
||||
// Now render visible spaces
|
||||
while (next_tab > 0 && written < cols) {
|
||||
@@ -233,23 +253,34 @@ TerminalRenderer::Draw(Editor &ed)
|
||||
++render_col;
|
||||
--next_tab;
|
||||
}
|
||||
++src_i;
|
||||
src_i += wch_len;
|
||||
continue;
|
||||
} else {
|
||||
// normal char
|
||||
disp_w = wcwidth(wch);
|
||||
if (disp_w < 0)
|
||||
disp_w = 1; // non-printable or similar
|
||||
|
||||
if (render_col < coloffs) {
|
||||
++render_col;
|
||||
++src_i;
|
||||
render_col += disp_w;
|
||||
src_i += wch_len;
|
||||
continue;
|
||||
}
|
||||
ch = static_cast<char>(c);
|
||||
from_src = true;
|
||||
}
|
||||
} else {
|
||||
// beyond EOL, fill spaces
|
||||
ch = ' ';
|
||||
wch = L' ';
|
||||
wch_len = 1;
|
||||
disp_w = 1;
|
||||
from_src = false;
|
||||
}
|
||||
|
||||
if (written + disp_w > cols) {
|
||||
// would overflow, just break
|
||||
break;
|
||||
}
|
||||
|
||||
bool in_hl = search_mode && from_src && is_src_in_hl(src_i);
|
||||
bool in_cur =
|
||||
has_current && li == cur_my && from_src && src_i >= cur_mx && src_i <
|
||||
@@ -273,11 +304,20 @@ TerminalRenderer::Draw(Editor &ed)
|
||||
if (!in_hl && from_src) {
|
||||
apply_token_attr(token_at(src_i));
|
||||
}
|
||||
addch(static_cast<unsigned char>(ch));
|
||||
++written;
|
||||
++render_col;
|
||||
|
||||
if (from_src) {
|
||||
cchar_t cch;
|
||||
wchar_t warr[2] = {wch, L'\0'};
|
||||
setcchar(&cch, warr, A_NORMAL, 0, nullptr);
|
||||
add_wch(&cch);
|
||||
} else {
|
||||
addch(' ');
|
||||
}
|
||||
|
||||
written += disp_w;
|
||||
render_col += disp_w;
|
||||
if (from_src)
|
||||
++src_i;
|
||||
src_i += wch_len;
|
||||
if (src_i >= line.size() && written >= cols)
|
||||
break;
|
||||
}
|
||||
@@ -297,23 +337,35 @@ TerminalRenderer::Draw(Editor &ed)
|
||||
// Place terminal cursor at logical position accounting for tabs and coloffs.
|
||||
// Recompute the rendered X using the same logic as the drawing loop to avoid
|
||||
// any drift between the command-layer computation and the terminal renderer.
|
||||
std::size_t cy = buf->Cury();
|
||||
std::size_t cx = buf->Curx();
|
||||
int cur_y = static_cast<int>(cy) - static_cast<int>(buf->Rowoffs());
|
||||
std::size_t cy = buf->Cury();
|
||||
std::size_t cx = buf->Curx();
|
||||
int cur_y = static_cast<int>(cy) - static_cast<int>(buf->Rowoffs());
|
||||
std::size_t rx_recomputed = 0;
|
||||
if (cy < lines.size()) {
|
||||
const std::string line_for_cursor = static_cast<std::string>(lines[cy]);
|
||||
std::size_t src_i_cur = 0;
|
||||
std::size_t render_col_cur = 0;
|
||||
std::size_t src_i_cur = 0;
|
||||
std::size_t render_col_cur = 0;
|
||||
while (src_i_cur < line_for_cursor.size() && src_i_cur < cx) {
|
||||
unsigned char ccur = static_cast<unsigned char>(line_for_cursor[src_i_cur]);
|
||||
if (ccur == '\t') {
|
||||
std::size_t next_tab = tabw - (render_col_cur % tabw);
|
||||
render_col_cur += next_tab;
|
||||
++src_i_cur;
|
||||
std::mbstate_t state = std::mbstate_t();
|
||||
wchar_t wch;
|
||||
size_t res = std::mbrtowc(
|
||||
&wch, &line_for_cursor[src_i_cur], line_for_cursor.size() - src_i_cur,
|
||||
&state);
|
||||
|
||||
if (res == (size_t) -1 || res == (size_t) -2) {
|
||||
render_col_cur += 1;
|
||||
src_i_cur += 1;
|
||||
} else if (res == 0) {
|
||||
src_i_cur += 1;
|
||||
} else {
|
||||
++render_col_cur;
|
||||
++src_i_cur;
|
||||
if (wch == L'\t') {
|
||||
std::size_t next_tab = tabw - (render_col_cur % tabw);
|
||||
render_col_cur += next_tab;
|
||||
} else {
|
||||
int dw = wcwidth(wch);
|
||||
render_col_cur += (dw < 0) ? 1 : dw;
|
||||
}
|
||||
src_i_cur += res;
|
||||
}
|
||||
}
|
||||
rx_recomputed = render_col_cur;
|
||||
@@ -403,9 +455,9 @@ TerminalRenderer::Draw(Editor &ed)
|
||||
{
|
||||
const char *app = "kte";
|
||||
left.reserve(256);
|
||||
left += app;
|
||||
left += " ";
|
||||
left += KTE_VERSION_STR; // already includes leading 'v'
|
||||
left += app;
|
||||
left += " ";
|
||||
left += KTE_VERSION_STR; // already includes leading 'v'
|
||||
const Buffer *b = buf;
|
||||
std::string fname;
|
||||
if (b) {
|
||||
@@ -426,11 +478,11 @@ TerminalRenderer::Draw(Editor &ed)
|
||||
std::size_t total = ed.BufferCount();
|
||||
if (total > 0) {
|
||||
std::size_t idx1 = ed.CurrentBufferIndex() + 1; // human-friendly 1-based
|
||||
left += "[";
|
||||
left += std::to_string(static_cast<unsigned long long>(idx1));
|
||||
left += "/";
|
||||
left += std::to_string(static_cast<unsigned long long>(total));
|
||||
left += "] ";
|
||||
left += "[";
|
||||
left += std::to_string(static_cast<unsigned long long>(idx1));
|
||||
left += "/";
|
||||
left += std::to_string(static_cast<unsigned long long>(total));
|
||||
left += "] ";
|
||||
}
|
||||
}
|
||||
left += fname;
|
||||
@@ -442,9 +494,9 @@ TerminalRenderer::Draw(Editor &ed)
|
||||
// Append total line count as "<n>L"
|
||||
if (b) {
|
||||
unsigned long lcount = static_cast<unsigned long>(b->Rows().size());
|
||||
left += " ";
|
||||
left += std::to_string(lcount);
|
||||
left += "L";
|
||||
left += " ";
|
||||
left += std::to_string(lcount);
|
||||
left += "L";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
78
cmake/fix_bundle.cmake
Normal file
78
cmake/fix_bundle.cmake
Normal file
@@ -0,0 +1,78 @@
|
||||
cmake_minimum_required(VERSION 3.15)
|
||||
|
||||
# Fix up a macOS .app bundle by copying non-Qt dylibs into
|
||||
# Contents/Frameworks and rewriting install names to use @rpath/@loader_path.
|
||||
#
|
||||
# Usage:
|
||||
# cmake -DAPP_BUNDLE=/path/to/kge.app -P cmake/fix_bundle.cmake
|
||||
|
||||
if (NOT APP_BUNDLE)
|
||||
message(FATAL_ERROR "APP_BUNDLE not set. Invoke with -DAPP_BUNDLE=/path/to/App.app")
|
||||
endif ()
|
||||
|
||||
get_filename_component(APP_DIR "${APP_BUNDLE}" ABSOLUTE)
|
||||
set(EXECUTABLE "${APP_DIR}/Contents/MacOS/kge")
|
||||
|
||||
if (NOT EXISTS "${EXECUTABLE}")
|
||||
message(FATAL_ERROR "Executable not found at: ${EXECUTABLE}")
|
||||
endif ()
|
||||
|
||||
include(BundleUtilities)
|
||||
|
||||
# Directories to search when resolving prerequisites. We include Homebrew so that
|
||||
# if any deps are currently resolved from there, fixup_bundle will copy them into
|
||||
# the bundle and rewrite install names to be self-contained.
|
||||
set(DIRS
|
||||
"/usr/local/lib"
|
||||
"/opt/homebrew/lib"
|
||||
"/opt/homebrew/opt"
|
||||
)
|
||||
|
||||
# Note: We pass empty plugin list so fixup_bundle scans the executable and all
|
||||
# libs it references recursively. Qt frameworks already live in the bundle after
|
||||
# macdeployqt; this step is primarily for non-Qt dylibs (glib, icu, pcre2, zstd,
|
||||
# dbus, etc.).
|
||||
# fixup_bundle often fails if copied libraries are read-only.
|
||||
# We also try to use the system install_name_tool and otool to avoid issues with Anaconda's version.
|
||||
# Note: BundleUtilities uses find_program(gp_otool "otool") internally, so we might need to set it differently.
|
||||
set(gp_otool "/usr/bin/otool")
|
||||
set(CMAKE_INSTALL_NAME_TOOL "/usr/bin/install_name_tool")
|
||||
set(CMAKE_OTOOL "/usr/bin/otool")
|
||||
set(ENV{PATH} "/usr/bin:/bin:/usr/sbin:/sbin")
|
||||
|
||||
execute_process(COMMAND chmod -R u+w "${APP_DIR}/Contents/Frameworks")
|
||||
|
||||
fixup_bundle("${APP_DIR}" "" "${DIRS}")
|
||||
|
||||
# On Apple Silicon (and modern macOS in general), modifications by fixup_bundle
|
||||
# invalidate code signatures. We must re-sign the bundle (at least ad-hoc)
|
||||
# for it to be allowed to run.
|
||||
# We sign deep, but sometimes explicit signing of components is more reliable.
|
||||
message(STATUS "Re-signing ${APP_DIR} after fixup...")
|
||||
|
||||
# 1. Sign dylibs in Frameworks
|
||||
file(GLOB_RECURSE DYLIBS "${APP_DIR}/Contents/Frameworks/*.dylib")
|
||||
foreach (DYLIB ${DYLIBS})
|
||||
message(STATUS "Signing ${DYLIB}...")
|
||||
execute_process(COMMAND /usr/bin/codesign --force --sign - "${DYLIB}")
|
||||
endforeach ()
|
||||
|
||||
# 2. Sign nested executables
|
||||
message(STATUS "Signing nested kte...")
|
||||
execute_process(COMMAND /usr/bin/codesign --force --sign - "${APP_DIR}/Contents/MacOS/kte")
|
||||
|
||||
# 3. Sign the main executable explicitly
|
||||
message(STATUS "Signing main kge...")
|
||||
execute_process(COMMAND /usr/bin/codesign --force --sign - "${APP_DIR}/Contents/MacOS/kge")
|
||||
|
||||
# 4. Sign the main bundle
|
||||
execute_process(
|
||||
COMMAND /usr/bin/codesign --force --deep --sign - "${APP_DIR}"
|
||||
RESULT_VARIABLE CODESIGN_RESULT
|
||||
)
|
||||
|
||||
if (NOT CODESIGN_RESULT EQUAL 0)
|
||||
message(FATAL_ERROR "Codesign failed with error: ${CODESIGN_RESULT}")
|
||||
endif ()
|
||||
|
||||
message(STATUS "fix_bundle.cmake completed for ${APP_DIR}")
|
||||
@@ -1,5 +1,6 @@
|
||||
{
|
||||
lib,
|
||||
pkgs ? import <nixpkgs> {},
|
||||
lib ? pkgs.lib,
|
||||
stdenv,
|
||||
cmake,
|
||||
ncurses,
|
||||
|
||||
163
docs/plans/test-plan.md
Normal file
163
docs/plans/test-plan.md
Normal file
@@ -0,0 +1,163 @@
|
||||
### Unit testing plan (headless, no interactive frontend)
|
||||
|
||||
#### Principles
|
||||
- Headless-only: exercise core components directly (`PieceTable`, `Buffer`, `UndoSystem`, `OptimizedSearch`, and minimal `Editor` flows) without starting `kte` or `kge`.
|
||||
- Deterministic and fast: avoid timers, GUI, environment-specific behavior; prefer in-memory operations and temporary files.
|
||||
- Regression-focused: encode prior failures (save/newline mismatch, legacy `rows_` writes) as explicit tests to prevent recurrences.
|
||||
|
||||
#### Harness and execution
|
||||
- Single binary: use target `kte_tests` (already present) to compile and run all tests under `tests/` with the minimal in-tree framework (`tests/Test.h`, `tests/TestRunner.cc`).
|
||||
- No GUI/ncurses deps: link only engine sources (PieceTable/Buffer/Undo/Search/Undo* and syntax minimal set), not frontends.
|
||||
- How to build/run:
|
||||
- Debug profile:
|
||||
```
|
||||
cmake -S /Users/kyle/src/kte -B /Users/kyle/src/kte/cmake-build-debug -DBUILD_TESTS=ON && \
|
||||
cmake --build /Users/kyle/src/kte/cmake-build-debug --target kte_tests && \
|
||||
/Users/kyle/src/kte/cmake-build-debug/kte_tests
|
||||
```
|
||||
- Release profile:
|
||||
```
|
||||
cmake -S /Users/kyle/src/kte -B /Users/kyle/src/kte/cmake-build-release -DBUILD_TESTS=ON && \
|
||||
cmake --build /Users/kyle/src/kte/cmake-build-release --target kte_tests && \
|
||||
/Users/kyle/src/kte/cmake-build-release/kte_tests
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Test catalog (summary table)
|
||||
|
||||
The table below catalogs all unit tests defined in this plan. It is headless-only and maps directly to the suites A–H described later. “Implemented” reflects current coverage in `kte_tests`.
|
||||
|
||||
| Suite | ID | Name | Description (1‑line) | Headless | Implemented |
|
||||
|:-----:|:---:|:------------------------------------------|:-------------------------------------------------------------------------------------|:--------:|:-----------:|
|
||||
| A | 1 | SaveAs then Save (append) | New buffer → write two lines → `SaveAs` → append → `Save`; verify exact bytes. | Yes | ✓ |
|
||||
| A | 2 | Open existing then Save | Open seeded file, append, `Save`; verify overwrite bytes. | Yes | ✓ |
|
||||
| A | 3 | Open non-existent then SaveAs | Start from non-existent path, insert `hello, world\n`, `SaveAs`; verify bytes. | Yes | ✓ |
|
||||
| A | 4 | Trailing newline preservation | Verify saving preserves presence/absence of final `\n`. | Yes | Planned |
|
||||
| A | 5 | Empty buffer saves | Empty → `SaveAs` → 0 bytes; then insert `\n` → `Save` → 1 byte. | Yes | Planned |
|
||||
| A | 6 | Large file streaming | 1–4 MiB with periodic newlines; size and content integrity. | Yes | Planned |
|
||||
| A | 7 | Tilde expansion | `SaveAs` with `~/...`; re-open to confirm path/content. | Yes | Planned |
|
||||
| A | 8 | Error propagation | Save to unwritable path → expect failure and error message. | Yes | Planned |
|
||||
| B | 1 | Insert/Delete LineCount | Basic inserts/deletes and line counting sanity. | Yes | ✓ |
|
||||
| B | 2 | Line/Col conversions | `LineColToByteOffset` and reverse around boundaries. | Yes | ✓ |
|
||||
| B | 3 | Delete spanning newlines | Delete ranges that cross line breaks; verify bytes/lines. | Yes | Planned |
|
||||
| B | 4 | Split/Join equivalence | `split_line` followed by `join_lines` yields original bytes. | Yes | Planned |
|
||||
| B | 5 | Stream vs Data equivalence | `WriteToStream` matches `GetRange`/`Data()` after edits. | Yes | Planned |
|
||||
| B | 6 | UTF‑8 bytes stability | Multibyte sequences behave correctly (byte-based ops). | Yes | Planned |
|
||||
| C | 1 | insert_text/delete_text | Edits at start/middle/end; `Rows()` mirrors PieceTable. | Yes | Planned |
|
||||
| C | 2 | split_line/join_lines | Effects and snapshots across multiple positions. | Yes | Planned |
|
||||
| C | 3 | insert_row/delete_row | Replace paragraph by row ops; verify bytes/linecount. | Yes | Planned |
|
||||
| C | 4 | Cache invalidation | After each mutation, `Rows()` matches `LineCount()`. | Yes | Planned |
|
||||
| D | 1 | Grouped insert undo | Contiguous typing undone/redone as a group. | Yes | Planned |
|
||||
| D | 2 | Delete/Newline undo/redo | Backspace/Delete and Newline transitions across undo/redo. | Yes | Planned |
|
||||
| D | 3 | Mark saved & dirty | Dirty/save markers interact correctly with undo/redo. | Yes | Planned |
|
||||
| E | 1 | Search parity basic | `OptimizedSearch::find_all` vs `std::string` reference. | Yes | ✓ |
|
||||
| E | 2 | Large text search | ~1 MiB random text/patterns parity. | Yes | Planned |
|
||||
| F | 1 | Editor open & reload | Open via `Editor`, modify, reload, verify on-disk bytes. | Yes | Planned |
|
||||
| F | 2 | Read-only toggle | Toggle and verify enforcement/behavior of saves. | Yes | Planned |
|
||||
| F | 3 | Prompt lifecycle | Start/Accept/Cancel prompt doesn’t corrupt state. | Yes | Planned |
|
||||
| G | 1 | Saved only newline regression | Insert text + newline; `Save` includes both bytes. | Yes | Planned |
|
||||
| G | 2 | Backspace crash regression | PieceTable-backed delete/join path remains stable. | Yes | Planned |
|
||||
| G | 3 | Overwrite-confirm path | Saving over existing path succeeds and is correct. | Yes | Planned |
|
||||
| H | 1 | Many small edits | 10k small edits; final bytes correct within time bounds. | Yes | Planned |
|
||||
| H | 2 | Consolidation equivalence | After many edits, stream vs data produce identical bytes. | Yes | Planned |
|
||||
|
||||
Legend: Implemented = ✓, Planned = to be added per Coverage roadmap.
|
||||
|
||||
### Test suites and cases
|
||||
|
||||
#### A) Filesystem I/O via Buffer
|
||||
1) SaveAs then Save (append)
|
||||
- New buffer → `insert_text` two lines (explicit `\n`) → `SaveAs(tmp)` → insert a third line → `Save()`.
|
||||
- Assert file bytes equal exact expected string.
|
||||
2) Open existing then Save
|
||||
- Seed a file on disk; `OpenFromFile(path)` → append line → `Save()`.
|
||||
- Assert file bytes updated exactly.
|
||||
3) Open non-existent then SaveAs
|
||||
- `OpenFromFile(nonexistent)` → assert `IsFileBacked()==false` → insert `"hello, world\n"` → `SaveAs(path)`.
|
||||
- Read back exact bytes.
|
||||
4) Trailing newline preservation
|
||||
- Case (a) last line without `\n`; (b) last line with `\n` → save and verify bytes unchanged.
|
||||
5) Empty buffer saves
|
||||
- `SaveAs(tmp)` on empty buffer → 0-byte file. Then insert `"\n"` and `Save()` → 1-byte file.
|
||||
6) Large file streaming
|
||||
- Insert ~1–4 MiB of data with periodic newlines. `SaveAs` then `Save`; verify size matches `content_.Size()` and bytes integrity.
|
||||
7) Path normalization and tilde expansion
|
||||
- `SaveAs("~/.../file.txt")` → verify path expands to `$HOME` and file content round-trips with `OpenFromFile`.
|
||||
8) Error propagation (guarded)
|
||||
- Attempt save into a non-writable path; expect `Save/SaveAs` returns false with non-empty error. Mark as skipped in environments lacking such path.
|
||||
|
||||
#### B) PieceTable semantics
|
||||
1) Line counting and deletion across lines
|
||||
- Insert `"abc\n123\nxyz"` → 3 lines; delete middle line range → 2 lines; validate `GetLine` contents.
|
||||
2) Position conversions
|
||||
- Validate `LineColToByteOffset` and `ByteOffsetToLineCol` at start/end of lines and EOF, especially around `\n`.
|
||||
3) Delete spanning newlines
|
||||
- Remove a range that crosses line boundaries; verify resulting bytes, `LineCount` and line contents.
|
||||
4) Split/join equivalence
|
||||
- Split at various columns; then join adjacent lines; verify bytes equal original.
|
||||
5) WriteToStream vs materialized `Data()`
|
||||
- After multiple inserts/deletes (without forcing `Data()`), stream to `std::ostringstream`; compare with `GetRange(0, Size())`, then call `Data()` and re-compare.
|
||||
6) UTF-8 bytes stability
|
||||
- Insert multibyte sequences (e.g., `"héllo"`, `"中文"`, emoji) as raw bytes; ensure line counting and conversions behave (byte-based API; no crashes/corruption).
|
||||
|
||||
#### C) Buffer editing helpers and rows cache correctness
|
||||
1) `insert_text`/`delete_text`
|
||||
- Apply at start/middle/end of lines; immediately call `Rows()` and validate contents/lengths mirror PieceTable.
|
||||
2) `split_line` and `join_lines`
|
||||
- Verify content effects and `Rows()` snapshots for multiple positions and consecutive operations.
|
||||
3) `insert_row`/`delete_row`
|
||||
- Replace a paragraph by deleting N rows then inserting N′ rows; verify bytes and `LineCount`.
|
||||
4) Cache invalidation
|
||||
- After each mutation, fetch `Rows()`; assert `Nrows() == content.LineCount()` and no stale data remains.
|
||||
|
||||
#### D) UndoSystem semantics
|
||||
1) Grouped contiguous insert undo
|
||||
- Emulate typing at a single location via repeated `insert_text`; one `undo()` should remove the whole run; `redo()` restores it.
|
||||
2) Delete/newline undo/redo
|
||||
- Simulate backspace/delete (`delete_text` and `join_lines`) and newline (`split_line`); verify content transitions across `undo()`/`redo()`.
|
||||
3) Mark saved and dirty flag
|
||||
- After successful save, call `UndoSystem::mark_saved()` (via existing pathways) and ensure dirty state pairing behaves as intended (at least: `SetDirty(false)` plus save does not break undo/redo).
|
||||
|
||||
#### E) Search algorithms
|
||||
1) Parity with `std::string::find`
|
||||
- Use `OptimizedSearch::find_all` across edge cases (empty needle/text, overlaps like `"aaaaa"` vs `"aa"`, Unicode byte sequences). Compare to reference implementation.
|
||||
2) Large text
|
||||
- Random ASCII text ~1 MiB; random patterns; results match reference.
|
||||
|
||||
#### F) Editor non-interactive flows (no frontend)
|
||||
1) Open and reload
|
||||
- Through `Editor`, open file; modify the underlying `Buffer` directly; invoke reload (`Buffer::OpenFromFile` or `cmd_reload_buffer` if you bring `Command.cc` into the test target). Verify bytes match the on-disk file after reload.
|
||||
2) Read-only toggle
|
||||
- Toggle `Buffer::ToggleReadOnly()`; confirm flag value changes and that subsequent saves still execute when not read-only (or, if enforcement exists, that mutations are appropriately restricted).
|
||||
3) Prompt lifecycle (headless)
|
||||
- Exercise `StartPrompt` → `AcceptPrompt` → `CancelPrompt`; ensure state resets and does not corrupt buffer/editor state.
|
||||
|
||||
#### G) Regression tests for reported bugs
|
||||
1) “Saved only newline”
|
||||
- Build buffer content via `insert_text` followed by `split_line` for newline; `Save` then validate bytes include both the text and newline.
|
||||
2) Backspace crash path
|
||||
- Mimic backspace behavior using PieceTable-backed helpers (`delete_text`/`join_lines`); ensure no dependency on legacy `rows_` mutation and no memory issues.
|
||||
3) Overwrite-confirm path behavior
|
||||
- Start with non-file-backed buffer named to collide with an existing file; perform `SaveAs(existing_path)` and assert success and correctness on disk (unit test bypasses interactive confirm, validating underlying write path).
|
||||
|
||||
#### H) Performance/stress sanity
|
||||
1) Many small edits
|
||||
- 10k single-char inserts and interleaved deletes; assert final bytes; keep within conservative runtime bounds.
|
||||
2) Consolidation heuristics
|
||||
- After many edits, call both `WriteToStream` and `Data()` and verify identical bytes.
|
||||
|
||||
---
|
||||
|
||||
### Coverage roadmap
|
||||
- Phase 1 (already implemented and passing):
|
||||
- Buffer I/O basics (A.1–A.3), PieceTable basics (B.1–B.2), Search parity (E.1).
|
||||
- Phase 2 (add next):
|
||||
- Buffer I/O edge cases (A.4–A.7), deeper PieceTable ops (B.3–B.6), Buffer helpers and cache (C.1–C.4), Undo semantics (D.1–D.2), Regression set (G.1–G.3).
|
||||
- Phase 3:
|
||||
- Editor flows (F.1–F.3), performance/stress (H.1–H.2), and optional integration of `Command.cc` into the test target to exercise non-interactive command execution paths directly.
|
||||
|
||||
### Notes
|
||||
- Use per-test temp files under the repo root or a unique temp directory; ensure cleanup after assertions.
|
||||
- For HOME-dependent tests (tilde expansion), set `HOME` in the test process if not present or skip with a clear message.
|
||||
- On macOS Debug, a benign allocator warning may appear; rely on process exit code for pass/fail.
|
||||
5438
fonts/BerkeleyMono.h
Normal file
5438
fonts/BerkeleyMono.h
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,4 +1,5 @@
|
||||
#include "Font.h"
|
||||
#include "IosevkaExtended.h"
|
||||
|
||||
#include "imgui.h"
|
||||
|
||||
@@ -8,16 +9,32 @@ Font::Load(const float size) const
|
||||
{
|
||||
const ImGuiIO &io = ImGui::GetIO();
|
||||
io.Fonts->Clear();
|
||||
const ImFont *font = io.Fonts->AddFontFromMemoryCompressedTTF(
|
||||
|
||||
ImFontConfig config;
|
||||
config.MergeMode = false;
|
||||
|
||||
// Load Basic Latin + Latin Supplement
|
||||
io.Fonts->AddFontFromMemoryCompressedTTF(
|
||||
this->data_,
|
||||
this->size_,
|
||||
size);
|
||||
size,
|
||||
&config,
|
||||
io.Fonts->GetGlyphRangesDefault());
|
||||
|
||||
if (!font) {
|
||||
font = io.Fonts->AddFontDefault();
|
||||
}
|
||||
// Merge Greek and Mathematical symbols from IosevkaExtended as fallback
|
||||
config.MergeMode = true;
|
||||
static const ImWchar extended_ranges[] = {
|
||||
0x0370, 0x03FF, // Greek and Coptic
|
||||
0x2200, 0x22FF, // Mathematical Operators
|
||||
0,
|
||||
};
|
||||
io.Fonts->AddFontFromMemoryCompressedTTF(
|
||||
kte::Fonts::IosevkaExtended::DefaultFontRegularCompressedData,
|
||||
kte::Fonts::IosevkaExtended::DefaultFontRegularCompressedSize,
|
||||
size,
|
||||
&config,
|
||||
extended_ranges);
|
||||
|
||||
(void) font;
|
||||
io.Fonts->Build();
|
||||
}
|
||||
} // namespace kte::Fonts
|
||||
@@ -3,12 +3,12 @@
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
#include "BrassMonoCode.h"
|
||||
#include "BerkeleyMono.h"
|
||||
|
||||
namespace kte::Fonts {
|
||||
// Provide default embedded font aliases used by GUIFrontend fallback loader
|
||||
inline const unsigned int DefaultFontSize = BrassMonoCode::DefaultFontBoldCompressedSize;
|
||||
inline const unsigned int *DefaultFontData = BrassMonoCode::DefaultFontBoldCompressedData;
|
||||
inline const unsigned int DefaultFontSize = BerkeleyMono::DefaultFontRegularCompressedSize;
|
||||
inline const unsigned int *DefaultFontData = BerkeleyMono::DefaultFontRegularCompressedData;
|
||||
|
||||
class Font {
|
||||
public:
|
||||
@@ -31,4 +31,4 @@ private:
|
||||
const unsigned int *data_{nullptr};
|
||||
unsigned int size_{0};
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#pragma once
|
||||
#include "B612Mono.h"
|
||||
#include "BerkeleyMono.h"
|
||||
#include "BrassMono.h"
|
||||
#include "BrassMonoCode.h"
|
||||
#include "FiraCode.h"
|
||||
@@ -14,4 +15,4 @@
|
||||
#include "SpaceMono.h"
|
||||
#include "Syne.h"
|
||||
#include "Triplicate.h"
|
||||
#include "Unispace.h"
|
||||
#include "Unispace.h"
|
||||
|
||||
@@ -7,28 +7,38 @@ InstallDefaultFonts()
|
||||
{
|
||||
FontRegistry::Instance().Register(std::make_unique<Font>(
|
||||
"default",
|
||||
BrassMono::DefaultFontBoldCompressedData,
|
||||
BrassMono::DefaultFontBoldCompressedSize
|
||||
BerkeleyMono::DefaultFontBoldCompressedData,
|
||||
BerkeleyMono::DefaultFontBoldCompressedSize
|
||||
));
|
||||
FontRegistry::Instance().Register(std::make_unique<Font>(
|
||||
"b612",
|
||||
B612Mono::DefaultFontRegularCompressedData,
|
||||
B612Mono::DefaultFontRegularCompressedSize
|
||||
));
|
||||
FontRegistry::Instance().Register(std::make_unique<Font>(
|
||||
"berkeley",
|
||||
BerkeleyMono::DefaultFontRegularCompressedData,
|
||||
BerkeleyMono::DefaultFontRegularCompressedSize
|
||||
));
|
||||
FontRegistry::Instance().Register(std::make_unique<Font>(
|
||||
"berkeley-bold",
|
||||
BerkeleyMono::DefaultFontBoldCompressedData,
|
||||
BerkeleyMono::DefaultFontBoldCompressedSize
|
||||
));
|
||||
FontRegistry::Instance().Register(std::make_unique<Font>(
|
||||
"brassmono",
|
||||
BrassMono::DefaultFontRegularCompressedData,
|
||||
BrassMono::DefaultFontRegularCompressedSize
|
||||
));
|
||||
FontRegistry::Instance().Register(std::make_unique<Font>(
|
||||
"brassmono-bold",
|
||||
BrassMono::DefaultFontBoldCompressedData,
|
||||
BrassMono::DefaultFontBoldCompressedSize
|
||||
"brassmono-bold",
|
||||
BrassMono::DefaultFontBoldCompressedData,
|
||||
BrassMono::DefaultFontBoldCompressedSize
|
||||
));
|
||||
FontRegistry::Instance().Register(std::make_unique<Font>(
|
||||
"brassmonocode",
|
||||
BrassMonoCode::DefaultFontRegularCompressedData,
|
||||
BrassMonoCode::DefaultFontRegularCompressedSize
|
||||
"brassmonocode",
|
||||
BrassMonoCode::DefaultFontRegularCompressedData,
|
||||
BrassMonoCode::DefaultFontRegularCompressedSize
|
||||
));
|
||||
FontRegistry::Instance().Register(std::make_unique<Font>(
|
||||
"brassmonocode-bold",
|
||||
@@ -101,4 +111,4 @@ InstallDefaultFonts()
|
||||
Unispace::DefaultFontRegularCompressedSize
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
15
main.cc
15
main.cc
@@ -1,3 +1,4 @@
|
||||
#include <clocale>
|
||||
#include <cctype>
|
||||
#include <cerrno>
|
||||
#include <cstdio>
|
||||
@@ -113,6 +114,8 @@ RunStressHighlighter(unsigned seconds)
|
||||
int
|
||||
main(int argc, const char *argv[])
|
||||
{
|
||||
std::setlocale(LC_ALL, "");
|
||||
|
||||
Editor editor;
|
||||
|
||||
// CLI parsing using getopt_long
|
||||
@@ -192,13 +195,11 @@ main(int argc, const char *argv[])
|
||||
} else if (req_term) {
|
||||
use_gui = false;
|
||||
} else {
|
||||
|
||||
|
||||
// Default depends on build target: kge defaults to GUI, kte to terminal
|
||||
// Default depends on build target: kge defaults to GUI, kte to terminal
|
||||
#if defined(KTE_DEFAULT_GUI)
|
||||
use_gui = true;
|
||||
use_gui = true;
|
||||
#else
|
||||
use_gui = false;
|
||||
use_gui = false;
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
@@ -307,6 +308,8 @@ main(int argc, const char *argv[])
|
||||
return 1;
|
||||
}
|
||||
|
||||
Execute(editor, CommandId::CenterOnCursor);
|
||||
|
||||
bool running = true;
|
||||
while (running) {
|
||||
fe->Step(editor, running);
|
||||
@@ -315,4 +318,4 @@ main(int argc, const char *argv[])
|
||||
fe->Shutdown();
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,14 +16,18 @@ open .
|
||||
cd ..
|
||||
|
||||
mkdir -p cmake-build-release-qt
|
||||
cmake -S . -B cmake-build-release -DBUILD_GUI=ON -DCMAKE_BUILD_TYPE=Release -DENABLE_ASAN=OFF
|
||||
cmake -S . -B cmake-build-release-qt -DBUILD_GUI=ON -DKTE_USE_QT=ON -DCMAKE_BUILD_TYPE=Release -DENABLE_ASAN=OFF
|
||||
|
||||
cd cmake-build-release-qt
|
||||
make clean
|
||||
rm -fr kge.app* kge-qt.app*
|
||||
make
|
||||
mv kge.app kge-qt.app
|
||||
macdeployqt kge-qt.app -always-overwrite
|
||||
mv -f kge.app kge-qt.app
|
||||
# Use the same Qt's macdeployqt as used for building; ensure it overwrites in-bundle paths
|
||||
macdeployqt kge-qt.app -always-overwrite -verbose=3
|
||||
|
||||
# Run CMake BundleUtilities fixup to internalize non-Qt dylibs and rewrite install names
|
||||
cmake -DAPP_BUNDLE="$(pwd)/kge-qt.app" -P "${PWD%/*}/cmake/fix_bundle.cmake"
|
||||
zip -r kge-qt.app.zip kge-qt.app
|
||||
sha256sum kge-qt.app.zip
|
||||
open .
|
||||
|
||||
@@ -1,74 +0,0 @@
|
||||
// Verify OptimizedSearch against std::string reference across patterns and sizes
|
||||
#include <cassert>
|
||||
#include <cstddef>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "OptimizedSearch.h"
|
||||
|
||||
|
||||
static std::vector<std::size_t>
|
||||
ref_find_all(const std::string &text, const std::string &pat)
|
||||
{
|
||||
std::vector<std::size_t> res;
|
||||
if (pat.empty())
|
||||
return res;
|
||||
std::size_t from = 0;
|
||||
while (true) {
|
||||
auto p = text.find(pat, from);
|
||||
if (p == std::string::npos)
|
||||
break;
|
||||
res.push_back(p);
|
||||
from = p + pat.size(); // non-overlapping
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
|
||||
static void
|
||||
run_case(std::size_t textLen, std::size_t patLen, unsigned seed)
|
||||
{
|
||||
std::mt19937 rng(seed);
|
||||
std::uniform_int_distribution<int> dist('a', 'z');
|
||||
std::string text(textLen, '\0');
|
||||
for (auto &ch: text)
|
||||
ch = static_cast<char>(dist(rng));
|
||||
std::string pat(patLen, '\0');
|
||||
for (auto &ch: pat)
|
||||
ch = static_cast<char>(dist(rng));
|
||||
|
||||
// Guarantee at least one match when possible
|
||||
if (textLen >= patLen && patLen > 0) {
|
||||
std::size_t pos = textLen / 3;
|
||||
if (pos + patLen <= text.size())
|
||||
std::copy(pat.begin(), pat.end(), text.begin() + static_cast<long>(pos));
|
||||
}
|
||||
|
||||
OptimizedSearch os;
|
||||
auto got = os.find_all(text, pat, 0);
|
||||
auto ref = ref_find_all(text, pat);
|
||||
assert(got == ref);
|
||||
}
|
||||
|
||||
|
||||
int
|
||||
main()
|
||||
{
|
||||
// Edge cases
|
||||
run_case(0, 0, 1);
|
||||
run_case(0, 1, 2);
|
||||
run_case(1, 0, 3);
|
||||
run_case(1, 1, 4);
|
||||
|
||||
// Various sizes
|
||||
for (std::size_t t = 128; t <= 4096; t *= 2) {
|
||||
for (std::size_t p = 1; p <= 64; p *= 2) {
|
||||
run_case(t, p, static_cast<unsigned>(t + p));
|
||||
}
|
||||
}
|
||||
// Larger random
|
||||
run_case(100000, 16, 12345);
|
||||
run_case(250000, 32, 67890);
|
||||
return 0;
|
||||
}
|
||||
338
test_undo.cc
338
test_undo.cc
@@ -1,338 +0,0 @@
|
||||
#include <cassert>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
|
||||
#include "Buffer.h"
|
||||
#include "Command.h"
|
||||
#include "Editor.h"
|
||||
#include "TestFrontend.h"
|
||||
|
||||
|
||||
int
|
||||
main()
|
||||
{
|
||||
// Install default commands
|
||||
InstallDefaultCommands();
|
||||
|
||||
Editor editor;
|
||||
TestFrontend frontend;
|
||||
|
||||
// Initialize frontend
|
||||
if (!frontend.Init(editor)) {
|
||||
std::cerr << "Failed to initialize frontend\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Create a temporary test file
|
||||
std::string err;
|
||||
const char *tmpfile = "/tmp/kte_test_undo.txt";
|
||||
{
|
||||
std::ofstream f(tmpfile);
|
||||
if (!f) {
|
||||
std::cerr << "Failed to create temp file\n";
|
||||
return 1;
|
||||
}
|
||||
f << "\n"; // Write one newline so file isn't empty
|
||||
f.close();
|
||||
}
|
||||
|
||||
if (!editor.OpenFile(tmpfile, err)) {
|
||||
std::cerr << "Failed to open test file: " << err << "\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
Buffer *buf = editor.CurrentBuffer();
|
||||
assert(buf != nullptr);
|
||||
|
||||
// Initialize cursor to (0,0) explicitly
|
||||
buf->SetCursor(0, 0);
|
||||
|
||||
std::cout << "test_undo: Testing undo/redo system\n";
|
||||
std::cout << "====================================\n\n";
|
||||
|
||||
bool running = true;
|
||||
|
||||
// Test 1: Insert text and verify buffer contains expected text
|
||||
std::cout << "Test 1: Insert text 'Hello'\n";
|
||||
frontend.Input().QueueText("Hello");
|
||||
|
||||
while (!frontend.Input().IsEmpty() && running) {
|
||||
frontend.Step(editor, running);
|
||||
}
|
||||
|
||||
assert(buf->Rows().size() >= 1);
|
||||
std::string line_after_insert = std::string(buf->Rows()[0]);
|
||||
assert(line_after_insert == "Hello");
|
||||
std::cout << " Buffer content: '" << line_after_insert << "'\n";
|
||||
std::cout << " ✓ Text insertion verified\n\n";
|
||||
|
||||
// Test 2: Undo insertion - text should be removed
|
||||
std::cout << "Test 2: Undo insertion\n";
|
||||
frontend.Input().QueueCommand(CommandId::Undo);
|
||||
|
||||
while (!frontend.Input().IsEmpty() && running) {
|
||||
frontend.Step(editor, running);
|
||||
}
|
||||
|
||||
assert(buf->Rows().size() >= 1);
|
||||
std::string line_after_undo = std::string(buf->Rows()[0]);
|
||||
assert(line_after_undo == "");
|
||||
std::cout << " Buffer content: '" << line_after_undo << "'\n";
|
||||
std::cout << " ✓ Undo successful - text removed\n\n";
|
||||
|
||||
// Test 3: Redo insertion - text should be restored
|
||||
std::cout << "Test 3: Redo insertion\n";
|
||||
frontend.Input().QueueCommand(CommandId::Redo);
|
||||
|
||||
while (!frontend.Input().IsEmpty() && running) {
|
||||
frontend.Step(editor, running);
|
||||
}
|
||||
|
||||
assert(buf->Rows().size() >= 1);
|
||||
std::string line_after_redo = std::string(buf->Rows()[0]);
|
||||
assert(line_after_redo == "Hello");
|
||||
std::cout << " Buffer content: '" << line_after_redo << "'\n";
|
||||
std::cout << " ✓ Redo successful - text restored\n\n";
|
||||
|
||||
// Test 4: Branching behavior – redo is discarded after new edits
|
||||
std::cout << "Test 4: Branching behavior (redo discarded after new edits)\n";
|
||||
// Reset to empty by undoing the last redo and the original insert, then reinsert 'abc'
|
||||
// Ensure buffer is empty before starting this scenario
|
||||
frontend.Input().QueueCommand(CommandId::Undo); // undo Hello
|
||||
while (!frontend.Input().IsEmpty() && running) {
|
||||
frontend.Step(editor, running);
|
||||
}
|
||||
assert(std::string(buf->Rows()[0]) == "");
|
||||
|
||||
// Type a contiguous word 'abc' (single batch)
|
||||
frontend.Input().QueueText("abc");
|
||||
while (!frontend.Input().IsEmpty() && running) {
|
||||
frontend.Step(editor, running);
|
||||
}
|
||||
assert(std::string(buf->Rows()[0]) == "abc");
|
||||
|
||||
// Undo once – should remove the whole batch and leave empty
|
||||
frontend.Input().QueueCommand(CommandId::Undo);
|
||||
while (!frontend.Input().IsEmpty() && running) {
|
||||
frontend.Step(editor, running);
|
||||
}
|
||||
assert(std::string(buf->Rows()[0]) == "");
|
||||
|
||||
// Now type new text 'X' – this should create a new branch and discard old redo chain
|
||||
frontend.Input().QueueText("X");
|
||||
while (!frontend.Input().IsEmpty() && running) {
|
||||
frontend.Step(editor, running);
|
||||
}
|
||||
assert(std::string(buf->Rows()[0]) == "X");
|
||||
|
||||
// Attempt Redo – should be a no-op (redo branch was discarded by new edit)
|
||||
frontend.Input().QueueCommand(CommandId::Redo);
|
||||
while (!frontend.Input().IsEmpty() && running) {
|
||||
frontend.Step(editor, running);
|
||||
}
|
||||
assert(std::string(buf->Rows()[0]) == "X");
|
||||
// Undo and Redo along the new branch should still work
|
||||
frontend.Input().QueueCommand(CommandId::Undo);
|
||||
frontend.Input().QueueCommand(CommandId::Redo);
|
||||
while (!frontend.Input().IsEmpty() && running) {
|
||||
frontend.Step(editor, running);
|
||||
}
|
||||
assert(std::string(buf->Rows()[0]) == "X");
|
||||
std::cout << " ✓ Redo discarded after new edit; new branch undo/redo works\n\n";
|
||||
|
||||
// Clear buffer state for next tests: undo to empty if needed
|
||||
frontend.Input().QueueCommand(CommandId::Undo);
|
||||
while (!frontend.Input().IsEmpty() && running) {
|
||||
frontend.Step(editor, running);
|
||||
}
|
||||
assert(std::string(buf->Rows()[0]) == "");
|
||||
|
||||
// Test 5: UTF-8 insertion and undo/redo round-trip
|
||||
std::cout << "Test 5: UTF-8 insertion 'é漢' and undo/redo\n";
|
||||
const std::string utf8_text = "é漢"; // multi-byte UTF-8 (2 bytes + 3 bytes)
|
||||
frontend.Input().QueueText(utf8_text);
|
||||
while (!frontend.Input().IsEmpty() && running) {
|
||||
frontend.Step(editor, running);
|
||||
}
|
||||
assert(std::string(buf->Rows()[0]) == utf8_text);
|
||||
// Undo should remove the entire contiguous insertion batch
|
||||
frontend.Input().QueueCommand(CommandId::Undo);
|
||||
while (!frontend.Input().IsEmpty() && running) {
|
||||
frontend.Step(editor, running);
|
||||
}
|
||||
assert(std::string(buf->Rows()[0]) == "");
|
||||
// Redo restores it
|
||||
frontend.Input().QueueCommand(CommandId::Redo);
|
||||
while (!frontend.Input().IsEmpty() && running) {
|
||||
frontend.Step(editor, running);
|
||||
}
|
||||
assert(std::string(buf->Rows()[0]) == utf8_text);
|
||||
std::cout << " ✓ UTF-8 insert round-trips with undo/redo\n\n";
|
||||
|
||||
// Clear for next test
|
||||
frontend.Input().QueueCommand(CommandId::Undo);
|
||||
while (!frontend.Input().IsEmpty() && running) {
|
||||
frontend.Step(editor, running);
|
||||
}
|
||||
assert(std::string(buf->Rows()[0]) == "");
|
||||
|
||||
// Test 6: Multi-line operations (newline split and join via backspace at BOL)
|
||||
std::cout << "Test 6: Newline split and join via backspace at BOL\n";
|
||||
// Insert "ab" then newline then "cd" → expect two lines
|
||||
frontend.Input().QueueText("ab");
|
||||
frontend.Input().QueueCommand(CommandId::Newline);
|
||||
frontend.Input().QueueText("cd");
|
||||
while (!frontend.Input().IsEmpty() && running) {
|
||||
frontend.Step(editor, running);
|
||||
}
|
||||
assert(buf->Rows().size() >= 2);
|
||||
assert(std::string(buf->Rows()[0]) == "ab");
|
||||
assert(std::string(buf->Rows()[1]) == "cd");
|
||||
std::cout << " ✓ Split into two lines\n";
|
||||
|
||||
// Undo once – should remove "cd" insertion leaving two lines ["ab", ""] or join depending on commit
|
||||
frontend.Input().QueueCommand(CommandId::Undo);
|
||||
while (!frontend.Input().IsEmpty() && running) {
|
||||
frontend.Step(editor, running);
|
||||
}
|
||||
// Current design batches typing on the second line; after undo, the second line should exist but be empty
|
||||
assert(buf->Rows().size() >= 2);
|
||||
assert(std::string(buf->Rows()[0]) == "ab");
|
||||
assert(std::string(buf->Rows()[1]) == "");
|
||||
|
||||
// Undo the newline – should rejoin to a single line "ab"
|
||||
frontend.Input().QueueCommand(CommandId::Undo);
|
||||
while (!frontend.Input().IsEmpty() && running) {
|
||||
frontend.Step(editor, running);
|
||||
}
|
||||
assert(buf->Rows().size() >= 1);
|
||||
assert(std::string(buf->Rows()[0]) == "ab");
|
||||
|
||||
// Redo twice to get back to ["ab","cd"]
|
||||
frontend.Input().QueueCommand(CommandId::Redo);
|
||||
frontend.Input().QueueCommand(CommandId::Redo);
|
||||
while (!frontend.Input().IsEmpty() && running) {
|
||||
frontend.Step(editor, running);
|
||||
}
|
||||
assert(std::string(buf->Rows()[0]) == "ab");
|
||||
assert(std::string(buf->Rows()[1]) == "cd");
|
||||
std::cout << " ✓ Newline undo/redo round-trip\n";
|
||||
|
||||
// Now join via Backspace at beginning of second line
|
||||
frontend.Input().QueueCommand(CommandId::MoveDown); // ensure we're on the second line
|
||||
frontend.Input().QueueCommand(CommandId::MoveHome); // go to BOL on second line
|
||||
frontend.Input().QueueCommand(CommandId::Backspace); // join with previous line
|
||||
while (!frontend.Input().IsEmpty() && running) {
|
||||
frontend.Step(editor, running);
|
||||
}
|
||||
assert(buf->Rows().size() >= 1);
|
||||
assert(std::string(buf->Rows()[0]) == "abcd");
|
||||
std::cout << " ✓ Backspace at BOL joins lines\n";
|
||||
|
||||
// Undo/Redo the join
|
||||
frontend.Input().QueueCommand(CommandId::Undo);
|
||||
frontend.Input().QueueCommand(CommandId::Redo);
|
||||
while (!frontend.Input().IsEmpty() && running) {
|
||||
frontend.Step(editor, running);
|
||||
}
|
||||
assert(buf->Rows().size() >= 1);
|
||||
assert(std::string(buf->Rows()[0]) == "abcd");
|
||||
std::cout << " ✓ Join undo/redo round-trip\n\n";
|
||||
|
||||
// Test 7: Typing batching – a contiguous word undone in one step
|
||||
std::cout << "Test 7: Typing batching (single undo removes whole word)\n";
|
||||
// Clear current line first
|
||||
frontend.Input().QueueCommand(CommandId::MoveHome);
|
||||
frontend.Input().QueueCommand(CommandId::KillToEOL);
|
||||
while (!frontend.Input().IsEmpty() && running) {
|
||||
frontend.Step(editor, running);
|
||||
}
|
||||
assert(std::string(buf->Rows()[0]).empty());
|
||||
// Type a word and verify one undo clears it
|
||||
frontend.Input().QueueText("hello");
|
||||
while (!frontend.Input().IsEmpty() && running) {
|
||||
frontend.Step(editor, running);
|
||||
}
|
||||
assert(std::string(buf->Rows()[0]) == "hello");
|
||||
frontend.Input().QueueCommand(CommandId::Undo);
|
||||
while (!frontend.Input().IsEmpty() && running) {
|
||||
frontend.Step(editor, running);
|
||||
}
|
||||
assert(std::string(buf->Rows()[0]).empty());
|
||||
frontend.Input().QueueCommand(CommandId::Redo);
|
||||
while (!frontend.Input().IsEmpty() && running) {
|
||||
frontend.Step(editor, running);
|
||||
}
|
||||
assert(std::string(buf->Rows()[0]) == "hello");
|
||||
std::cout << " ✓ Contiguous typing batched into single undo step\n\n";
|
||||
|
||||
// Test 8: Forward delete batching at a fixed anchor column
|
||||
std::cout << "Test 8: Forward delete batching at fixed anchor (DeleteChar)\n";
|
||||
// Prepare line content
|
||||
frontend.Input().QueueCommand(CommandId::MoveHome);
|
||||
frontend.Input().QueueCommand(CommandId::KillToEOL);
|
||||
while (!frontend.Input().IsEmpty() && running) {
|
||||
frontend.Step(editor, running);
|
||||
}
|
||||
frontend.Input().QueueText("abcdef");
|
||||
while (!frontend.Input().IsEmpty() && running) {
|
||||
frontend.Step(editor, running);
|
||||
}
|
||||
// Ensure cursor at anchor column 0
|
||||
frontend.Input().QueueCommand(CommandId::MoveHome);
|
||||
// Delete three chars at cursor; should batch into one Delete node
|
||||
frontend.Input().QueueCommand(CommandId::DeleteChar, "", 3);
|
||||
while (!frontend.Input().IsEmpty() && running) {
|
||||
frontend.Step(editor, running);
|
||||
}
|
||||
assert(std::string(buf->Rows()[0]) == "def");
|
||||
// Single undo should restore the entire deleted run
|
||||
frontend.Input().QueueCommand(CommandId::Undo);
|
||||
while (!frontend.Input().IsEmpty() && running) {
|
||||
frontend.Step(editor, running);
|
||||
}
|
||||
assert(std::string(buf->Rows()[0]) == "abcdef");
|
||||
// Redo should remove the same run again
|
||||
frontend.Input().QueueCommand(CommandId::Redo);
|
||||
while (!frontend.Input().IsEmpty() && running) {
|
||||
frontend.Step(editor, running);
|
||||
}
|
||||
assert(std::string(buf->Rows()[0]) == "def");
|
||||
std::cout << " ✓ Forward delete batched and undo/redo round-trips\n\n";
|
||||
|
||||
// Test 9: Backspace batching with prepend rule (cursor moves left)
|
||||
std::cout << "Test 9: Backspace batching with prepend rule\n";
|
||||
// Restore to full string then backspace a run
|
||||
frontend.Input().QueueCommand(CommandId::Undo); // bring back to "abcdef"
|
||||
while (!frontend.Input().IsEmpty() && running) {
|
||||
frontend.Step(editor, running);
|
||||
}
|
||||
assert(std::string(buf->Rows()[0]) == "abcdef");
|
||||
// Move to end and backspace three characters; should batch into one Delete node
|
||||
frontend.Input().QueueCommand(CommandId::MoveEnd);
|
||||
frontend.Input().QueueCommand(CommandId::Backspace, "", 3);
|
||||
while (!frontend.Input().IsEmpty() && running) {
|
||||
frontend.Step(editor, running);
|
||||
}
|
||||
assert(std::string(buf->Rows()[0]) == "abc");
|
||||
// Single undo restores the deleted run
|
||||
frontend.Input().QueueCommand(CommandId::Undo);
|
||||
while (!frontend.Input().IsEmpty() && running) {
|
||||
frontend.Step(editor, running);
|
||||
}
|
||||
assert(std::string(buf->Rows()[0]) == "abcdef");
|
||||
// Redo removes it again
|
||||
frontend.Input().QueueCommand(CommandId::Redo);
|
||||
while (!frontend.Input().IsEmpty() && running) {
|
||||
frontend.Step(editor, running);
|
||||
}
|
||||
assert(std::string(buf->Rows()[0]) == "abc");
|
||||
std::cout << " ✓ Backspace run batched and undo/redo round-trips\n\n";
|
||||
|
||||
frontend.Shutdown();
|
||||
|
||||
std::cout << "====================================\n";
|
||||
std::cout << "All tests passed!\n";
|
||||
|
||||
return 0;
|
||||
}
|
||||
63
tests/Test.h
Normal file
63
tests/Test.h
Normal file
@@ -0,0 +1,63 @@
|
||||
// Minimal header-only unit test framework for kte
|
||||
#pragma once
|
||||
#include <functional>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <chrono>
|
||||
#include <sstream>
|
||||
|
||||
namespace ktet {
|
||||
|
||||
struct TestCase {
|
||||
std::string name;
|
||||
std::function<void()> fn;
|
||||
};
|
||||
|
||||
inline std::vector<TestCase>& registry() {
|
||||
static std::vector<TestCase> r;
|
||||
return r;
|
||||
}
|
||||
|
||||
struct Registrar {
|
||||
Registrar(const char* name, std::function<void()> fn) {
|
||||
registry().push_back(TestCase{std::string(name), std::move(fn)});
|
||||
}
|
||||
};
|
||||
|
||||
// Assertions
|
||||
struct AssertionFailure {
|
||||
std::string msg;
|
||||
};
|
||||
|
||||
inline void expect(bool cond, const char* expr, const char* file, int line) {
|
||||
if (!cond) {
|
||||
std::cerr << file << ":" << line << ": EXPECT failed: " << expr << "\n";
|
||||
}
|
||||
}
|
||||
|
||||
inline void assert_true(bool cond, const char* expr, const char* file, int line) {
|
||||
if (!cond) {
|
||||
throw AssertionFailure{std::string(file) + ":" + std::to_string(line) + ": ASSERT failed: " + expr};
|
||||
}
|
||||
}
|
||||
|
||||
template<typename A, typename B>
|
||||
inline void assert_eq_impl(const A& a, const B& b, const char* ea, const char* eb, const char* file, int line) {
|
||||
if (!(a == b)) {
|
||||
std::ostringstream oss;
|
||||
oss << file << ":" << line << ": ASSERT_EQ failed: " << ea << " == " << eb;
|
||||
throw AssertionFailure{oss.str()};
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace ktet
|
||||
|
||||
#define TEST(name) \
|
||||
static void name(); \
|
||||
static ::ktet::Registrar _reg_##name(#name, &name); \
|
||||
static void name()
|
||||
|
||||
#define EXPECT_TRUE(x) ::ktet::expect((x), #x, __FILE__, __LINE__)
|
||||
#define ASSERT_TRUE(x) ::ktet::assert_true((x), #x, __FILE__, __LINE__)
|
||||
#define ASSERT_EQ(a,b) ::ktet::assert_eq_impl((a),(b), #a, #b, __FILE__, __LINE__)
|
||||
33
tests/TestRunner.cc
Normal file
33
tests/TestRunner.cc
Normal file
@@ -0,0 +1,33 @@
|
||||
#include "Test.h"
|
||||
#include <iostream>
|
||||
#include <chrono>
|
||||
|
||||
int main() {
|
||||
using namespace std::chrono;
|
||||
auto ® = ktet::registry();
|
||||
std::cout << "kte unit tests: " << reg.size() << " test(s)\n";
|
||||
int failed = 0;
|
||||
auto t0 = steady_clock::now();
|
||||
for (const auto &tc : reg) {
|
||||
auto ts = steady_clock::now();
|
||||
try {
|
||||
tc.fn();
|
||||
auto te = steady_clock::now();
|
||||
auto ms = duration_cast<milliseconds>(te - ts).count();
|
||||
std::cout << "[ OK ] " << tc.name << " (" << ms << " ms)\n";
|
||||
} catch (const ktet::AssertionFailure &e) {
|
||||
++failed;
|
||||
std::cerr << "[FAIL] " << tc.name << " -> " << e.msg << "\n";
|
||||
} catch (const std::exception &e) {
|
||||
++failed;
|
||||
std::cerr << "[EXCP] " << tc.name << " -> " << e.what() << "\n";
|
||||
} catch (...) {
|
||||
++failed;
|
||||
std::cerr << "[EXCP] " << tc.name << " -> unknown exception\n";
|
||||
}
|
||||
}
|
||||
auto t1 = steady_clock::now();
|
||||
auto total_ms = duration_cast<milliseconds>(t1 - t0).count();
|
||||
std::cout << "Done in " << total_ms << " ms. Failures: " << failed << "\n";
|
||||
return failed == 0 ? 0 : 1;
|
||||
}
|
||||
79
tests/test_buffer_io.cc
Normal file
79
tests/test_buffer_io.cc
Normal file
@@ -0,0 +1,79 @@
|
||||
#include "Test.h"
|
||||
#include <fstream>
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
#include "Buffer.h"
|
||||
|
||||
static std::string read_all(const std::string &path) {
|
||||
std::ifstream in(path, std::ios::binary);
|
||||
return std::string((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
|
||||
}
|
||||
|
||||
TEST(Buffer_SaveAs_and_Save_new_file) {
|
||||
const std::string path = "./.kte_ut_buffer_io_1.tmp";
|
||||
std::remove(path.c_str());
|
||||
|
||||
Buffer b;
|
||||
// insert two lines
|
||||
b.insert_text(0, 0, std::string("Hello, world!\n"));
|
||||
b.insert_text(1, 0, std::string("Second line\n"));
|
||||
|
||||
std::string err;
|
||||
ASSERT_TRUE(b.SaveAs(path, err));
|
||||
ASSERT_EQ(err.empty(), true);
|
||||
|
||||
// append another line then Save()
|
||||
b.insert_text(2, 0, std::string("Third\n"));
|
||||
b.SetDirty(true);
|
||||
ASSERT_TRUE(b.Save(err));
|
||||
ASSERT_EQ(err.empty(), true);
|
||||
|
||||
std::string got = read_all(path);
|
||||
ASSERT_EQ(got, std::string("Hello, world!\nSecond line\nThird\n"));
|
||||
|
||||
std::remove(path.c_str());
|
||||
}
|
||||
|
||||
TEST(Buffer_Save_after_Open_existing) {
|
||||
const std::string path = "./.kte_ut_buffer_io_2.tmp";
|
||||
std::remove(path.c_str());
|
||||
{
|
||||
std::ofstream out(path, std::ios::binary);
|
||||
out << "abc\n123\n";
|
||||
}
|
||||
|
||||
Buffer b;
|
||||
std::string err;
|
||||
ASSERT_TRUE(b.OpenFromFile(path, err));
|
||||
ASSERT_EQ(err.empty(), true);
|
||||
|
||||
b.insert_text(2, 0, std::string("tail\n"));
|
||||
b.SetDirty(true);
|
||||
ASSERT_TRUE(b.Save(err));
|
||||
ASSERT_EQ(err.empty(), true);
|
||||
|
||||
std::string got = read_all(path);
|
||||
ASSERT_EQ(got, std::string("abc\n123\ntail\n"));
|
||||
std::remove(path.c_str());
|
||||
}
|
||||
|
||||
TEST(Buffer_Open_nonexistent_then_SaveAs) {
|
||||
const std::string path = "./.kte_ut_buffer_io_3.tmp";
|
||||
std::remove(path.c_str());
|
||||
|
||||
Buffer b;
|
||||
std::string err;
|
||||
ASSERT_TRUE(b.OpenFromFile(path, err));
|
||||
ASSERT_EQ(err.empty(), true);
|
||||
ASSERT_EQ(b.IsFileBacked(), false);
|
||||
|
||||
b.insert_text(0, 0, std::string("hello, world"));
|
||||
b.insert_text(0, 12, std::string("\n"));
|
||||
b.SetDirty(true);
|
||||
ASSERT_TRUE(b.SaveAs(path, err));
|
||||
ASSERT_EQ(err.empty(), true);
|
||||
|
||||
std::string got = read_all(path);
|
||||
ASSERT_EQ(got, std::string("hello, world\n"));
|
||||
std::remove(path.c_str());
|
||||
}
|
||||
49
tests/test_piece_table.cc
Normal file
49
tests/test_piece_table.cc
Normal file
@@ -0,0 +1,49 @@
|
||||
#include "Test.h"
|
||||
#include "PieceTable.h"
|
||||
#include <string>
|
||||
|
||||
TEST(PieceTable_Insert_Delete_LineCount) {
|
||||
PieceTable pt;
|
||||
// start empty
|
||||
ASSERT_EQ(pt.Size(), (std::size_t)0);
|
||||
ASSERT_EQ(pt.LineCount(), (std::size_t)1); // empty buffer has 1 logical line
|
||||
|
||||
// Insert some text with newlines
|
||||
const char *t = "abc\n123\nxyz"; // last line without trailing NL
|
||||
pt.Insert(0, t, 11);
|
||||
ASSERT_EQ(pt.Size(), (std::size_t)11);
|
||||
ASSERT_EQ(pt.LineCount(), (std::size_t)3);
|
||||
|
||||
// Check get line
|
||||
ASSERT_EQ(pt.GetLine(0), std::string("abc"));
|
||||
ASSERT_EQ(pt.GetLine(1), std::string("123"));
|
||||
ASSERT_EQ(pt.GetLine(2), std::string("xyz"));
|
||||
|
||||
// Delete middle line entirely including its trailing NL
|
||||
auto r = pt.GetLineRange(1); // [start,end) points to start of line 1 to start of line 2
|
||||
pt.Delete(r.first, r.second - r.first);
|
||||
ASSERT_EQ(pt.LineCount(), (std::size_t)2);
|
||||
ASSERT_EQ(pt.GetLine(0), std::string("abc"));
|
||||
ASSERT_EQ(pt.GetLine(1), std::string("xyz"));
|
||||
}
|
||||
|
||||
TEST(PieceTable_LineCol_Conversions) {
|
||||
PieceTable pt;
|
||||
std::string s = "hello\nworld\n"; // two lines with trailing NL
|
||||
pt.Insert(0, s.data(), s.size());
|
||||
|
||||
// Byte offsets of starts
|
||||
auto off0 = pt.LineColToByteOffset(0, 0);
|
||||
auto off1 = pt.LineColToByteOffset(1, 0);
|
||||
auto off2 = pt.LineColToByteOffset(2, 0); // EOF
|
||||
ASSERT_EQ(off0, (std::size_t)0);
|
||||
ASSERT_EQ(off1, (std::size_t)6); // "hello\n"
|
||||
ASSERT_EQ(off2, pt.Size());
|
||||
|
||||
auto lc0 = pt.ByteOffsetToLineCol(0);
|
||||
auto lc1 = pt.ByteOffsetToLineCol(6);
|
||||
ASSERT_EQ(lc0.first, (std::size_t)0);
|
||||
ASSERT_EQ(lc0.second, (std::size_t)0);
|
||||
ASSERT_EQ(lc1.first, (std::size_t)1);
|
||||
ASSERT_EQ(lc1.second, (std::size_t)0);
|
||||
}
|
||||
36
tests/test_search.cc
Normal file
36
tests/test_search.cc
Normal file
@@ -0,0 +1,36 @@
|
||||
#include "Test.h"
|
||||
#include "OptimizedSearch.h"
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
static std::vector<std::size_t> ref_find_all(const std::string &text, const std::string &pat) {
|
||||
std::vector<std::size_t> res;
|
||||
if (pat.empty()) return res;
|
||||
std::size_t from = 0;
|
||||
while (true) {
|
||||
auto p = text.find(pat, from);
|
||||
if (p == std::string::npos) break;
|
||||
res.push_back(p);
|
||||
from = p + pat.size();
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
TEST(OptimizedSearch_basic_cases) {
|
||||
OptimizedSearch os;
|
||||
struct Case { std::string text; std::string pat; } cases[] = {
|
||||
{"", ""},
|
||||
{"", "a"},
|
||||
{"a", ""},
|
||||
{"a", "a"},
|
||||
{"aaaaa", "aa"},
|
||||
{"hello world", "world"},
|
||||
{"abcabcabc", "abc"},
|
||||
{"the quick brown fox", "fox"},
|
||||
};
|
||||
for (auto &c : cases) {
|
||||
auto got = os.find_all(c.text, c.pat, 0);
|
||||
auto ref = ref_find_all(c.text, c.pat);
|
||||
ASSERT_EQ(got, ref);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user