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

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

No files matched your search

+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;
};