Scaffold: upstream @ b12d713, core submodule, test runner, example

This commit is contained in:
4DBug committed 2026-10-16 23:47:02 -05:00
commit 390f1cb687
22 files changed
+19789

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
.gitattributes export-ignore
tools/upstream/** linguist-vendored=true
+3
View File
@@ -0,0 +1,3 @@
[submodule "tools/core"]
path = tools/core
url = https://git.bug.tools/bug/imgui-luau.git
+23
View File
@@ -0,0 +1,23 @@
MIT License
Copyright (c) 2024-2026 Johan A. Goossens. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Luau port: Copyright (c) 2026 4DBug, same MIT terms.
+26
View File
@@ -0,0 +1,26 @@
# imguicolortextedit-luau
Syntax-highlighting text editor widget for imgui-luau (Roblox / LÖVE).
Luau port of [TextEditor](https://github.com/goossens/ImGuiColorTextEdit) for [imgui-luau](https://git.bug.tools/bug/imgui-luau) ([GitHub](https://github.com/4DBug/imgui-luau)).
Mirrors: [git.bug.tools](https://git.bug.tools/bug/imguicolortextedit-luau) / [GitHub](https://github.com/4DBug/imguicolortextedit-luau).
**Status: work in progress.**
```lua
local G = require(ReplicatedStorage.ImGui)
local TextEditor = require(ReplicatedStorage.TextEditor)(G)
```
## Development
```sh
git clone --recursive https://git.bug.tools/bug/imguicolortextedit-luau.git
bash tools/test.sh # tests/t_*.luau in the core's Roblox mock
```
Upstream source (pinned) is in `tools/upstream/`; port-specific comments are tagged `[Port]`.
## License
MIT, see LICENSE (upstream copyright kept).
+8
View File
@@ -0,0 +1,8 @@
-- TextEditor for imgui-luau. Port of https://github.com/goossens/ImGuiColorTextEdit (b12d713e77e8edddff1e69973f67085ac9cfaf74).
-- Usage: local TextEditor = require(path.to.TextEditor)(require(path.to.ImGui))
return function(G)
local ImGui, ImVec2, ImVec4 = G.ImGui, G.ImVec2, G.ImVec4
local TextEditor = {}
-- [Port] TODO: port from tools/upstream
return TextEditor
end
+11
View File
@@ -0,0 +1,11 @@
{
"name": "imguicolortextedit-luau",
"tree": {
"$className": "DataModel",
"ReplicatedStorage": {
"ImGui": { "$path": "tools/core/build/ImGuiTyped.luau", "Impl": { "$path": "tools/core/build/ImGui.luau" } },
"TextEditor": { "$path": "TextEditor.lua" }
},
"StarterPlayer": { "StarterPlayerScripts": { "TextEditorExample": { "$path": "examples/roblox/main.client.luau" } } }
}
}
+15
View File
@@ -0,0 +1,15 @@
local RS = game:GetService("ReplicatedStorage")
local RunService = game:GetService("RunService")
local G = require(RS:WaitForChild("ImGui"))
local TextEditor = require(RS:WaitForChild("TextEditor"))(G)
local ImGui = G.ImGui
ImGui.CreateContext()
G.ImGui_ImplRoblox.Init(game:GetService("Players").LocalPlayer:WaitForChild("PlayerGui"))
RunService.RenderStepped:Connect(function()
G.ImGui_ImplRoblox.NewFrame()
ImGui.NewFrame()
-- TextEditor example goes here
ImGui.Render()
G.ImGui_ImplRoblox.RenderDrawData(ImGui.GetDrawData())
end)
+5
View File
@@ -0,0 +1,5 @@
local RS = game:GetService("ReplicatedStorage")
local G = require(RS:WaitForChild("ImGui"))
local TextEditor = require(RS:WaitForChild("TextEditor"))(G)
assert(type(TextEditor) == "table", "module did not return a table")
print("OK")
Submodule
+1
Submodule tools/core added at 7cd2ee010a.
Executable
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
# Runs every tests/t_*.luau against the core (tools/core submodule) in the Roblox mock.
cd "$(dirname "$0")/.."
fail=0
for t in tests/t_*.luau; do
out=$(python3 tools/core/tools/test/run.py --module TextEditor=TextEditor.lua --main "$t" --quiet --roblox 2>&1)
if echo "$out" | grep -q "^OK"; then echo "PASS $t"; else echo "FAIL $t"; echo "$out" | tail -20; fail=1; fi
done
exit $fail
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2024-2026 Johan A. Goossens. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+859
View File
@@ -0,0 +1,859 @@
// TextDiff - A syntax highlighting text diff widget for Dear ImGui.
// Copyright (c) 2024-2026 Johan A. Goossens. All rights reserved.
//
// This work is licensed under the terms of the MIT license.
// For a copy, see <https://opensource.org/licenses/MIT>.
//
// Include files
//
#include <cmath>
#include "imgui_internal.h"
#include "dtl.h"
#include "TextDiff.h"
//
// TextDiff::TextDiff
//
TextDiff::TextDiff() {
SetPalette(TextEditor::GetDefaultPalette());
}
//
// TextDiff::SetText
//
void TextDiff::SetText(const std::string_view& left, const std::string_view& right) {
// split text into lines
std::vector<std::string_view> leftLines;
std::vector<std::string_view> rightLines;
splitLines(leftLines, left);
splitLines(rightLines, right);
// create two documents
diff.leftDocument.setUtf8Text(diff.config, leftLines);
diff.rightDocument.setUtf8Text(diff.config, rightLines);
// calculate the difference between the two documents
dtl::Diff<std::string_view> difference(leftLines, rightLines);
difference.compose();
auto ranges = difference.getSes().getSequence();
// determine status of each line in diff view
diff.state.clear();
size_t leftIndex = 0;
size_t rightIndex = 0;
for (auto& [text, info] : ranges) {
switch (info.type) {
case dtl::SES_COMMON:
diff.state.emplace_back(leftIndex++, rightIndex++, DiffType::common);
break;
case dtl::SES_ADD:
diff.state.emplace_back(leftIndex, rightIndex++, DiffType::added);
break;
case dtl::SES_DELETE:
diff.state.emplace_back(leftIndex++, rightIndex, DiffType::deleted);
break;
}
}
}
//
// TextDiff::Render
//
void TextDiff::Render(const char* title, const ImVec2& size, ImGuiChildFlags childFlags, ImGuiWindowFlags windowFlags) {
// update color palette (if required)
if (diff.paletteAlpha != ImGui::GetStyle().Alpha) {
updatePalette();
}
// update colorizer states (if required)
diff.leftColorizer.update(diff.config, diff.leftDocument);
diff.rightColorizer.update(diff.config, diff.rightDocument);
// ensure editor has focus (if required)
if (diff.focusOnDiff) {
ImGui::SetNextWindowFocus();
diff.focusOnDiff = false;
}
if (diff.sideBySideMode) {
// render a custom side-by-side view
sideBySideView.render(title, size, childFlags, windowFlags, diff);
} else {
// render combined view
integratedView.render(title, size, childFlags, windowFlags, diff);
}
// reset view mode
diff.previousSideBySideMode = diff.sideBySideMode;
// reset document state (if required)
if (diff.leftDocument.isUpdated()) {
diff.leftDocument.resetUpdated();
}
if (diff.rightDocument.isUpdated()) {
diff.rightDocument.resetUpdated();
}
}
//
// TextDiff::IntegratedView::render
//
void TextDiff::IntegratedView::render(const char* title, const ImVec2& size, ImGuiChildFlags childFlags, ImGuiWindowFlags windowFlags, Diff& diff) {
// get font information
font = ImGui::GetFont();
fontSize = ImGui::GetFontSize();
glyphSize = ImVec2(ImGui::CalcTextSize("#").x, ImGui::GetTextLineHeightWithSpacing() * diff.config.lineSpacing);
// start rendering the widget
ImGui::SetNextWindowContentSize(ImVec2(0.0f, glyphSize.y * rows.size()));
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0.0f, 0.0f));
ImGui::PushStyleColor(ImGuiCol_ChildBg, ImGui::ColorConvertU32ToFloat4(diff.palette.get(TextEditor::Color::background)));
ImGui::BeginChild(title, size, childFlags, windowFlags | ImGuiWindowFlags_HorizontalScrollbar);
// determine visible dimensions
drawList = ImGui::GetWindowDrawList();
cursorScreenPos = ImGui::GetCursorScreenPos();
const auto visibleSize = ImGui::GetContentRegionAvail();
leftLineNumberDigits = static_cast<int>(std::log10(diff.leftDocument.size() + 1) + 1.0f);
rightLineNumberDigits = static_cast<int>(std::log10(diff.rightDocument.size() + 1) + 1.0f);
lineNumberWidth = glyphSize.x * (leftLineNumberDigits + rightLineNumberDigits + 3);
textColumnWidth = visibleSize.x - lineNumberWidth;
textColumnWidth = std::floor(textColumnWidth / glyphSize.x) * glyphSize.x;
diff.config.wordWrapColumns = static_cast<size_t>(std::max(textColumnWidth / glyphSize.x, 0.0f));
// update typesetters and update layout (if required)
bool layoutChanged = false;
layoutChanged |= leftTypeSetter.update(diff.config, diff.leftDocument, leftLineFold);
layoutChanged |= rightTypeSetter.update(diff.config, diff.rightDocument, rightLineFold);
const bool viewChanged = diff.sideBySideMode != diff.previousSideBySideMode;
if (layoutChanged || viewChanged) {
updateLayout(diff);
}
// determine layout parameters
lineNumberPos = cursorScreenPos.x;
textPos = lineNumberPos + lineNumberWidth;
textEnd = textPos + textColumnWidth;
visibleRows = std::max(static_cast<int>(std::ceil(visibleSize.y / glyphSize.y)), 0);
visibleColumns = std::max(static_cast<int>(std::ceil(textColumnWidth / glyphSize.x)), 0);
firstVisibleRow = std::max(static_cast<int>(std::floor(ImGui::GetScrollY() / glyphSize.y)), 0);
lastVisibleRow = std::min(static_cast<int>(std::ceil((ImGui::GetScrollY() + visibleSize.y) / glyphSize.y)), static_cast<int>(rows.size() - 1));
firstVisibleColumn = std::max(static_cast<int>(std::floor(textScroll / glyphSize.x)), 0);
lastVisibleColumn = static_cast<int>(std::ceil((textScroll + textColumnWidth) / glyphSize.x));
firstRenderableColumn = (firstVisibleColumn / diff.config.tabSize) * diff.config.tabSize;
renderBackground(diff);
renderText(diff);
renderScrollbar();
renderMiniMap(diff);
ImGui::EndChild();
ImGui::PopStyleColor();
ImGui::PopStyleVar();
}
//
// TextDiff::IntegratedView::renderBackground
//
void TextDiff::IntegratedView::renderBackground(const Diff& diff) {
// render line numbers and text backgrounds
auto y = cursorScreenPos.y + firstVisibleRow * glyphSize.y;
char buffer[32];
for (auto i = firstVisibleRow; i <= lastVisibleRow; i++) {
const auto& row = rows[i];
const auto lineLeft = static_cast<int>(row.leftLine + 1);
const auto lineRight = static_cast<int>(row.rightLine + 1);
switch(row.type) {
case DiffType::common:
if (row.section == 0) {
snprintf(buffer, sizeof(buffer), " %*d %*d", leftLineNumberDigits, lineLeft, rightLineNumberDigits, lineRight);
drawList->AddText(ImVec2(lineNumberPos, y), diff.palette.get(TextEditor::Color::lineNumber), buffer);
}
break;
case DiffType::added:
if (row.section == 0) {
snprintf(buffer, sizeof(buffer), " %*s %*d +", leftLineNumberDigits, "", rightLineNumberDigits, lineRight);
drawList->AddText(ImVec2(lineNumberPos, y), diff.palette.get(TextEditor::Color::lineNumber), buffer);
}
drawList->AddRectFilled(ImVec2(lineNumberPos, y),ImVec2(textEnd, y + glyphSize.y), diff.addedColor);
break;
case DiffType::deleted:
if (row.section == 0) {
snprintf(buffer, sizeof(buffer), " %*d %*s -", leftLineNumberDigits, lineLeft, rightLineNumberDigits, "");
drawList->AddText(ImVec2(lineNumberPos, y), diff.palette.get(TextEditor::Color::lineNumber), buffer);
}
drawList->AddRectFilled(ImVec2(lineNumberPos, y), ImVec2(textEnd, y + glyphSize.y), diff.deletedColor);
break;
}
y += glyphSize.y;
}
}
//
// TextDiff::IntegratedView::renderText
//
void TextDiff::IntegratedView::renderText(const Diff& diff) {
// setup rendering
const auto yTop = drawList->GetClipRectMin().y;
auto yBottom = drawList->GetClipRectMax().y;
if (maxColumns * glyphSize.x > textColumnWidth) {
yBottom -= ImGui::GetStyle().ScrollbarSize + ImGui::GetCurrentWindow()->WindowBorderSize;
}
// render left text
drawList->PushClipRect(ImVec2(textPos, yTop), ImVec2(textEnd, yBottom), false);
for (auto i = firstVisibleRow; i <= lastVisibleRow; i++) {
const auto& row = rows[i];
const auto y = cursorScreenPos.y + i * glyphSize.y;
switch(row.type) {
case DiffType::common:
case DiffType::deleted:
renderLine(textPos, y, diff.leftDocument[row.leftLine], row.section, diff);
break;
case DiffType::added:
renderLine(textPos, y, diff.rightDocument[row.rightLine], row.section, diff);
break;
}
}
drawList->PopClipRect();
}
//
// TextDiff::IntegratedView::renderLine
//
void TextDiff::IntegratedView::renderLine(float x, float y, const TextEditor::Line& line, size_t sectionNo, const Diff& diff) {
// determine visible boundaries for this row
size_t index;
size_t column;
size_t endColumn;
if (diff.config.wordWrap && line.sections) {
const auto& section = line.sections->at(sectionNo);
index = section.startIndex;
column = section.indent;
endColumn = section.columns;
} else {
index = 0;
column = 0;
endColumn = line.columns;
}
// only process all visible columns
while (column < endColumn && column <= lastVisibleColumn) {
const auto& glyph = line[index++];
const auto codepoint = glyph.codepoint;
const ImVec2 glyphPos(x + column * glyphSize.x - textScroll, y);
// handle tabs
if (codepoint == '\t') {
if (diff.config.showTabs && column >= firstRenderableColumn) {
const auto x1 = glyphPos.x + glyphSize.x * 0.3f;
const auto y1 = glyphPos.y + fontSize * 0.5f;
const auto x2 = glyphPos.x + glyphSize.x;
const auto p1 = ImVec2(x1, y1);
const auto p2 = ImVec2(x2, y1);
const auto p3 = ImVec2(x2 - fontSize * 0.16f, y1 - fontSize * 0.16f);
const auto p4 = ImVec2(x2 - fontSize * 0.16f, y1 + fontSize * 0.16f);
drawList->AddLine(p1, p2, diff.palette.get(TextEditor::Color::whitespace));
drawList->AddLine(p2, p3, diff.palette.get(TextEditor::Color::whitespace));
drawList->AddLine(p2, p4, diff.palette.get(TextEditor::Color::whitespace));
}
// handle spaces
} else if (codepoint == ' ') {
if (diff.config.showSpaces && column >= firstRenderableColumn) {
const auto x1 = glyphPos.x + glyphSize.x * 0.5f;
const auto y1 = glyphPos.y + fontSize * 0.5f;
drawList->AddCircleFilled(ImVec2(x1, y1), 1.5f, diff.palette.get(TextEditor::Color::whitespace), 4);
}
// handle regular glyphs
} else {
if (column >= firstRenderableColumn) {
font->RenderChar(drawList, fontSize, glyphPos, diff.palette.get(glyph.color), codepoint);
}
}
column += glyph.columns;
}
}
//
// TextDiff::IntegratedView::renderScrollbar
//
void TextDiff::IntegratedView::renderScrollbar() {
const auto maxColumnsWidth = maxColumns * glyphSize.x;
if (maxColumnsWidth > textColumnWidth) {
const auto window = ImGui::GetCurrentWindow();
const auto outerRect = window->Rect();
const auto borderSize = std::round(window->WindowBorderSize * 0.5f);
const auto scrollbarSize = ImGui::GetStyle().ScrollbarSize;
const auto scrollbarTop = std::max(outerRect.Min.y + borderSize, outerRect.Max.y - borderSize - scrollbarSize);
const ImRect scrollbarFrame(textPos, scrollbarTop, textEnd, scrollbarTop + scrollbarSize);
ImS64 scroll = static_cast<ImS64>(textScroll);
if (ImGui::ScrollbarEx(
scrollbarFrame,
ImGui::GetID("textScroll"),
ImGuiAxis_X,
&scroll,
static_cast<ImS64>(textColumnWidth),
static_cast<ImS64>(maxColumnsWidth),
ImDrawFlags_RoundCornersAll)) {
textScroll = static_cast<float>(scroll);
}
textScroll = std::clamp(textScroll - ImGui::GetIO().MouseWheelH * ImGui::GetFontSize(), 0.0f, maxColumnsWidth - textColumnWidth);
if (ImGui::Shortcut(ImGuiKey_LeftArrow, ImGuiInputFlags_Repeat)) { textScroll = std::max(textScroll - glyphSize.x, 0.0f); }
else if (ImGui::Shortcut(ImGuiKey_RightArrow, ImGuiInputFlags_Repeat)) { textScroll = std::min(textScroll + glyphSize.x, maxColumnsWidth - textColumnWidth); }
else if (ImGui::Shortcut(ImGuiKey_Home)) { textScroll = 0.0f; }
else if (ImGui::Shortcut(ImGuiKey_End)) { textScroll = maxColumnsWidth - textColumnWidth; }
} else {
// no scrolling if the text fits
textScroll = 0.0f;
}
if (ImGui::Shortcut(ImGuiKey_UpArrow, ImGuiInputFlags_Repeat)) { ImGui::SetScrollY(std::max(ImGui::GetScrollY() - glyphSize.y, 0.0f)); }
else if (ImGui::Shortcut(ImGuiMod_Ctrl | ImGuiKey_UpArrow)) { ImGui::SetScrollY(0.0f); }
else if (ImGui::Shortcut(ImGuiKey_DownArrow, ImGuiInputFlags_Repeat)) { ImGui::SetScrollY(std::min(ImGui::GetScrollY() + glyphSize.y, ImGui::GetScrollMaxY())); }
else if (ImGui::Shortcut(ImGuiMod_Ctrl | ImGuiKey_DownArrow)) { ImGui::SetScrollY(ImGui::GetScrollMaxY()); }
else if (ImGui::Shortcut(ImGuiKey_PageUp, ImGuiInputFlags_Repeat)) { ImGui::SetScrollY(std::max(ImGui::GetScrollY() - (visibleRows - 2) * glyphSize.y, 0.0f)); }
else if (ImGui::Shortcut(ImGuiKey_PageDown, ImGuiInputFlags_Repeat)) { ImGui::SetScrollY(std::min(ImGui::GetScrollY() + (visibleRows - 2) * glyphSize.y, ImGui::GetScrollMaxY())); }
}
//
// TextDiff::IntegratedView::renderMiniMap
//
void TextDiff::IntegratedView::renderMiniMap(const Diff& diff) {
// based on https://github.com/ocornut/imgui/issues/3114
if (diff.config.showScrollbarMiniMap) {
auto window = ImGui::GetCurrentWindow();
if (window->ScrollbarY) {
const auto rect = ImGui::GetWindowScrollbarRect(window, ImGuiAxis_Y);
const auto rowHeight = rect.GetHeight() / static_cast<float>(rows.size());
const auto offset = (rect.Max.x - rect.Min.x) * 0.3f;
const auto left = rect.Min.x + offset;
const auto right = rect.Max.x - offset;
drawList->PushClipRect(rect.Min, rect.Max, false);
// render diff locations
for (size_t i = 0; i < rows.size(); i++) {
const auto& row = rows[i];
if (row.type != DiffType::common) {
const auto color = (row.type == DiffType::added) ? diff.addedColor : diff.deletedColor;
const auto ly = std::round(rect.Min.y + i * rowHeight);
drawList->AddRectFilled(ImVec2(left, ly), ImVec2(right, ly + rowHeight), color);
}
}
drawList->PopClipRect();
}
}
}
//
// TextDiff::IntegratedView::updateLayout
//
void TextDiff::IntegratedView::updateLayout(Diff& diff) {
rows.clear();
maxColumns = 0;
for (const auto& lineState : diff.state) {
auto& line = lineState.type == DiffType::added
? diff.rightDocument[lineState.rightLine]
: diff.leftDocument[lineState.leftLine];
if (line.rows > 10) {
line.rows = 10;
}
for (size_t i = 0; i < line.rows; i++) {
rows.emplace_back(lineState.type, lineState.leftLine, lineState.rightLine, i, line.columns);
}
maxColumns = std::max(maxColumns, line.columns);
}
}
//
// TextDiff::SideBySideView::render
//
void TextDiff::SideBySideView::render(const char* title, const ImVec2& size, ImGuiChildFlags childFlags, ImGuiWindowFlags windowFlags, Diff& diff) {
// get font information
font = ImGui::GetFont();
fontSize = ImGui::GetFontSize();
glyphSize = ImVec2(ImGui::CalcTextSize("#").x, ImGui::GetTextLineHeightWithSpacing() * diff.config.lineSpacing);
// start rendering the widget
ImGui::SetNextWindowContentSize(ImVec2(0.0f, glyphSize.y * rows.size()));
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0.0f, 0.0f));
ImGui::PushStyleColor(ImGuiCol_ChildBg, ImGui::ColorConvertU32ToFloat4(diff.palette.get(TextEditor::Color::background)));
ImGui::BeginChild(title, size, childFlags, windowFlags);
// determine visible dimensions
cursorScreenPos = ImGui::GetCursorScreenPos();
drawList = ImGui::GetWindowDrawList();
const auto visibleSize = ImGui::GetContentRegionAvail();
leftLineNumberDigits = static_cast<int>(std::log10(diff.leftDocument.size() + 1) + 1.0f);
rightLineNumberDigits = static_cast<int>(std::log10(diff.rightDocument.size() + 1) + 1.0f);
leftLineNumberWidth = glyphSize.x * (leftLineNumberDigits + 4);
rightLineNumberWidth = glyphSize.x * (rightLineNumberDigits + 4);
textColumnWidth = static_cast<float>(visibleSize.x - leftLineNumberWidth - rightLineNumberWidth) / 2.0f;
textColumnWidth = std::floor(textColumnWidth / glyphSize.x) * glyphSize.x;
diff.config.wordWrapColumns = static_cast<size_t>(std::max(textColumnWidth / glyphSize.x, 0.0f));
// update typesetters and update layout (if required)
bool layoutChanged = false;
layoutChanged |= leftTypeSetter.update(diff.config, diff.leftDocument, leftLineFold);
layoutChanged |= rightTypeSetter.update(diff.config, diff.rightDocument, rightLineFold);
const bool viewChanged = diff.sideBySideMode != diff.previousSideBySideMode;
if (layoutChanged || viewChanged) {
updateLayout(diff);
}
// determine layout parameters
leftLineNumberPos = cursorScreenPos.x;
leftTextPos = leftLineNumberPos + leftLineNumberWidth;
rightLineNumberPos = leftTextPos + textColumnWidth;
rightTextPos = rightLineNumberPos + rightLineNumberWidth;
rightTextEnd = rightTextPos + textColumnWidth;
visibleRows = std::max(static_cast<int>(std::ceil(visibleSize.y / glyphSize.y)), 0);
visibleColumns = std::max(static_cast<int>(std::ceil(textColumnWidth / glyphSize.x)), 0);
firstVisibleRow = std::max(static_cast<int>(std::floor(ImGui::GetScrollY() / glyphSize.y)), 0);
lastVisibleRow = std::min(static_cast<int>(std::floor((ImGui::GetScrollY() + visibleSize.y) / glyphSize.y)), static_cast<int>(rows.size() - 1));
firstVisibleColumn = std::max(static_cast<int>(std::floor(textScroll / glyphSize.x)), 0);
lastVisibleColumn = static_cast<int>(std::floor((textScroll + textColumnWidth) / glyphSize.x));
firstRenderableColumn = (firstVisibleColumn / diff.config.tabSize) * diff.config.tabSize;
renderBackground(diff);
renderText(diff);
renderScrollbars();
renderMiniMap(diff);
ImGui::EndChild();
ImGui::PopStyleColor();
ImGui::PopStyleVar();
}
//
// TextDiff::SideBySideView::renderBackground
//
void TextDiff::SideBySideView::renderBackground(const Diff& diff) {
// render line numbers and text backgrounds
auto y = cursorScreenPos.y + firstVisibleRow * glyphSize.y;
char buffer[32];
for (auto i = firstVisibleRow; i <= lastVisibleRow; i++) {
const auto& row = rows[i];
const auto lineLeft = static_cast<int>(row.leftLine + 1);
const auto lineRight = static_cast<int>(row.rightLine + 1);
switch(row.type) {
case DiffType::common:
if (row.leftSection == 0) {
snprintf(buffer, sizeof(buffer), " %*d", leftLineNumberDigits, lineLeft);
drawList->AddText(ImVec2(leftLineNumberPos, y), diff.palette.get(TextEditor::Color::lineNumber), buffer);
snprintf(buffer, sizeof(buffer), " %*d", rightLineNumberDigits, lineRight);
drawList->AddText(ImVec2(rightLineNumberPos, y), diff.palette.get(TextEditor::Color::lineNumber), buffer);
}
break;
case DiffType::added:
if (row.rightSection == 0) {
snprintf(buffer, sizeof(buffer), " %*d +", rightLineNumberDigits, lineRight);
drawList->AddText(ImVec2(rightLineNumberPos, y), diff.palette.get(TextEditor::Color::lineNumber), buffer);
}
drawList->AddRectFilled(
ImVec2(rightTextPos, y),
ImVec2(rightTextEnd, y + glyphSize.y),
diff.addedColor);
break;
case DiffType::deleted:
if (row.leftSection == 0) {
snprintf(buffer, sizeof(buffer), " %*d -", leftLineNumberDigits, lineLeft);
drawList->AddText(ImVec2(leftLineNumberPos, y), diff.palette.get(TextEditor::Color::lineNumber), buffer);
}
drawList->AddRectFilled(
ImVec2(leftTextPos, y),
ImVec2(rightLineNumberPos, y + glyphSize.y),
diff.deletedColor);
break;
}
y += glyphSize.y;
}
}
//
// TextDiff::SideBySideView::renderText
//
void TextDiff::SideBySideView::renderText(const Diff& diff) {
// setup rendering
const auto yTop = drawList->GetClipRectMin().y;
auto yBottom = drawList->GetClipRectMax().y;
if (maxColumns * glyphSize.x > textColumnWidth) {
yBottom -= ImGui::GetStyle().ScrollbarSize + ImGui::GetCurrentWindow()->WindowBorderSize;
}
// render left text
drawList->PushClipRect(ImVec2(leftTextPos, yTop), ImVec2(rightLineNumberPos, yBottom), false);
for (auto i = firstVisibleRow; i <= lastVisibleRow; i++) {
const auto& row = rows[i];
const auto y = cursorScreenPos.y + i * glyphSize.y;
switch(row.type) {
case DiffType::common:
case DiffType::deleted:
renderLine(leftTextPos, y, diff.leftDocument[row.leftLine], row.leftSection, diff);
break;
case DiffType::added:
break;
}
}
drawList->PopClipRect();
// render right text
drawList->PushClipRect(ImVec2(rightTextPos, yTop), ImVec2(rightTextEnd, yBottom), false);
for (auto i = firstVisibleRow; i <= lastVisibleRow; i++) {
const auto& row = rows[i];
const auto y = cursorScreenPos.y + i * glyphSize.y;
switch(row.type) {
case DiffType::common:
case DiffType::added:
renderLine(rightTextPos, y, diff.rightDocument[row.rightLine], row.rightSection, diff);
break;
case DiffType::deleted:
break;
}
}
drawList->PopClipRect();
}
//
// TextDiff::SideBySideView::renderLine
//
void TextDiff::SideBySideView::renderLine(float x, float y, const TextEditor::Line& line, size_t sectionNo, const Diff& diff) {
// determine visible boundaries for this row
size_t index;
size_t column;
size_t endColumn;
if (diff.config.wordWrap && line.sections) {
const auto& section = line.sections->at(sectionNo);
index = section.startIndex;
column = section.indent;
endColumn = section.columns;
} else {
index = 0;
column = 0;
endColumn = line.columns;
}
// only process all visible columns
while (column < endColumn && column <= lastVisibleColumn) {
const auto& glyph = line[index++];
const auto codepoint = glyph.codepoint;
const ImVec2 glyphPos(x + column * glyphSize.x - textScroll, y);
// handle tabs
if (codepoint == '\t') {
if (diff.config.showTabs && column >= firstRenderableColumn) {
const auto x1 = glyphPos.x + glyphSize.x * 0.3f;
const auto y1 = glyphPos.y + fontSize * 0.5f;
const auto x2 = glyphPos.x + glyphSize.x;
const auto p1 = ImVec2(x1, y1);
const auto p2 = ImVec2(x2, y1);
const auto p3 = ImVec2(x2 - fontSize * 0.16f, y1 - fontSize * 0.16f);
const auto p4 = ImVec2(x2 - fontSize * 0.16f, y1 + fontSize * 0.16f);
drawList->AddLine(p1, p2, diff.palette.get(TextEditor::Color::whitespace));
drawList->AddLine(p2, p3, diff.palette.get(TextEditor::Color::whitespace));
drawList->AddLine(p2, p4, diff.palette.get(TextEditor::Color::whitespace));
}
// handle spaces
} else if (codepoint == ' ') {
if (diff.config.showSpaces && column >= firstRenderableColumn) {
const auto x1 = glyphPos.x + glyphSize.x * 0.5f;
const auto y1 = glyphPos.y + fontSize * 0.5f;
drawList->AddCircleFilled(ImVec2(x1, y1), 1.5f, diff.palette.get(TextEditor::Color::whitespace), 4);
}
// handle regular glyphs
} else {
if (column >= firstRenderableColumn) {
font->RenderChar(drawList, fontSize, glyphPos, diff.palette.get(glyph.color), codepoint);
}
}
column += glyph.columns;
}
}
//
// TextDiff::SideBySideView::renderScrollbars
//
void TextDiff::SideBySideView::renderScrollbars() {
const auto maxColumnsWidth = maxColumns * glyphSize.x;
if (maxColumnsWidth > textColumnWidth) {
const auto window = ImGui::GetCurrentWindow();
const auto outerRect = window->Rect();
const auto borderSize = std::round(window->WindowBorderSize * 0.5f);
const auto scrollbarSize = ImGui::GetStyle().ScrollbarSize;
const auto scrollbarTop = std::max(outerRect.Min.y + borderSize, outerRect.Max.y - borderSize - scrollbarSize);
const ImRect leftScrollbarFrame(leftTextPos, scrollbarTop, rightLineNumberPos, scrollbarTop + scrollbarSize);
const ImRect rightScrollbarFrame(rightTextPos, scrollbarTop, rightTextEnd, scrollbarTop + scrollbarSize);
ImS64 scroll = static_cast<ImS64>(textScroll);
if (ImGui::ScrollbarEx(
leftScrollbarFrame,
ImGui::GetID("leftTextScroll"),
ImGuiAxis_X,
&scroll,
static_cast<ImS64>(textColumnWidth),
static_cast<ImS64>(maxColumnsWidth),
ImDrawFlags_RoundCornersAll)) {
textScroll = static_cast<float>(scroll);
}
if (ImGui::ScrollbarEx(
rightScrollbarFrame,
ImGui::GetID("rightTextScroll"),
ImGuiAxis_X,
&scroll,
static_cast<ImS64>(textColumnWidth),
static_cast<ImS64>(maxColumnsWidth),
ImDrawFlags_RoundCornersAll)) {
textScroll = static_cast<float>(scroll);
}
textScroll = std::clamp(textScroll - ImGui::GetIO().MouseWheelH * ImGui::GetFontSize(), 0.0f, maxColumnsWidth - textColumnWidth);
if (ImGui::Shortcut(ImGuiKey_LeftArrow, ImGuiInputFlags_Repeat)) { textScroll = std::max(textScroll - glyphSize.x, 0.0f); }
else if (ImGui::Shortcut(ImGuiKey_RightArrow, ImGuiInputFlags_Repeat)) { textScroll = std::min(textScroll + glyphSize.x, maxColumnsWidth - textColumnWidth); }
else if (ImGui::Shortcut(ImGuiKey_Home)) { textScroll = 0.0f; }
else if (ImGui::Shortcut(ImGuiKey_End)) { textScroll = maxColumnsWidth - textColumnWidth; }
} else {
// no scrolling if the text fits
textScroll = 0.0f;
}
if (ImGui::Shortcut(ImGuiKey_UpArrow, ImGuiInputFlags_Repeat)) { ImGui::SetScrollY(std::max(ImGui::GetScrollY() - glyphSize.y, 0.0f)); }
else if (ImGui::Shortcut(ImGuiMod_Ctrl | ImGuiKey_UpArrow)) { ImGui::SetScrollY(0.0f); }
else if (ImGui::Shortcut(ImGuiKey_DownArrow, ImGuiInputFlags_Repeat)) { ImGui::SetScrollY(std::min(ImGui::GetScrollY() + glyphSize.y, ImGui::GetScrollMaxY())); }
else if (ImGui::Shortcut(ImGuiMod_Ctrl | ImGuiKey_DownArrow)) { ImGui::SetScrollY(ImGui::GetScrollMaxY()); }
else if (ImGui::Shortcut(ImGuiKey_PageUp, ImGuiInputFlags_Repeat)) { ImGui::SetScrollY(std::max(ImGui::GetScrollY() - (visibleRows - 2) * glyphSize.y, 0.0f)); }
else if (ImGui::Shortcut(ImGuiKey_PageDown, ImGuiInputFlags_Repeat)) { ImGui::SetScrollY(std::min(ImGui::GetScrollY() + (visibleRows - 2) * glyphSize.y, ImGui::GetScrollMaxY())); }
}
//
// TextDiff::SideBySideView::renderMiniMap
//
void TextDiff::SideBySideView::renderMiniMap(const Diff& diff) {
// based on https://github.com/ocornut/imgui/issues/3114
if (diff.config.showScrollbarMiniMap) {
const auto window = ImGui::GetCurrentWindow();
if (window->ScrollbarY) {
const auto rect = ImGui::GetWindowScrollbarRect(window, ImGuiAxis_Y);
const auto rowHeight = rect.GetHeight() / static_cast<float>(rows.size());
const auto offset = (rect.Max.x - rect.Min.x) * 0.3f;
const auto left = rect.Min.x + offset;
const auto right = rect.Max.x - offset;
drawList->PushClipRect(rect.Min, rect.Max, false);
// render diff locations
for (size_t i = 0; i < rows.size(); i++) {
const auto& row = rows[i];
if (row.type != DiffType::common) {
const auto color = (row.type == DiffType::added) ? diff.addedColor : diff.deletedColor;
const auto ly = std::round(rect.Min.y + i * rowHeight);
drawList->AddRectFilled(ImVec2(left, ly), ImVec2(right, ly + rowHeight), color);
}
}
drawList->PopClipRect();
}
}
}
//
// TextDiff::SideBySideView::updateLayout
//
void TextDiff::SideBySideView::updateLayout(Diff& diff) {
rows.clear();
maxColumns = 0;
for (const auto& lineState : diff.state) {
switch (lineState.type) {
case DiffType::common: {
const auto& line = diff.leftDocument[lineState.leftLine];
for (size_t i = 0; i < line.rows; i++) {
rows.emplace_back(lineState.type, lineState.leftLine, i, lineState.rightLine, i, line.columns);
}
maxColumns = std::max(maxColumns, line.columns);
break;
}
case DiffType::added: {
const auto& line = diff.rightDocument[lineState.rightLine];
for (size_t i = 0; i < line.rows; i++) {
rows.emplace_back(lineState.type, 0, 0, lineState.rightLine, i, line.columns);
}
maxColumns = std::max(maxColumns, line.columns);
break;
}
case DiffType::deleted: {
const auto& line = diff.leftDocument[lineState.leftLine];
for (size_t i = 0; i < line.rows; i++) {
rows.emplace_back(lineState.type, lineState.leftLine, i, 0, 0, line.columns);
}
maxColumns = std::max(maxColumns, line.columns);
break;
}
}
}
}
//
// TextDiff::splitLines
//
void TextDiff::splitLines(std::vector<std::string_view>& result, const std::string_view& text) {
size_t prev = TextEditor::CodePoint::skipBOM(text.begin(), text.end()) - text.begin();
size_t pos;
while ((pos = text.find('\n', prev)) != std::string_view::npos) {
result.push_back(text.substr(prev, pos - prev));
prev = pos + 1;
}
result.push_back(text.substr(prev));
}
//
// TextDiff::updatePalette
//
void TextDiff::updatePalette() {
// Update palette with the current alpha from style
diff.paletteAlpha = ImGui::GetStyle().Alpha;
for (size_t i = 0; i < static_cast<size_t>(TextEditor::Color::count); i++) {
auto color = ImGui::ColorConvertU32ToFloat4(diff.paletteBase[i]);
color.w *= diff.paletteAlpha;
diff.palette[i] = ImGui::ColorConvertFloat4ToU32(color);
}
}
+248
View File
@@ -0,0 +1,248 @@
// TextDiff - A syntax highlighting text diff widget for Dear ImGui.
// Copyright (c) 2024-2026 Johan A. Goossens. All rights reserved.
//
// This work is licensed under the terms of the MIT license.
// For a copy, see <https://opensource.org/licenses/MIT>.
#pragma once
//
// Include files
//
#include "TextEditor.h"
//
// TextDiff
//
class IMGUI_API TextDiff {
public:
// constructor
TextDiff();
// specify options
inline void SetSideBySideMode(bool flag) { diff.sideBySideMode = flag; }
inline bool GetSideBySideMode() const { return diff.sideBySideMode; }
inline void SetTabSize(size_t value) { diff.config.tabSize = value; }
inline size_t GetTabSize() const { return diff.config.tabSize; }
inline void SetLineSpacing(float value) { diff.config.lineSpacing = std::max(1.0f, std::min(2.0f, value)); }
inline float GetLineSpacing() const { return diff.config.lineSpacing; }
inline void SetWordWrapEnabled(bool value) { diff.config.wordWrap = value; }
inline bool IsWordWrapEnabled() const { return diff.config.wordWrap; }
inline void SetShowWhitespacesEnabled(bool value) { diff.config.showSpaces = value; diff.config.showTabs = value; }
inline bool IsShowWhitespacesEnabled() const { return diff.config.showSpaces && diff.config.showTabs; }
inline void SetShowSpacesEnabled(bool value) { diff.config.showSpaces = value; }
inline bool IsShowSpacesEnabled() const { return diff.config.showSpaces; }
inline void SetShowTabsEnabled(bool value) { diff.config.showTabs = value; }
inline bool IsShowTabsEnabled() const { return diff.config.showTabs; }
inline void SetShowScrollbarMiniMapEnabled(bool value) { diff.config.showScrollbarMiniMap = value; }
inline bool IsShowScrollbarMiniMapEnabled() const { return diff.config.showScrollbarMiniMap; }
inline void SetLanguage(const TextEditor::Language* language) { diff.config.language = language; }
inline const TextEditor::Language* GetLanguage() const { return diff.config.language; };
inline void SetColors(ImU32 ac, ImU32 dc) { diff.addedColor = ac; diff.deletedColor = dc; }
inline void SetPalette(const TextEditor::Palette& newPalette) { diff.paletteBase = newPalette; diff.paletteAlpha = -1.0f; }
inline const TextEditor::Palette& GetPalette() const { return diff.paletteBase; }
// programmatically set focus on the editor
inline void SetFocus() { diff.focusOnDiff = true; }
// specify the text to be compared (using UTF-8 encoded strings)
void SetText(const std::string_view& left, const std::string_view& right);
// render text diff in a Dear ImGui context
// note: if you overwrite windowFlags to for instance add ImGuiWindowFlags_NoSavedSettings
// ensure you keep the default as it is required for the diff widget
// - ImGuiWindowFlags_NoMove to ensure mouse drag event are passed to the diff widget
void Render(const char* title, const ImVec2& size=ImVec2(), ImGuiChildFlags childFlags=0, ImGuiWindowFlags windowFlags=ImGuiWindowFlags_NoMove);
private:
// information about a single line
enum class DiffType {
common,
added,
deleted
};
class LineState {
public:
LineState(size_t leftLine, size_t rightLine, DiffType type) : leftLine(leftLine), rightLine(rightLine), type(type) {}
size_t leftLine;
size_t rightLine;
DiffType type;
};
// diff context
struct Diff {
// options
bool sideBySideMode = false;
bool previousSideBySideMode = false;
TextEditor::Config config;
bool focusOnDiff = false;
// the two documents being compared
TextEditor::Document leftDocument;
TextEditor::Document rightDocument;
// coloring supports
TextEditor::Colorizer leftColorizer;
TextEditor::Colorizer rightColorizer;
// difference between the two documents
std::vector<LineState> state;
// colors
ImU32 addedColor = IM_COL32(0, 150, 32, 128);
ImU32 deletedColor = IM_COL32(180, 0, 32, 128);
// color palette support
TextEditor::Palette paletteBase;
TextEditor::Palette palette;
float paletteAlpha;
} diff;
// integrated rendering state
struct IntegratedView {
// visual layout
struct Row {
Row() = default;
Row(DiffType type, size_t leftLine, size_t rightLine, size_t section, size_t columns) :
type(type), leftLine(leftLine), rightLine(rightLine), section(section), columns(columns) {}
DiffType type;
size_t leftLine;
size_t rightLine;
size_t section;
size_t columns;
};
std::vector<Row> rows;
// rendering context
ImDrawList* drawList;
ImVec2 cursorScreenPos;
ImFont* font;
float fontSize;
ImVec2 glyphSize;
int leftLineNumberDigits;
int rightLineNumberDigits;
float lineNumberWidth;
float textColumnWidth;
float lineNumberPos;
float textPos;
float textEnd;
float textScroll;
size_t visibleRows;
size_t visibleColumns;
size_t maxColumns = 0;
size_t firstVisibleRow;
size_t lastVisibleRow;
size_t firstVisibleColumn;
size_t lastVisibleColumn;
size_t firstRenderableColumn;
// layout support
TextEditor::LineFold leftLineFold;
TextEditor::LineFold rightLineFold;
TextEditor::TypeSetter leftTypeSetter;
TextEditor::TypeSetter rightTypeSetter;
// rendering functions
void render(const char* title, const ImVec2& size, ImGuiChildFlags childFlags, ImGuiWindowFlags windowFlags, Diff& diff);
void renderBackground(const Diff& diff);
void renderText(const Diff& diff);
void renderLine(float x, float y, const TextEditor::Line& line, size_t section, const Diff& diff);
void renderScrollbar();
void renderMiniMap(const Diff& diff);
// layout functions
void updateLayout(Diff& diff);
} integratedView;
// side-by-side rendering state
struct SideBySideView {
// visual layout
struct Row {
Row() = default;
Row(DiffType type, size_t leftLine, size_t leftSection, size_t rightLine, size_t rightSection, size_t columns) :
type(type),
leftLine(leftLine), leftSection(leftSection),
rightLine(rightLine), rightSection(rightSection),
columns(columns) {}
DiffType type;
size_t leftLine;
size_t leftSection;
size_t rightLine;
size_t rightSection;
size_t columns;
};
std::vector<Row> rows;
// rendering context
ImDrawList* drawList;
ImVec2 cursorScreenPos;
ImFont* font;
float fontSize;
ImVec2 glyphSize;
int leftLineNumberDigits;
int rightLineNumberDigits;
float leftLineNumberWidth;
float rightLineNumberWidth;
float textColumnWidth;
float leftLineNumberPos;
float leftTextPos;
float rightLineNumberPos;
float rightTextPos;
float rightTextEnd;
float textScroll;
size_t visibleRows;
size_t visibleColumns;
size_t maxColumns = 0;
size_t firstVisibleRow;
size_t lastVisibleRow;
size_t firstVisibleColumn;
size_t lastVisibleColumn;
size_t firstRenderableColumn;
// layout support
TextEditor::LineFold leftLineFold;
TextEditor::LineFold rightLineFold;
TextEditor::TypeSetter leftTypeSetter;
TextEditor::TypeSetter rightTypeSetter;
// rendering functions
void render(const char* title, const ImVec2& size, ImGuiChildFlags childFlags, ImGuiWindowFlags windowFlags, Diff& diff);
void renderBackground(const Diff& diff);
void renderText(const Diff& diff);
void renderLine(float x, float y, const TextEditor::Line& line, size_t section, const Diff& diff);
void renderScrollbars();
void renderMiniMap(const Diff& diff);
// layout functions
void updateLayout(Diff& diff);
} sideBySideView;
// split string into lines
static void splitLines(std::vector<std::string_view>& result, const std::string_view& text);
// update the color palette
void updatePalette();
};
+14241
View File
File diff suppressed because it is too large. Load diff
+2117
View File
File diff suppressed because it is too large. Load diff
+1
View File
@@ -0,0 +1 @@
https://github.com/goossens/ImGuiColorTextEdit @ b12d713e77e8edddff1e69973f67085ac9cfaf74
+1284
View File
File diff suppressed because it is too large. Load diff
+457
View File
@@ -0,0 +1,457 @@
// TextEditor - A syntax highlighting text editor for Dear ImGui.
// Copyright (c) 2024-2026 Johan A. Goossens. All rights reserved.
//
// This work is licensed under the terms of the MIT license.
// For a copy, see <https://opensource.org/licenses/MIT>.
//
// Include files
//
#include <iostream>
#include <sstream>
#include <utility>
#include "lsp/messages.h"
#include "LspBridge.h"
//
// LspBridge::LspBridge
//
LspBridge::LspBridge() {
}
//
// LspBridge::~LspBridge
//
LspBridge::~LspBridge() {
if (IsRunning()) {
Stop();
}
}
//
// LspBridge::Start
//
bool LspBridge::Start(const std::string& rootPath, const std::string& executable, const std::vector<std::string>& args) {
try {
// start a new language server
process = lsp::Process(executable, args);
connection = std::make_unique<lsp::Connection>(process.stdIO());
messageHandler = std::make_unique<lsp::MessageHandler>(*connection);
running.store(true);
// start a thread to handle message exchanges
messageThread = std::thread([this](){
messageLoop();
});
// setup initialize params with client capabilities
auto initializeParams = lsp::requests::Initialize::Params();
initializeParams.processId = lsp::Process::currentProcessId();
initializeParams.rootUri = lsp::DocumentUri::fromPath(rootPath);
initializeParams.capabilities = {
.textDocument = lsp::TextDocumentClientCapabilities {
// .completion = lsp::CompletionClientCapabilities {
// .completionItem = lsp::CompletionClientCapabilitiesCompletionItem {
// .insertTextModeSupport = lsp::CompletionClientCapabilitiesCompletionItemInsertTextModeSupport {
// .valueSet = lsp::Array<lsp::InsertTextModeEnum>{
// lsp::InsertTextMode::AsIs
// }
// }
// }
// },
.hover = lsp::HoverClientCapabilities {
.contentFormat = {
{lsp::MarkupKind::PlainText}
}
}
},
.general = lsp::GeneralClientCapabilities {
.positionEncodings = lsp::Array<lsp::PositionEncodingKindEnum>{
lsp::PositionEncodingKind::UTF32
}
}
};
// send initialize request to the server and wait for the response
auto initializeRequest = messageHandler->sendRequest<lsp::requests::Initialize>(std::move(initializeParams));
auto initializeResult = initializeRequest.result.get();
serverCapabilities = std::move(initializeResult.capabilities);
// send the 'initialized' notification to let the server know that the client is ready
messageHandler->sendNotification<lsp::notifications::Initialized>({});
return true;
} catch(const std::exception& e) {
std::stringstream ss;
ss << "Can't start language server[" << executable << "], error: " << e.what();
errorMessage = ss.str();
return false;
}
}
//
// LspBridge::Stop
//
void LspBridge::Stop() {
if (IsRunning()) {
// clear all open documents (this also closes them)
documents.clear();
// send a shutdown request and wait for response
messageHandler->sendRequest<lsp::requests::Shutdown>(
[this](const lsp::requests::Shutdown::Result&) {
// send an exit notification
messageHandler->sendNotification<lsp::notifications::Exit>();
running.store(false);
},
[](const lsp::ResponseError& error) {
std::cerr << "Error: " << error.code() << " - " << error.what() << std::endl;
});
// wait for message handling thread to finish
if (messageThread.joinable()) {
messageThread.join();
}
}
}
//
// LspBridge::messageLoop
//
void LspBridge::messageLoop() {
while (IsRunning()) {
try {
messageHandler->processIncomingMessages();
} catch(const std::exception& e) {
std::cerr << "================================ Error: " << e.what() << std::endl;
}
}
}
//
// LspBridge::o
//
void LspBridge::OpenDocument(const std::filesystem::path& path, TextEditor& editor, int options) {
if (IsRunning()) {
if (documents.find(path) != documents.end()) {
documents.erase(path);
}
documents.try_emplace(path, *this, path, editor, options);
}
}
//
// LspBridge::CloseDocument
//
void LspBridge::CloseDocument(const std::filesystem::path& path) {
if (IsRunning()) {
if (documents.find(path) != documents.end()) {
documents.erase(path);
}
}
}
//
// LspBridge::IsOpen
//
bool LspBridge::IsOpen(const std::filesystem::path& path) {
return documents.find(path) != documents.end();
}
//
// LspBridge::update
//
void LspBridge::Update(const std::filesystem::path& path) {
const auto i = documents.find(path);
if (i != documents.end()) {
i->second.update();
}
}
//
// LspBridge::Document::Document
//
LspBridge::Document::Document(LspBridge& bridge, const std::filesystem::path& path, TextEditor& editor, int options)
: bridge(bridge), path(path), editor(editor), options(options) {
// sanitize options (can't hover and signature at the same time)
if ((options & showHoverHelp) && (options & showSignature)) {
options &= ~showSignature;
}
// open document in language server
bridge.messageHandler->sendNotification<lsp::notifications::TextDocument_DidOpen>({
.textDocument = {
.uri = lsp::DocumentUri::fromPath(path.string()),
.languageId = editor.GetLanguageName(),
.version = version++,
.text = editor.GetText()
}
});
// provide document text to language server
lsp::Array<lsp::TextDocumentContentChangeEvent> contentChanges;
contentChanges.emplace_back(lsp::TextDocumentContentChangeEvent_Text({
.text = editor.GetText()
}));
lsp::DidChangeTextDocumentParams params;
params.textDocument.uri = lsp::DocumentUri::fromPath(path.string());
params.textDocument.version = version++;
params.contentChanges = std::move(contentChanges);
bridge.messageHandler->sendNotification<lsp::notifications::TextDocument_DidChange>(std::move(params));
// track changes in document from now on and pass them to the language server
editor.SetTransactionCallback([&](const std::vector<TextEditor::Change>& changes) {
lsp::Array<lsp::TextDocumentContentChangeEvent> contentChanges;
for (auto& change : changes) {
if (change.insert) {
contentChanges.emplace_back(lsp::TextDocumentContentChangeEvent_Range_Text({
.range = lsp::Range({
.start = lsp::Position({
.line = static_cast<lsp::uint>(change.start.line),
.character = static_cast<lsp::uint>(change.start.index)
}),
.end = lsp::Position({
.line = static_cast<lsp::uint>(change.start.line),
.character = static_cast<lsp::uint>(change.start.index)
})
}),
.text = change.text
}));
} else {
contentChanges.emplace_back(lsp::TextDocumentContentChangeEvent_Range_Text({
.range = lsp::Range({
.start = lsp::Position({
.line = static_cast<lsp::uint>(change.start.line),
.character = static_cast<lsp::uint>(change.start.index)
}),
.end = lsp::Position({
.line = static_cast<lsp::uint>(change.end.line),
.character = static_cast<lsp::uint>(change.end.index)
})
}),
.text = ""
}));
}
}
lsp::DidChangeTextDocumentParams params;
params.textDocument.uri = lsp::DocumentUri::fromPath(path.string());
params.textDocument.version = version++;
params.contentChanges = std::move(contentChanges);
bridge.messageHandler->sendNotification<lsp::notifications::TextDocument_DidChange>(std::move(params));
});
if (options & autocomplete) {
TextEditor::AutoCompleteConfig config;
config.callback = [&](TextEditor::AutoCompleteState& state) {
bridge.messageHandler->sendRequest<lsp::requests::TextDocument_Completion>(
{
{
.textDocument = {
.uri = lsp::DocumentUri::fromPath(path.string())
},
.position = lsp::Position {
.line = static_cast<lsp::uint>(state.searchTermEnd.line),
.character = static_cast<lsp::uint>(state.searchTermEnd.index)
}
}
},
[&](const lsp::requests::TextDocument_Completion::Result& result) {
// if (result.holdsAlternative<lsp::CompletionList>()) {
if (!result.isNull()) {
const std::scoped_lock lock(mutex);
suggestions.clear();
auto list = result.get<lsp::CompletionList>();
for (auto& item : list.items) {
if (item.insertText) {
suggestions.emplace_back(*item.insertText);
}
}
}
},
[](const lsp::ResponseError& error) {
std::cerr << "Error: " << error.code() << " - " << error.what() << std::endl;
});
state.suggestionsPromise = true;
};
editor.SetAutoCompleteConfig(&config);
}
}
//
// LspBridge::Document::~Document
//
LspBridge::Document::~Document() {
// close document in language server
bridge.messageHandler->sendNotification<lsp::notifications::TextDocument_DidClose>({
.textDocument = {
.uri = lsp::DocumentUri::fromPath(path.string())
}
});
// disconnect from editor
editor.SetTransactionCallback(nullptr);
if (options & autocomplete) {
editor.SetAutoCompleteConfig(nullptr);
}
if ((options & showHoverHelp) || (options & showSignature)) {
if (editor.HasTextHoverCallback()) {
editor.SetTextHoverCallback(nullptr);
}
}
}
//
// LspBridge::Document::update
//
void LspBridge::Document::update() {
// see if we are hovering over text
if (editor.IsMousePosOverGlyph(ImGui::GetMousePos())) {
const auto docPos = editor.GetDocPosAtMousePos(ImGui::GetMousePos());
if (docPos != mouseDocPos) {
mouseDocPos = docPos;
if (options & showSignature) {
bridge.messageHandler->sendRequest<lsp::requests::TextDocument_SignatureHelp>(
{
{
.textDocument = {
.uri = lsp::DocumentUri::fromPath(path.string())
},
.position = lsp::Position {
.line = static_cast<lsp::uint>(docPos.line),
.character = static_cast<lsp::uint>(docPos.index)
}
}
},
[&](const lsp::requests::TextDocument_SignatureHelp::Result& result) {
if (!result.isNull()) {
signatures.clear();
for (auto& signature : result->signatures) {
signatures.emplace_back(signature.label);
}
}
},
[](const lsp::ResponseError& error) {
std::cerr << "Error: " << error.code() << " - " << error.what() << std::endl;
});
} else if (options & showHoverHelp) {
bridge.messageHandler->sendRequest<lsp::requests::TextDocument_Hover>(
{
{
.textDocument = {
.uri = lsp::DocumentUri::fromPath(path.string())
},
.position = lsp::Position {
.line = static_cast<lsp::uint>(docPos.line),
.character = static_cast<lsp::uint>(docPos.index)
}
}
},
[this](const lsp::requests::TextDocument_Hover::Result& result) {
if (!result.isNull()) {
const std::scoped_lock lock(mutex);
if (std::holds_alternative<lsp::MarkupContent>(result->contents)) {
const auto message = std::get<lsp::MarkupContent>(result->contents);
hoverMessage = message.value;
} else {
hoverMessage.clear();
}
} else {
hoverMessage.clear();
}
},
[](const lsp::ResponseError& error) {
std::cerr << "Error: " << error.code() << " - " << error.what() << std::endl;
});
}
}
}
// submit suggestions asynchronously (if required)
if ((options & autocomplete) && suggestions.size()) {
const std::scoped_lock lock(mutex);
editor.SetAutoCompleteSuggestions(suggestions);
suggestions.clear();
}
// setup hover help (if required)
if (options & showHoverHelp) {
const std::scoped_lock lock(mutex);
if (hoverMessage.size() && editor.IsMousePosOverGlyph(ImGui::GetMousePos())) {
editor.SetTextHoverCallback([&](TextEditor::PopupData) {
ImGui::TextDisabled("%s", hoverMessage.c_str());
});
} else {
editor.ClearTextHoverCallback();
}
}
// setup signatures (if required)
if (options & showSignature) {
const std::scoped_lock lock(mutex);
if (signatures.size() && editor.IsMousePosOverGlyph(ImGui::GetMousePos())) {
editor.SetTextHoverCallback([&](TextEditor::PopupData) {
for (const auto& signature : signatures) {
ImGui::TextDisabled("%s", signature.c_str());
}
});
} else {
editor.ClearTextHoverCallback();
}
}
}
+106
View File
@@ -0,0 +1,106 @@
// TextEditor - A syntax highlighting text editor for Dear ImGui.
// Copyright (c) 2024-2026 Johan A. Goossens. All rights reserved.
//
// This work is licensed under the terms of the MIT license.
// For a copy, see <https://opensource.org/licenses/MIT>.
#pragma once
//
// Include files
//
#include <atomic>
#include <filesystem>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <unordered_map>
#include <vector>
#include "lsp/messagehandler.h"
#include "lsp/types.h"
#include "lsp/process.h"
#include "../TextEditor.h"
//
// LspBridge
//
class LspBridge {
public:
// constructor/destructor
LspBridge();
~LspBridge();
// start/stop the server
bool Start(const std::string& rootPath, const std::string& executable, const std::vector<std::string>& args={});
void Stop();
// features for a specific document
static constexpr int autocomplete = 1 << 0;
static constexpr int showSignature = 1 << 1;
static constexpr int showHoverHelp = 1 << 2;
// open/close documents (server can handle multiple at the time)
void OpenDocument(const std::filesystem::path& path, TextEditor& editor, int options=autocomplete);
void CloseDocument(const std::filesystem::path& path);
bool IsOpen(const std::filesystem::path& path);
// call this before TextEditor is rendered
void Update(const std::filesystem::path& path);
// get status
inline bool IsRunning() const { return running.load(); }
inline const std::string& GetError() const { return errorMessage; }
private:
// work variables
friend class Document;
lsp::Process process;
std::string errorMessage;
std::unique_ptr<lsp::Connection> connection;
std::unique_ptr<lsp::MessageHandler> messageHandler;
lsp::ServerCapabilities serverCapabilities;
std::atomic_bool running = false;
std::thread messageThread;
// a single open document
class Document {
public:
// constructor/destructor
Document(LspBridge& bridge, const std::filesystem::path& path, TextEditor& editor, int options);
~Document();
// update document state
void update();
private:
// properties
LspBridge& bridge;
const std::filesystem::path path;
TextEditor& editor;
int options;
int version = 1;
std::mutex mutex;
std::vector<std::string> suggestions;
std::vector<std::string> signatures;
std::string hoverMessage;
TextEditor::DocPos mouseDocPos;
};
// all documents currently open
std::unordered_map<std::filesystem::path, Document> documents;
// support functions
void messageLoop();
};
+236
View File
@@ -0,0 +1,236 @@
// TextEditor - A syntax highlighting text editor for Dear ImGui.
// Copyright (c) 2024-2026 Johan A. Goossens. All rights reserved.
//
// This work is licensed under the terms of the MIT license.
// For a copy, see <https://opensource.org/licenses/MIT>.
//
// Include files
//
#include "TrieAutoComplete.h"
//
// TrieAutoComplete::TrieAutoComplete
//
TrieAutoComplete::TrieAutoComplete() {
}
//
// TrieAutoComplete::Connect
//
void TrieAutoComplete::Connect(TextEditor* newEditor) {
// disconnect first (if required)
if (editor) {
Disconnect();
}
// remember current editor
editor = newEditor;
// rebuild word list
buildTrie();
// setup autocomplete by submitting a new configuration
TextEditor::AutoCompleteConfig config;
config.callback = [this](TextEditor::AutoCompleteState& state) {
trie.findSuggestions(state.suggestions, state.searchTerm);
};
editor->SetAutoCompleteConfig(&config);
// enable tracking of language changes
editor->SetLanguageChangeCallback([this]() {
buildTrie();
});
// enable change tracking
// we don't track every keystroke, callbacks can be delayed up to 2000 milliseconds
// if you want live tracking, change the 2000 to 0 (performance hit will be minimal for small documents)
editor->SetChangeCallback([this]() {
buildTrie();
}, 2000);
}
//
// TrieAutoComplete::Disconnect
//
void TrieAutoComplete::Disconnect() {
// disconnect from text editor (if required)
if (editor) {
editor->SetAutoCompleteConfig(nullptr);
editor->SetLanguageChangeCallback(nullptr);
editor->SetChangeCallback(nullptr);
editor = nullptr;
}
}
//
// TrieAutoComplete::buildTrie
//
void TrieAutoComplete::buildTrie() {
// empty list first
trie.clear();
// add language words (if required)
auto language = editor->GetLanguage();
if (language) {
for (const auto& word : language->keywords) { trie.insert(word); }
for (const auto& word : language->declarations) { trie.insert(word); }
for (const auto& word : language->identifiers) { trie.insert(word); }
}
// add all identifiers in current document
editor->IterateIdentifiers([this](const std::string& identifier) {
trie.insert(identifier);
});
}
//
// TrieAutoComplete::Trie::insert
//
void TrieAutoComplete::Trie::insert(const std::string_view& word) {
auto node = root.get();
const auto end = word.end();
auto i = TextEditor::CodePoint::skipBOM(word.begin(), end);
while (i < end) {
ImWchar codepoint;
i = TextEditor::CodePoint::read(i, end, &codepoint);
if (node->children.find(codepoint) == node->children.end()) {
node->children[codepoint] = std::make_unique<Node>();
}
node = node->children[codepoint].get();
}
node->word = word;
}
//
// TrieAutoComplete::Trie::findSuggestions
//
void TrieAutoComplete::Trie::findSuggestions(std::vector<std::string>& suggestions, const std::string_view& searchTerm, size_t limit, size_t maxSkippedLetters) {
// clear result vector
maxSkip = maxSkippedLetters;
suggestions.clear();
// don't even try if search term is empty
if (searchTerm.size() != 0) {
// convert search term into vector of code blocks
searchCodepoints.clear();
const auto end = searchTerm.end();
auto i = TextEditor::CodePoint::skipBOM(searchTerm.begin(), end);
while (i < end) {
ImWchar codepoint;
i = TextEditor::CodePoint::read(i, end, &codepoint);
searchCodepoints.emplace_back(codepoint);
}
// recursively evaluate nodes
candidates.clear();
evaluateNode(root.get(), 0, 0, maxSkip);
// did we find anything?
if (candidates.size()) {
// sort candidates by cost
std::sort(candidates.begin(), candidates.end());
// remove duplicates which are caused by mutiple paths based on skips
const auto last = std::unique(candidates.begin(), candidates.end());
candidates.erase(last, candidates.end());
// populate suggestions (applying limit)
const auto size = std::min(static_cast<size_t>(limit), candidates.size());
for (size_t j = 0; j < size; j++) {
suggestions.emplace_back(candidates[j].node->word);
}
}
}
}
//
// TrieAutoComplete::Trie::evaluateNode
//
void TrieAutoComplete::Trie::evaluateNode(const Node* node, size_t index, size_t cost, size_t skip) {
// see if that is one of our children (check both lower and uppercase matches)
const ImWchar codepointLower = TextEditor::CodePoint::toLower(searchCodepoints[index]);
const Node* childLower = nullptr;
if (node->children.find(codepointLower) != node->children.end()) {
// codepoint found, is this the last one in our searchTerm?
childLower = node->children.at(codepointLower).get();
if (index == searchCodepoints.size() - 1) {
// yes, add candidate words to results
addCandidates(childLower, cost);
} else {
// no, try to find the rest
evaluateNode(childLower, index + 1, cost, maxSkip);
}
}
const ImWchar codepointUpper = TextEditor::CodePoint::toUpper(searchCodepoints[index]);
const Node* childUpper = nullptr;
if (node->children.find(codepointUpper) != node->children.end()) {
// codepoint found, is this the last one in our searchTerm?
childUpper = node->children.at(codepointUpper).get();
if (index == searchCodepoints.size() - 1) {
// yes, add candidate words to results
addCandidates(childUpper, cost);
} else {
// no, try to find the rest
evaluateNode(childUpper, index + 1, cost, maxSkip);
}
}
// also try children to support detection of missing letters (if we haven't skipped too many entries yet)
if (skip) {
for (const auto& [key, value] : node->children) {
const auto next = value.get();
if (next != childLower && next != childUpper) {
evaluateNode(next, index, cost + 1, skip - 1);
}
}
}
}
//
// TrieAutoComplete::Trie::addCandidates
//
void TrieAutoComplete::Trie::addCandidates(const Node* node, size_t cost) {
if (node->word.size()) {
candidates.emplace_back(node, cost);
}
for (const auto& [key, value] : node->children) {
addCandidates(value.get(), cost + 1);
}
}
+105
View File
@@ -0,0 +1,105 @@
// TextEditor - A syntax highlighting text editor for Dear ImGui.
// Copyright (c) 2024-2026 Johan A. Goossens. All rights reserved.
//
// This work is licensed under the terms of the MIT license.
// For a copy, see <https://opensource.org/licenses/MIT>.
#pragma once
//
// Include files
//
#include <memory>
#include <string>
#include <string_view>
#include <unordered_map>
#include <vector>
#include "../TextEditor.h"
//
// TrieAutoComplete
//
// This is a utility class that can be connected to an TextEditor instance
// and it will provide simple autocomplete features based on the language
// set in the editor and identifiers contained in the text.
//
// This feature is not context aware and for that, you should connect
// to a language server using the LspBridge class also contained in this
// directory.
//
// TrieAutoComplete is standalone, simple, fast but not context accurate.
// LspBridge has dependencies and is more complex.
//
class TrieAutoComplete {
public:
// constructor
TrieAutoComplete();
// manage connection to text editor
void Connect(TextEditor* editor);
void Disconnect();
inline bool IsConnected() const { return editor != nullptr; }
private:
// the text editor we are connected to
TextEditor* editor = nullptr;
// support functions
void buildTrie();
// the trie structure containing possible solutions
class Trie {
public:
// constructor
Trie() { clear(); }
// clear word tree
inline void clear() { root = std::make_unique<Node>(); }
// insert word (UTF-8 encoded) into tree
void insert(const std::string_view& word);
// populate list of suggestions based on provided search term (which is UTF-8 encoded)
// limit is maximum number of suggestions returned after they are sorted by relevance
// maxSkippedLetters is a the largest number of letters that can be skipped to find the next match
// this allows for missing letters (out of order letters are not taken into account)
void findSuggestions(std::vector<std::string>& suggestions, const std::string_view& searchTerm, size_t limit=20, size_t maxSkippedLetters=2);
private:
// definition of single node in the word graph
struct Node {
std::unordered_map<ImWchar, std::unique_ptr<Node>> children;
std::string word;
};
// the root node
std::unique_ptr<Node> root;
// maximum number of letters that can be skipped skip in matching algorithm
size_t maxSkip;
// search term as codepoint vector
std::vector<ImWchar> searchCodepoints;
// possible autocomplete candidates
struct Candidate {
Candidate(const Node* n, size_t c) : node(n), cost(c) {}
bool operator<(const Candidate& rhs) const { return cost < rhs.cost; }
bool operator==(const Candidate& rhs) const { return node == rhs.node; }
const Node* node;
size_t cost;
};
std::vector<Candidate> candidates;
// utility functions
void evaluateNode(const Node* node, size_t index, size_t cost, size_t skip);
void addCandidates(const Node* node, size_t cost);
} trie;
};
+11
View File
@@ -0,0 +1,11 @@
[package]
name = "4dbug/imguicolortextedit-luau"
version = "0.1.0"
registry = "https://github.com/UpliftGames/wally-index"
realm = "shared"
license = "MIT"
description = "Syntax-highlighting text editor widget for imgui-luau (Roblox / LÖVE)."
include = ["TextEditor.lua", "LICENSE", "README.md", "wally.toml", "default.project.json"]
[peer-dependencies]
ImGui = "4dbug/imgui-luau@^0.4.0"