Skip to content

Commit f4a85ad

Browse files
committed
Add GetWordAtScreenPos() - get the word at a screen position (e.g. from ImGui::GetMousePos())
1 parent 2df4247 commit f4a85ad

2 files changed

Lines changed: 29 additions & 0 deletions

File tree

TextEditor.cpp

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,7 @@ void TextEditor::render(const char* title, const ImVec2& size, bool border) {
9191

9292
// get current position and total/visible editor size
9393
auto pos = ImGui::GetCursorScreenPos();
94+
lastRenderOrigin = pos;
9495
auto totalSize = ImVec2(textOffset + document.getMaxColumn() * glyphSize.x + cursorWidth, document.size() * glyphSize.y);
9596
auto region = ImGui::GetContentRegionAvail();
9697
auto visibleSize = ImGui::CalcItemSize(size, region.x, region.y); // messing with Dear ImGui internals
@@ -1306,6 +1307,30 @@ std::string TextEditor::getCursorText(size_t cursor) const {
13061307
}
13071308

13081309

1310+
//
1311+
// TextEditor::GetWordAtScreenPos
1312+
//
1313+
1314+
std::string TextEditor::GetWordAtScreenPos(const ImVec2& screenPos) const {
1315+
// Convert screen position to local coordinates using the origin saved during last Render()
1316+
auto local = screenPos - lastRenderOrigin;
1317+
1318+
// Convert to text coordinates using the same logic as handleMouseInteractions()
1319+
Coordinate glyphCoordinate;
1320+
Coordinate cursorCoordinate;
1321+
document.normalizeCoordinate(
1322+
local.y / glyphSize.y,
1323+
(local.x - textOffset) / glyphSize.x,
1324+
glyphCoordinate,
1325+
cursorCoordinate);
1326+
1327+
// Find word boundaries and extract text
1328+
auto start = document.findWordStart(glyphCoordinate);
1329+
auto end = document.findWordEnd(glyphCoordinate);
1330+
return document.getSectionText(start, end);
1331+
}
1332+
1333+
13091334
//
13101335
// TextEditor::makeCursorVisible
13111336
//

TextEditor.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,9 @@ class TextEditor {
157157
inline CursorSelection GetCursorSelection(size_t cursor) const { CursorSelection s; getCursor(s.start.line, s.start.column, s.end.line, s.end.column, cursor); return s; }
158158
inline CursorSelection GetMainCursorSelection() const { return GetCursorSelection(cursors.getMainIndex()); }
159159

160+
// get the word at a screen position (e.g. from ImGui::GetMousePos()) - uses the origin saved during the last Render() call
161+
std::string GetWordAtScreenPos(const ImVec2& screenPos) const;
162+
160163
// scrolling support
161164
enum class Scroll {
162165
alignTop,
@@ -1290,6 +1293,7 @@ class TextEditor {
12901293
ImFont* font;
12911294
float fontSize;
12921295
ImVec2 glyphSize;
1296+
ImVec2 lastRenderOrigin;
12931297
float lineNumberLeftOffset;
12941298
float lineNumberRightOffset;
12951299
float decorationOffset;

0 commit comments

Comments
 (0)