-- TextEditor for imgui-luau. Port of https://github.com/goossens/ImGuiColorTextEdit (b12d713e77e8edddff1e69973f67085ac9cfaf74). -- Usage: local TextEditor = require(path.to.TextEditor)(require(path.to.ImGui)) -- -- [Port] Indexing conventions: -- * Public API (DocPos.line / DocPos.index, line numbers, cursor numbers) is 0-based, exactly like upstream. -- * Internally the document is a 1-based Lua array: line `n` (0-based) is `document.lines[n + 1]`, -- glyph `i` (0-based) of a line is `line[i + 1]`. Cursor `c` (0-based) is `cursors.list[c + 1]`. -- * Text is UTF-8 encoded Lua strings; glyphs store unicode codepoints. -- -- [Port] Ported: Document, Cursor/Cursors, Transactions (undo/redo), text get/set, insert/delete, word boundaries, -- palettes, languages/colorizer, bracketeer, Render (line numbers, selections, text, carets, brackets, markers, -- scrolling), keyboard and mouse handling, clipboard. Not ported yet: word wrap/typesetting, folding, minimap, -- squiggles, decorations and autocomplete (see `[Port] TODO`). return function(G) local ImGui, ImVec2, ImVec4 = G.ImGui, G.ImVec2, G.ImVec4 local TextEditor = {} TextEditor.__index = TextEditor -- color palette support -- [Port] enum values are 1-based so they index a Palette (a Lua array of IM_COL32 ints) directly local Color = { text = 1, keyword = 2, declaration = 3, number = 4, string = 5, punctuation = 6, preprocessor = 7, identifier = 8, knownIdentifier = 9, comment = 10, background = 11, cursor = 12, selection = 13, whitespace = 14, matchingBracketBackground = 15, matchingBracketActive = 16, matchingBracketLevel1 = 17, matchingBracketLevel2 = 18, matchingBracketLevel3 = 19, matchingBracketError = 20, lineNumber = 21, currentLineNumber = 22, currentLineHighlight = 23, currentLineHighlightBorder = 24, count = 24, } TextEditor.Color = Color -- colorizer/tokenizer state -- [Port] LineState is a plain integer enum (same order as upstream) local LineState = { inText = 0, inComment = 1, -- inCommentLevel1..7 = 2..8 inSingleQuotedString = 9, inDoubleQuotedString = 10, inOtherString = 11, inOtherStringAlt = 12, inStringLevel0 = 13, -- inStringLevel1..7 = 14..20 } local maxCommentLevel = 7 local maxStringLevel = 7 local function lineStateInComment(state) return state >= 1 and state <= 8 end local function lineStateInStringLevel(state) return state >= 13 and state <= 20 end local function commentLevelToLineState(level) return LineState.inComment + level end local function stringLevelToLineState(level) return LineState.inStringLevel0 + level end -- -- DocPos: logical position of a glyph expressed as a line number and glyph index (both zero-based) -- local DocPos = {} DocPos.__index = DocPos TextEditor.DocPos = DocPos local function newDocPos(line, index) return setmetatable({ line = line or 0, index = index or 0 }, DocPos) end DocPos.new = newDocPos DocPos.__eq = function(a, b) return a.line == b.line and a.index == b.index end DocPos.__lt = function(a, b) if a.line ~= b.line then return a.line < b.line end return a.index < b.index end DocPos.__le = function(a, b) if a.line ~= b.line then return a.line < b.line end return a.index <= b.index end DocPos.__tostring = function(a) return "DocPos(" .. a.line .. ", " .. a.index .. ")" end -- [Port] DocSelection is a plain table { start = DocPos, ["end"] = DocPos } local function newDocSelection(s, e) return { start = s, ["end"] = e } end -- -- CodePoint -- local CodePoint = {} -- [Port] decode UTF-8 into a list of codepoints; invalid sequences fall back to one codepoint per byte function CodePoint.decode(text) local out = {} local ok = pcall(function() for _, c in utf8.codes(text) do out[#out + 1] = c end end) if not ok then table.clear(out) for i = 1, #text do out[i] = string.byte(text, i) end end return out end function CodePoint.write(codepoint) return utf8.char(codepoint) end -- [Port] ASCII rules as upstream; the unicode whitespace table is reduced to a few common codepoints function CodePoint.isWhiteSpace(codepoint) if codepoint < 0x7f then return codepoint == 32 or (codepoint >= 9 and codepoint <= 13) end return codepoint == 0x85 or codepoint == 0xA0 or codepoint == 0x1680 or (codepoint >= 0x2000 and codepoint <= 0x200A) or codepoint == 0x2028 or codepoint == 0x2029 or codepoint == 0x202F or codepoint == 0x205F or codepoint == 0x3000 end -- [Port] ASCII rules as upstream; every other non-whitespace codepoint counts as a word character function CodePoint.isWord(codepoint) if codepoint < 0x7f then return (codepoint >= 97 and codepoint <= 122) or (codepoint >= 65 and codepoint <= 90) or (codepoint >= 48 and codepoint <= 57) or codepoint == 95 end return not CodePoint.isWhiteSpace(codepoint) end -- [Port] no east asian width tables: every glyph is one column wide @native function CodePoint.getGlyphWidth(codepoint) return 1 end TextEditor.CodePoint = CodePoint -- -- Document: the document being edited (Lines of Glyphs) -- a glyph is { codepoint = number, color = Color } -- local Document = {} Document.__index = Document local function newGlyph(codepoint, color) return { codepoint = codepoint, color = color or Color.text } end function Document.new() local self = setmetatable({ lines = {}, updated = false, version = 0 }, Document) self:appendLine() return self end function Document:size() return #self.lines end function Document:at(line) return self.lines[line + 1] end -- [Port] a line is an array of glyphs with hash fields { needsColorizing, state } (upstream's Line members) local function newLine() return { needsColorizing = true, state = LineState.inText } end function Document:appendLine() self.lines[#self.lines + 1] = newLine() end function Document:insertLine(offset) table.insert(self.lines, offset + 1, newLine()) end function Document:deleteLines(s, e) for _ = s, e do table.remove(self.lines, s + 1) end end function Document:clearDocument() table.clear(self.lines) end function Document:getSpacesToTab(config, line, index) local columns = 0 for i = 1, index do columns = columns + CodePoint.getGlyphWidth(line[i].codepoint) end return (math.floor(columns / config.tabSize) + 1) * config.tabSize - columns end function Document:setUtf8Text(config, text) -- reset document self:clearDocument() self:appendLine() -- process UTF-8 and generate lines of glyphs local cps = CodePoint.decode(text) for _, character in ipairs(cps) do local back = self.lines[#self.lines] if character == 10 then self:appendLine() elseif config.insertSpacesOnTabs and character == 9 then local spaces = self:getSpacesToTab(config, back, #back) for _ = 1, spaces do back[#back + 1] = newGlyph(32) end elseif character ~= 13 then back[#back + 1] = newGlyph(character) end end -- [Port] updateIndents skipped (used by rendering only) self.updated = true self.version = self.version + 1 end -- insert/delete part of the document's text (strings are UTF-8 encoded) function Document:insertText(config, start, text) local lineNo = start.line local line = self:at(lineNo) local index = start.index -- process all codepoints for _, character in ipairs(CodePoint.decode(text)) do if character == 10 then -- split line self:insertLine(lineNo + 1) lineNo = lineNo + 1 local nextLine = self:at(lineNo) for j = index + 1, #line do nextLine[#nextLine + 1] = line[j] end for j = #line, index + 1, -1 do line[j] = nil end line = nextLine index = 0 elseif config.insertSpacesOnTabs and character == 9 then local spaces = self:getSpacesToTab(config, line, index) for _ = 1, spaces do index = index + 1 table.insert(line, index, newGlyph(32)) end elseif character ~= 13 then -- insert next glyph index = index + 1 table.insert(line, index, newGlyph(character)) end end -- determine end of insert local e = newDocPos(lineNo, index) -- mark affected lines as changed for j = start.line, e.line do local changed = self:at(j) changed.needsColorizing = true changed.columns = nil end self.updated = true self.version = self.version + 1 return e end function Document:deleteText(config, start, e) local startLine = self:at(start.line) local endLine = self:at(e.line) -- see if start and end are on the same line if start.line == e.line then local n = #startLine table.move(startLine, e.index + 1, n, start.index + 1) for j = n - (e.index - start.index) + 1, n do startLine[j] = nil end else -- start and end are on different lines -- remove end of first line, then join with the remainder of the last line for j = #startLine, start.index + 1, -1 do startLine[j] = nil end for j = e.index + 1, #endLine do startLine[#startLine + 1] = endLine[j] end -- delete lines self:deleteLines(start.line + 1, e.line) end -- mark line and document as changed startLine.needsColorizing = true startLine.columns = nil self.updated = true self.version = self.version + 1 end -- get document text as UTF-8 function Document:getUtf8Text() local parts = {} local n = #self.lines for l = 1, n do local line = self.lines[l] for i = 1, #line do parts[#parts + 1] = utf8.char(line[i].codepoint) end if l ~= n or #line > 0 then parts[#parts + 1] = "\n" end end return table.concat(parts) end -- get part of document text (returned strings are UTF-8 encoded) -- [Port] the last result is kept until the document changes (version) or another section is asked for: the editor -- hands the selected text to the platform (IME / Roblox text proxy) every frame function Document:getSectionText(start, e) local memo = self.sectionMemo if memo and memo[1] == self.version and memo[2] == start.line and memo[3] == start.index and memo[4] == e.line and memo[5] == e.index then return memo[6] end local text = self:getSectionTextUncached(start, e) if not memo then memo = {}; self.sectionMemo = memo end memo[1], memo[2], memo[3], memo[4], memo[5], memo[6] = self.version, start.line, start.index, e.line, e.index, text return text end function Document:getSectionTextUncached(start, e) local parts = {} local lineNo = start.line local index = start.index while lineNo < e.line or index < e.index do local line = self:at(lineNo) if index < #line then parts[#parts + 1] = utf8.char(line[index + 1].codepoint) index = index + 1 else parts[#parts + 1] = "\n" lineNo = lineNo + 1 index = 0 end end return table.concat(parts) end function Document:getLineText(line) return self:getSectionText(newDocPos(line, 0), newDocPos(line, #self:at(line))) end function Document:getCodePoint(location) local line = self:at(location.line) if location.index < #line then return line[location.index + 1].codepoint end return 0xFFFD -- IM_UNICODE_CODEPOINT_INVALID end function Document:getColor(location) local line = self:at(location.line) if location.index < #line then return line[location.index + 1].color end return Color.text end -- see if document is empty function Document:isEmpty() return #self.lines == 1 and #self.lines[1] == 0 end -- [Port] no folding: hidden line helpers just move to the neighbouring line function Document:getLeftBeforeHiddenLines(pos) if pos.line == 0 then return newDocPos(0, 0) end return newDocPos(pos.line - 1, #self:at(pos.line - 1)) end function Document:getRightAfterHiddenLines(pos) if pos.line + 1 >= #self.lines then return self:getBottom() end return newDocPos(pos.line + 1, 0) end -- coordinate operations in context of document function Document:getLeft(from, wordMode) if wordMode then -- first move left by one glyph from = self:getLeft(from) -- now skip all whitespaces from = self:findPreviousNonWhiteSpace(from, false) -- find the start of the current word return self:findWordStart(from) else -- calculate position of previous glyph (could be on previous line) if from.index == 0 then return self:getLeftBeforeHiddenLines(from) end return newDocPos(from.line, from.index - 1) end end function Document:getRight(from, wordMode) if wordMode then -- first move right by one glyph from = self:getRight(from) -- now skip all whitespaces from = self:findNextNonWhiteSpace(from, false) -- find the end of the current word return self:findWordEnd(from) else -- calculate pos of next glyph (could be on next line) if from.index == #self:at(from.line) then return self:getRightAfterHiddenLines(from) end return newDocPos(from.line, from.index + 1) end end function Document:getTop() return newDocPos(0, 0) end function Document:getBottom() local lastLine = #self.lines - 1 return newDocPos(lastLine, #self:at(lastLine)) end function Document:getStartOfLine(from) return newDocPos(from.line, 0) end function Document:getEndOfLine(from) return newDocPos(from.line, #self:at(from.line)) end function Document:getNextLine(from) return self:getRight(self:getEndOfLine(from)) end -- search in document function Document:findWordStart(from, wordOnly) local line = self:at(from.line) if from.index == 0 or #line == 0 then return from end local index = from.index local firstCharacter = line[index].codepoint local isWord, isWhiteSpace = CodePoint.isWord, CodePoint.isWhiteSpace if not wordOnly and isWhiteSpace(firstCharacter) then while index > 0 and isWhiteSpace(line[index].codepoint) do index = index - 1 end elseif isWord(firstCharacter) then while index > 0 and isWord(line[index].codepoint) do index = index - 1 end else while not wordOnly and index > 0 and not isWord(line[index].codepoint) and not isWhiteSpace(line[index].codepoint) do index = index - 1 end end return newDocPos(from.line, index) end function Document:findWordEnd(from, wordOnly) local line = self:at(from.line) local size = #line local index = from.index if index >= size then return from end local firstCharacter = line[index + 1].codepoint local isWord, isWhiteSpace = CodePoint.isWord, CodePoint.isWhiteSpace if not wordOnly and isWhiteSpace(firstCharacter) then while index < size and isWhiteSpace(line[index + 1].codepoint) do index = index + 1 end elseif isWord(firstCharacter) then while index < size and isWord(line[index + 1].codepoint) do index = index + 1 end else while not wordOnly and index < size and not isWord(line[index + 1].codepoint) and not isWhiteSpace(line[index + 1].codepoint) do index = index + 1 end end return newDocPos(from.line, index) end -- utility functions function Document:isStartOfLine(from) return from.index == 0 end function Document:isEndOfLine(from) return from.index == #self:at(from.line) end function Document:isLastLine(line) return line == #self.lines - 1 end function Document:isWordStart(pos, wordOnly) local line = self:at(pos.line) local isWord, isWhiteSpace = CodePoint.isWord, CodePoint.isWhiteSpace if self:isEndOfLine(pos) then return false elseif self:isStartOfLine(pos) then if #line == 0 then return false end return not wordOnly or isWord(line[1].codepoint) end local glyph1 = line[pos.index].codepoint local glyph2 = line[pos.index + 1].codepoint if wordOnly then return not isWord(glyph1) and isWord(glyph2) elseif isWord(glyph2) then return not isWord(glyph1) elseif isWhiteSpace(glyph2) then return not isWhiteSpace(glyph1) end return isWord(glyph1) or isWhiteSpace(glyph1) end function Document:isWordEnd(pos, wordOnly) local line = self:at(pos.line) local isWord, isWhiteSpace = CodePoint.isWord, CodePoint.isWhiteSpace if self:isStartOfLine(pos) then return false elseif self:isEndOfLine(pos) then if #line == 0 then return false end return not wordOnly or isWord(line[#line].codepoint) end local glyph1 = line[pos.index].codepoint local glyph2 = line[pos.index + 1].codepoint if wordOnly then return isWord(glyph1) and not isWord(glyph2) elseif isWord(glyph1) then return not isWord(glyph2) elseif isWhiteSpace(glyph1) then return not isWhiteSpace(glyph2) end return isWord(glyph2) or isWhiteSpace(glyph2) end function Document:isWholeWord(start, e, wordOnly) if e <= start or start.line ~= e.line then return false end return self:isWordStart(start, wordOnly) and self:isWordEnd(e, wordOnly) end function Document:getWholeWord(pos, wordOnly) if wordOnly and not self:isStartOfLine(pos) and not self:isEndOfLine(pos) and not CodePoint.isWord(self:at(pos.line)[pos.index + 1].codepoint) then return newDocSelection(pos, pos) elseif self:isWordStart(pos, wordOnly) then return newDocSelection(pos, self:findWordEnd(pos, wordOnly)) elseif self:isWordEnd(pos, wordOnly) then return newDocSelection(self:findWordStart(pos, wordOnly), pos) end return newDocSelection(self:findWordStart(pos, wordOnly), self:findWordEnd(pos, wordOnly)) end function Document:findPreviousNonWhiteSpace(from, includeEndOfLine) if includeEndOfLine == nil then includeEndOfLine = true end from = newDocPos(from.line, from.index) local done = false while not done do local line = self:at(from.line) local index = from.index while not done and index > 0 do index = index - 1 if not CodePoint.isWhiteSpace(line[index + 1].codepoint) then from.index = index done = true end end if not done then if from.line == 0 or not includeEndOfLine then from.index = 0 done = true else from = self:getLeftBeforeHiddenLines(from) end end end return from end function Document:findNextNonWhiteSpace(from, includeEndOfLine) if includeEndOfLine == nil then includeEndOfLine = true end from = newDocPos(from.line, from.index) local done = false while not done do local line = self:at(from.line) local index = from.index while not done and index < #line do if CodePoint.isWhiteSpace(line[index + 1].codepoint) then index = index + 1 else from.index = index done = true end end if not done then -- [Port] upstream compares with size(); last line check avoids looping at the bottom if from.line >= #self.lines - 1 or not includeEndOfLine then from.index = #line done = true else from = self:getRightAfterHiddenLines(from) end end end return from end function Document:normalizePos(pos) local line = math.max(0, pos.line) if line >= #self.lines then return self:getBottom() elseif pos.index > #self:at(line) then return self:getEndOfLine(newDocPos(line, 0)) end return newDocPos(line, math.max(0, pos.index)) end function Document:normalizeLine(line) if line >= #self.lines then return #self.lines - 1 end return line end TextEditor.Document = Document -- -- Cursor: a single cursor -- local Cursor = {} Cursor.__index = Cursor function Cursor.new(s, e) return setmetatable({ start = s, ["end"] = e or s, main = false, current = true, updated = true, preferredColumn = 0 }, Cursor) end function Cursor:copy() local c = Cursor.new(self.start, self["end"]) c.main, c.current, c.updated, c.preferredColumn = self.main, self.current, self.updated, self.preferredColumn return c end -- update the cursor -- [Port] overloads: update(pos), update(s, e), update(pos, keep:boolean) function Cursor:update(a, b) if b == nil then self["end"] = a elseif type(b) == "boolean" then if b then self["end"] = a else self.start = a self["end"] = a end else self.start = a self["end"] = b end self.updated = true end -- grow the cursor either to the left or the right function Cursor:grow(position) if position < self:getSelectionStart() then if self["end"] > self.start then self.start, self["end"] = self["end"], self.start end self["end"] = position self.updated = true elseif position > self:getSelectionEnd() then if self["end"] < self.start then self.start, self["end"] = self["end"], self.start end self["end"] = position self.updated = true end end local function adjustCoordinateForInsert(position, insertStart, insertEnd) local line, index = position.line, position.index if line == insertStart.line then index = index + insertEnd.index - insertStart.index end line = line + insertEnd.line - insertStart.line return newDocPos(line, index) end local function adjustCoordinateForDelete(position, deleteStart, deleteEnd) local line, index = position.line, position.index if deleteStart.line == deleteEnd.line then if line == deleteEnd.line then index = index - (deleteEnd.index - deleteStart.index) end else line = line - (deleteEnd.line - deleteStart.line) if line == deleteEnd.line then index = index - deleteEnd.index end end return newDocPos(line, index) end -- adjust cursor for insert/delete operations -- (these functions assume that insert or delete points are before the cursor) function Cursor:adjustForInsert(insertStart, insertEnd) self.start = adjustCoordinateForInsert(self.start, insertStart, insertEnd) self["end"] = adjustCoordinateForInsert(self["end"], insertStart, insertEnd) end function Cursor:adjustForDelete(deleteStart, deleteEnd) self.start = adjustCoordinateForDelete(self.start, deleteStart, deleteEnd) self["end"] = adjustCoordinateForDelete(self["end"], deleteStart, deleteEnd) end -- access cursor properties function Cursor:getInteractiveStart() return self.start end function Cursor:getInteractiveEnd() return self["end"] end function Cursor:getSelectionStart() if self.start < self["end"] then return self.start end return self["end"] end function Cursor:getSelectionEnd() if self.start > self["end"] then return self.start end return self["end"] end function Cursor:hasSelection() return self.start ~= self["end"] end function Cursor:resetToStart() local p = self:getSelectionStart(); self:update(p, p) end function Cursor:resetToEnd() local p = self:getSelectionEnd(); self:update(p, p) end TextEditor.Cursor = Cursor -- -- Cursors: overlay to track the current list of cursors -- main/current are 0-based indices into list -- local Cursors = {} Cursors.__index = Cursors function Cursors.new() local self = setmetatable({ list = {}, main = 0, current = 0 }, Cursors) self:clearAll() return self end function Cursors:copy() local c = setmetatable({ list = {}, main = self.main, current = self.current }, Cursors) for i, cursor in ipairs(self.list) do c.list[i] = cursor:copy() end return c end function Cursors:size() return #self.list end function Cursors:at(i) return self.list[i + 1] end -- reset the cursors function Cursors:reset() table.clear(self.list) self.main = 0 self.current = 0 end -- erase all cursors and specify a new one function Cursors:setCursor(s, e) self:reset() local c = Cursor.new(s, e or s) c.main = true c.current = true self.list[1] = c end -- add a cursor to the list function Cursors:addCursor(s, e) self:at(self.current).current = false local c = Cursor.new(s, e or s) c.current = true self.list[#self.list + 1] = c self.current = #self.list - 1 end function Cursors:updateCurrentCursor(a, b) self:at(self.current):update(a, b) end function Cursors:growCurrentCursor(position) self:at(self.current):grow(position) end -- check cursor status function Cursors:hasMultiple() return #self.list > 1 end function Cursors:anyHasSelection() for _, cursor in ipairs(self.list) do if cursor:hasSelection() then return true end end return false end function Cursors:allHaveSelection() for _, cursor in ipairs(self.list) do if not cursor:hasSelection() then return false end end return true end function Cursors:cursorHasSelection(cursor) if cursor < #self.list then return self:at(cursor):hasSelection() end return false end function Cursors:mainCursorHasSelection() return self:at(self.main):hasSelection() end function Cursors:currentCursorHasSelection() return self:at(self.current):hasSelection() end function Cursors:mainHasUpdate() return self:at(self.main).updated end function Cursors:anyHasUpdate() for _, cursor in ipairs(self.list) do if cursor.updated then return true end end return false end -- clear the selections and create the default cursor function Cursors:clearAll() self:setCursor(newDocPos(0, 0)) end -- clear all additional cursors function Cursors:clearAdditional(reset) local kept = {} for _, cursor in ipairs(self.list) do if cursor.main then kept[#kept + 1] = cursor end end self.list = kept self.main = 0 self.current = 0 self.list[1].current = true if reset then self.list[1]:resetToEnd() end end -- clear all updated flags function Cursors:clearUpdated() for _, cursor in ipairs(self.list) do cursor.updated = false end end function Cursors:getMain() return self:at(self.main) end function Cursors:getMainIndex() return self.main end function Cursors:getCurrent() return self:at(self.current) end function Cursors:getCurrentIndex() return self.current end -- update cursors (sort and merge overlapping cursors) -- [Port] ensureNotHidden skipped (no folding yet) function Cursors:update(document) if not self:anyHasUpdate() then return end -- reset update flags self:clearUpdated() -- only sort and potential merge when we have multiple cursors if not self:hasMultiple() then return end local list = self.list table.sort(list, function(a, b) return a:getSelectionStart() < b:getSelectionStart() end) -- merge cursors (walk backwards: cursor = list[i], previous = list[i - 1]) local i = #list while i > 1 do local cursor = list[i] local previous = list[i - 1] if previous:getSelectionEnd() >= cursor:getSelectionEnd() then -- handle case where one cursor completely contains another cursor if cursor.main then previous.main = true end if cursor.current then previous.current = true end table.remove(list, i) i = i - 1 elseif previous:getSelectionEnd() > cursor:getSelectionStart() then if cursor:getInteractiveEnd() < cursor:getInteractiveStart() then previous:update(cursor:getSelectionEnd(), previous:getSelectionStart()) else previous:update(previous:getSelectionStart(), cursor:getSelectionEnd()) end if cursor.main then previous.main = true end if cursor.current then previous.current = true end table.remove(list, i) i = i - 1 else i = i - 1 end end -- find main and current cursor self.main = 0 self.current = 0 for c = 0, #list - 1 do if list[c + 1].main then self.main = c elseif list[c + 1].current then self.current = c end end end -- adjust cursors for insert/delete operations -- [Port] `start` is a 0-based cursor index instead of an iterator function Cursors:adjustForInsert(start, insertStart, insertEnd, includeCurrent) local first = start + 1 if includeCurrent then first = start end for c = first, #self.list - 1 do self.list[c + 1]:adjustForInsert(insertStart, insertEnd) end end function Cursors:adjustForDelete(start, deleteStart, deleteEnd, includeCurrent) local first = start + 1 if includeCurrent then first = start end for c = first, #self.list - 1 do self.list[c + 1]:adjustForDelete(deleteStart, deleteEnd) end end TextEditor.Cursors = Cursors -- -- Transaction: a collection of actions for a complete transaction -- an action is { type = "insertText"|"deleteText", start = DocPos, ["end"] = DocPos, text = string } -- local Transaction = {} Transaction.__index = Transaction function Transaction.new() return setmetatable({ actions = {}, before = nil, after = nil }, Transaction) end function Transaction:size() return #self.actions end function Transaction:setBeforeState(cursors) self.before = cursors:copy() end function Transaction:getBeforeState() return self.before end function Transaction:setAfterState(cursors) self.after = cursors:copy() end function Transaction:getAfterState() return self.after end function Transaction:addInsert(s, e, text) self.actions[#self.actions + 1] = { type = "insertText", start = s, ["end"] = e, text = text } end function Transaction:addDelete(s, e, text) self.actions[#self.actions + 1] = { type = "deleteText", start = s, ["end"] = e, text = text } end -- -- Transactions: overlay for managing the transaction list to support do/undo/redo -- undoIndex is a count (0 = nothing to undo), as upstream -- local Transactions = {} Transactions.__index = Transactions function Transactions.new() return setmetatable({ list = {}, undoIndex = 0, version = 0, callback = nil }, Transactions) end local function makeChanges(transaction, invert) local changes = {} for _, action in ipairs(transaction.actions) do local insert = action.type == "insertText" if invert then insert = not insert end changes[#changes + 1] = { insert = insert, start = action.start, ["end"] = action["end"], text = action.text } end return changes end function Transactions:reset() table.clear(self.list) self.undoIndex = 0 self.version = 0 end -- add a transaction to the list and make it undoable function Transactions:add(transaction) for i = #self.list, self.undoIndex + 1, -1 do self.list[i] = nil end self.list[#self.list + 1] = transaction self.undoIndex = self.undoIndex + 1 self.version = self.version + 1 if self.callback then self.callback(makeChanges(transaction, false)) end end -- undo the last transaction function Transactions:undo(config, document, editor) local transaction = self.list[self.undoIndex] self.undoIndex = self.undoIndex - 1 local actions = transaction.actions for i = #actions, 1, -1 do local action = actions[i] if action.type == "insertText" then document:deleteText(config, action.start, action["end"]) else document:insertText(config, action.start, action.text) end end -- [Port] cursors live on the editor; it is replaced by a copy of the saved state editor.cursors = transaction:getBeforeState():copy() self.version = self.version + 1 if self.callback then self.callback(makeChanges(transaction, true)) end end -- redo the last undone transaction function Transactions:redo(config, document, editor) self.undoIndex = self.undoIndex + 1 local transaction = self.list[self.undoIndex] for _, action in ipairs(transaction.actions) do if action.type == "insertText" then document:insertText(config, action.start, action.text) else document:deleteText(config, action.start, action["end"]) end end editor.cursors = transaction:getAfterState():copy() self.version = self.version + 1 if self.callback then self.callback(makeChanges(transaction, false)) end end function Transactions:canUndo() return self.undoIndex > 0 end function Transactions:canRedo() return self.undoIndex < #self.list end function Transactions:getUndoIndex() return self.undoIndex end function Transactions:getVersion() return self.version end TextEditor.Transactions = Transactions -- -- Color palettes -- local IM_COL32 = G.IM_COL32 local darkPalette = { IM_COL32(224, 224, 224, 255), -- text IM_COL32(197, 134, 192, 255), -- keyword IM_COL32( 90, 179, 155, 255), -- declaration IM_COL32(181, 206, 168, 255), -- number IM_COL32(206, 145, 120, 255), -- string IM_COL32(255, 255, 153, 255), -- punctuation IM_COL32( 64, 192, 128, 255), -- preprocessor IM_COL32(156, 220, 254, 255), -- identifier IM_COL32( 79, 193, 255, 255), -- known identifier IM_COL32(106, 153, 85, 255), -- comment IM_COL32( 30, 30, 30, 255), -- background IM_COL32(224, 224, 224, 255), -- cursor IM_COL32( 32, 96, 160, 255), -- selection IM_COL32( 80, 80, 80, 255), -- whitespace IM_COL32( 70, 70, 70, 255), -- matchingBracketBackground IM_COL32(140, 140, 140, 255), -- matchingBracketActive IM_COL32(246, 222, 36, 255), -- matchingBracketLevel1 IM_COL32( 66, 120, 198, 255), -- matchingBracketLevel2 IM_COL32(213, 96, 213, 255), -- matchingBracketLevel3 IM_COL32(198, 8, 32, 255), -- matchingBracketError IM_COL32(128, 128, 144, 255), -- line number IM_COL32(224, 224, 240, 255), -- current line number IM_COL32(255, 255, 255, 8), -- current line highlight IM_COL32(255, 255, 255, 16), -- current line highlight border } local lightPalette = { IM_COL32( 64, 64, 64, 255), -- text IM_COL32(170, 0, 220, 255), -- keyword IM_COL32( 65, 0, 255, 255), -- declaration IM_COL32( 40, 140, 90, 255), -- number IM_COL32(160, 32, 32, 255), -- string IM_COL32( 0, 0, 0, 255), -- punctuation IM_COL32( 96, 96, 64, 255), -- preprocessor IM_COL32( 64, 64, 64, 255), -- identifier IM_COL32( 16, 96, 96, 255), -- known identifier IM_COL32( 35, 135, 5, 255), -- comment IM_COL32(255, 255, 255, 255), -- background IM_COL32( 0, 0, 0, 255), -- cursor IM_COL32( 0, 0, 96, 64), -- selection IM_COL32(144, 144, 144, 144), -- whitespace IM_COL32(180, 180, 180, 144), -- matchingBracketBackground IM_COL32( 72, 72, 72, 255), -- matchingBracketActive IM_COL32( 70, 0, 250, 255), -- matchingBracketLevel1 IM_COL32( 80, 160, 70, 255), -- matchingBracketLevel2 IM_COL32(120, 60, 25, 255), -- matchingBracketLevel3 IM_COL32(198, 8, 32, 255), -- matchingBracketError IM_COL32( 0, 80, 80, 255), -- line number IM_COL32( 0, 0, 0, 255), -- current line number IM_COL32( 0, 0, 0, 8), -- current line highlight IM_COL32( 0, 0, 0, 16), -- current line highlight border } -- [Port] palettes are returned as copies so callers can't mutate the built-in ones function TextEditor.GetDarkPalette() return table.clone(darkPalette) end function TextEditor.GetLightPalette() return table.clone(lightPalette) end local defaultPalette = table.clone(darkPalette) function TextEditor.SetDefaultPalette(value) defaultPalette = table.clone(value) end function TextEditor.GetDefaultPalette() return defaultPalette end -- -- Language support -- -- [Port] a Language is a plain table with upstream's fields: -- name, caseSensitive, preprocess (codepoint or nil), singleLineComment, singleLineCommentAlt, -- commentStart, commentEnd, commentLevelStart, commentLevelEnd, hasSingleQuotedStrings, -- hasDoubleQuotedStrings, otherStringStart, otherStringEnd, otherStringAltStart, otherStringAltEnd, -- stringEscape (codepoint or nil), stringLevelStart, stringLevelEnd, indentationForBlocks, -- keywords/declarations/identifiers (sets: { [word] = true }), isPunctuation(codepoint), -- getIdentifier, getNumber, customTokenizer. -- [Port] Iterator replacement: tokenizer functions receive (text, i) where `text` is the line encoded as one -- byte per glyph (codepoints >= 128 become "\128") and `i` is the 1-based glyph index of the token start. -- They return the index after the token (returning `i` means no token was found). Level functions return -- (end, level); customTokenizer returns (end, color). Delimiter strings must be ASCII. -- local Language = {} TextEditor.Language = Language TextEditor.LanguageDefinition = Language -- [Port] classic API alias local function makeSet(list) local set = {} for _, word in ipairs(list) do set[word] = true end return set end local function makePunctuation(chars) local set = {} for i = 1, #chars do set[string.byte(chars, i)] = true end return function(codepoint) return set[codepoint] == true end end -- [Port] Luau patterns replace upstream's re2c generated scanners; the first (longest-first) match wins local function patternScanner(patterns) return function(text, i) for _, pattern in ipairs(patterns) do local _, e = string.find(text, pattern, i) if e then return e + 1 end end return i end end -- [Port] isXidStart/isXidContinue: ASCII rules, every non-ASCII glyph is accepted local function getCStyleIdentifier(text, i) local _, e = string.find(text, "^[%a_\128][%w_\128]*", i) if e then return e + 1 end return i end local getCStyleNumber = patternScanner({ "^0[xX]%x+[uUlL]*", "^0[bB][01]+[uUlL]*", "^%d+%.?%d*[eE][%+%-]?%d+[fFlL]?", "^%.%d+[eE][%+%-]?%d+[fFlL]?", "^%d+%.%d*[fFlL]?", "^%.%d+[fFlL]?", "^%d+[uUlL]*", }) local getLuaStyleNumber = patternScanner({ "^0[xX]%x*%.?%x*[pP][%+%-]?%d+", "^0[xX]%x+%.?%x*", "^0[xX]%.%x+", "^%d+%.?%d*[eE][%+%-]?%d+", "^%.%d+[eE][%+%-]?%d+", "^%d+%.?%d*", "^%.%d+", }) local isCStylePunctuation = makePunctuation("!%&()*+,-./:;<=>?[]^{|}~") -- []{}!%#^&*()-+=~|<>?:/;,. local isLuaStylePunctuation = makePunctuation("[]{}!%#^&*()-+=~|<>?:/;,.") local function luaCommentLevelStart(text, i) local _, e, eq = string.find(text, "^%-%-%[(=*)%[", i) if e then return e + 1, #eq end return i, 0 end local function luaCommentLevelEnd(text, i) local _, e, eq = string.find(text, "^%](=*)%]", i) if e then return e + 1, #eq end return i, 0 end local function luaStringLevelStart(text, i) local _, e, eq = string.find(text, "^%[(=*)%[", i) if e then return e + 1, #eq end return i, 0 end local luaStringLevelEnd = luaCommentLevelEnd local cLanguage, cppLanguage, luaLanguage function Language.C() if not cLanguage then cLanguage = { name = "C", caseSensitive = true, preprocess = string.byte("#"), singleLineComment = "//", commentStart = "/*", commentEnd = "*/", hasSingleQuotedStrings = true, hasDoubleQuotedStrings = true, stringEscape = string.byte("\\"), keywords = makeSet({ "break", "case", "continue", "default", "do", "else", "for", "goto", "if", "return", "sizeof", "switch", "while", "_Alignas", "_Alignof", "_Atomic", "_Bool", "_Complex", "_Generic", "_Imaginary", "_Noreturn", "_Static_assert", "_Thread_local", }), declarations = makeSet({ "auto", "char", "const", "double", "enum", "extern", "float", "inline", "int", "long", "register", "restrict", "short", "signed", "static", "struct", "typedef", "union", "unsigned", "void", "volatile", }), identifiers = {}, isPunctuation = isCStylePunctuation, getIdentifier = getCStyleIdentifier, getNumber = getCStyleNumber, } end return cLanguage end function Language.Cpp() if not cppLanguage then cppLanguage = { name = "C++", caseSensitive = true, preprocess = string.byte("#"), singleLineComment = "//", commentStart = "/*", commentEnd = "*/", hasSingleQuotedStrings = true, hasDoubleQuotedStrings = true, stringEscape = string.byte("\\"), keywords = makeSet({ "alignas", "alignof", "and", "and_eq", "asm", "atomic_cancel", "atomic_commit", "atomic_noexcept", "bitand", "bitor", "break", "case", "catch", "compl", "const_cast", "continue", "default", "delete", "do", "dynamic_cast", "else", "explicit", "export", "extern", "false", "for", "goto", "if", "import", "new", "noexcept", "not", "not_eq", "nullptr", "operator", "or", "or_eq", "reinterpret_cast", "requires", "return", "sizeof", "static_assert", "static_cast", "switch", "synchronized", "this", "thread_local", "throw", "true", "try", "while", "xor", "xor_eq", }), declarations = makeSet({ "auto", "bool", "char", "char8_t", "char16_t", "char32_t", "class", "concept", "const", "constexpr", "decltype", "double", "explicit", "export", "extern", "enum", "extern", "float", "friend", "inline", "int", "long", "module", "mutable", "namespace", "private", "protected", "public", "register", "restrict", "short", "signed", "static", "struct", "template", "typedef", "typeid", "typename", "union", "using", "unsigned", "virtual", "void", "volatile", "wchar_t", }), identifiers = {}, isPunctuation = isCStylePunctuation, getIdentifier = getCStyleIdentifier, getNumber = getCStyleNumber, } end return cppLanguage end function Language.Lua() if not luaLanguage then luaLanguage = { name = "Lua", caseSensitive = true, singleLineComment = "--", commentLevelStart = luaCommentLevelStart, commentLevelEnd = luaCommentLevelEnd, hasSingleQuotedStrings = true, hasDoubleQuotedStrings = true, stringLevelStart = luaStringLevelStart, stringLevelEnd = luaStringLevelEnd, stringEscape = string.byte("\\"), keywords = makeSet({ "and", "break", "do", "else", "elseif", "end", "false", "for", "function", "goto", "if", "in", "local", "nil", "not", "or", "repeat", "return", "then", "true", "until", "while", }), declarations = {}, identifiers = makeSet({ "_G", "_VERSION", "abs", "acos", "asin", "assert", "atan", "atan2", "byte", "ceil", "char", "clock", "close", "collectgarbage", "concat", "coroutine", "cos", "cosh", "cpath", "create", "date", "debug", "deg", "difftime", "dofile", "dump", "error", "execute", "exit", "exp", "find", "floor", "flush", "fmod", "format", "frexp", "getenv", "getfenv", "gethook", "getinfo", "getlocal", "getmetatable", "getregistry", "getupvalue", "gmatch", "gsub", "huge", "input", "insert", "io", "ipairs", "ldexp", "len", "lines", "load", "loaded", "loaders", "loadfile", "loadlib", "loadstring", "log", "log10", "lower", "match", "math", "max", "maxn", "min", "modf", "module", "next", "open", "os", "output", "package", "pairs", "path", "pcall", "pi", "popen", "pow", "preload", "print", "rad", "random", "randomseed", "rawequal", "rawget", "rawset", "read", "remove", "rename", "rep", "require", "resume", "reverse", "running", "seeall", "seek", "select", "setfenv", "sethook", "setlocal", "setlocale", "setmetatable", "setupvalue", "setvbuf", "sin", "sinh", "sort", "sqrt", "status", "stderr", "stdin", "stdout", "string", "sub", "table", "tan", "tanh", "time", "tmpfile", "tmpname", "tonumber", "tostring", "traceback", "type", "unpack", "upper", "wrap", "write", "xpcall", "yield", }), isPunctuation = isLuaStylePunctuation, getIdentifier = getCStyleIdentifier, getNumber = getLuaStyleNumber, } end return luaLanguage end -- [Port] TODO: Cs, AngelScript, Python, Glsl, Hlsl, Json, Markdown, Sql -- -- Colorizer: overlay to colorize text (based on language tokenizing) -- local Colorizer = {} Colorizer.__index = Colorizer function Colorizer.new() return setmetatable({ language = nil }, Colorizer) end -- set color for specified range of glyphs (1-based, end exclusive) local function setColor(line, s, e, color) for i = s, e - 1 do line[i].color = color end end -- [Port] encode a line as one byte per glyph so Luau patterns can scan it (see Language notes) local function lineToText(line) local bytes = table.create(#line) for i, glyph in ipairs(line) do local cp = glyph.codepoint if cp >= 128 then cp = 128 end bytes[i] = string.char(cp) end return table.concat(bytes) end -- see if text at glyph i matches provided string local function matches(text, i, str) return string.sub(text, i, i + #str - 1) == str end -- update color in a single line function Colorizer:updateLine(line) -- initialize local variables local language = self.language local state = line.state local nonWhiteSpace = false local text = lineToText(line) local glyph = 1 local e = #line + 1 local isWhiteSpace = CodePoint.isWhiteSpace -- process all glyphs on this line while glyph < e do -- start parsing glyphs local start = glyph local codepoint = line[glyph].codepoint if state == LineState.inText then -- special handling for preprocessor lines if not nonWhiteSpace and language.preprocess and codepoint ~= language.preprocess and not isWhiteSpace(codepoint) then nonWhiteSpace = true end -- are we starting a multilevel, multiline comment if language.commentLevelStart then local tokenEnd, level = language.commentLevelStart(text, glyph) if tokenEnd ~= glyph then state = commentLevelToLineState(math.min(level, maxCommentLevel)) setColor(line, glyph, tokenEnd, Color.comment) glyph = tokenEnd end end -- are we starting a multilevel, multiline string if glyph == start and language.stringLevelStart then local tokenEnd, level = language.stringLevelStart(text, glyph) if tokenEnd ~= glyph then state = stringLevelToLineState(math.min(level, maxStringLevel)) setColor(line, glyph, tokenEnd, Color.string) glyph = tokenEnd end end if glyph == start then local commentStart = language.commentStart local singleLineComment = language.singleLineComment local singleLineCommentAlt = language.singleLineCommentAlt local otherStringStart = language.otherStringStart local otherStringAltStart = language.otherStringAltStart -- mark whitespace characters if isWhiteSpace(codepoint) then line[glyph].color = Color.whitespace glyph = glyph + 1 -- are we starting a multiline comment elseif commentStart and #commentStart > 0 and matches(text, glyph, commentStart) then state = LineState.inComment setColor(line, glyph, glyph + #commentStart, Color.comment) glyph = glyph + #commentStart -- handle single line comments elseif singleLineComment and #singleLineComment > 0 and matches(text, glyph, singleLineComment) then setColor(line, glyph, e, Color.comment) glyph = e elseif singleLineCommentAlt and #singleLineCommentAlt > 0 and matches(text, glyph, singleLineCommentAlt) then setColor(line, glyph, e, Color.comment) glyph = e -- are we starting a special string elseif otherStringStart and #otherStringStart > 0 and matches(text, glyph, otherStringStart) then state = LineState.inOtherString setColor(line, glyph, glyph + #otherStringStart, Color.string) glyph = glyph + #otherStringStart elseif otherStringAltStart and #otherStringAltStart > 0 and matches(text, glyph, otherStringAltStart) then state = LineState.inOtherStringAlt setColor(line, glyph, glyph + #otherStringAltStart, Color.string) glyph = glyph + #otherStringAltStart -- are we starting a single quoted string elseif language.hasSingleQuotedStrings and codepoint == 39 then state = LineState.inSingleQuotedString line[glyph].color = Color.string glyph = glyph + 1 -- are we starting a double quoted string elseif language.hasDoubleQuotedStrings and codepoint == 34 then state = LineState.inDoubleQuotedString line[glyph].color = Color.string glyph = glyph + 1 -- is this a preprocessor line elseif language.preprocess and not nonWhiteSpace and codepoint == language.preprocess then setColor(line, 1, e, Color.preprocessor) glyph = e end end if glyph == start then -- nothing worked so far so it's time to do some tokenizing local tokenEnd, color = glyph, nil if language.customTokenizer then tokenEnd, color = language.customTokenizer(text, glyph) end -- handle custom tokenizer (if we have one) if tokenEnd ~= glyph then setColor(line, glyph, tokenEnd, color) glyph = tokenEnd else if language.getIdentifier then tokenEnd = language.getIdentifier(text, glyph) end -- do we have an identifier if tokenEnd ~= glyph then -- determine identifier text and color local parts = {} for i = glyph, tokenEnd - 1 do parts[#parts + 1] = utf8.char(line[i].codepoint) end local identifier = table.concat(parts) if language.caseSensitive == false then identifier = string.lower(identifier) end color = Color.identifier if language.keywords and language.keywords[identifier] then color = Color.keyword elseif language.declarations and language.declarations[identifier] then color = Color.declaration elseif language.identifiers and language.identifiers[identifier] then color = Color.knownIdentifier end -- colorize identifier and move on setColor(line, glyph, tokenEnd, color) glyph = tokenEnd else if language.getNumber then tokenEnd = language.getNumber(text, glyph) end -- do we have a number if tokenEnd ~= glyph then setColor(line, glyph, tokenEnd, Color.number) glyph = tokenEnd -- is this punctuation elseif language.isPunctuation and language.isPunctuation(codepoint) then line[glyph].color = Color.punctuation glyph = glyph + 1 else -- I guess we don't know what this character is line[glyph].color = Color.text glyph = glyph + 1 end end end end elseif lineStateInComment(state) then -- stay in comment state until we see the end sequence local commentEnd = language.commentEnd if commentEnd and #commentEnd > 0 and matches(text, glyph, commentEnd) then setColor(line, glyph, glyph + #commentEnd, Color.comment) glyph = glyph + #commentEnd state = LineState.inText elseif language.commentLevelEnd then local tokenEnd, level = language.commentLevelEnd(text, glyph) if tokenEnd ~= glyph and state == commentLevelToLineState(math.min(level, maxCommentLevel)) then setColor(line, glyph, tokenEnd, Color.comment) glyph = tokenEnd state = LineState.inText end end -- [Port] bounds guard: a level end token at end of line would otherwise index past it if lineStateInComment(state) and glyph < e then line[glyph].color = Color.comment glyph = glyph + 1 end elseif lineStateInStringLevel(state) then -- stay in string level until matching closing is detected local tokenEnd, level = language.stringLevelEnd(text, glyph) if tokenEnd ~= glyph and state == stringLevelToLineState(math.min(level, maxStringLevel)) then setColor(line, glyph, tokenEnd, Color.string) glyph = tokenEnd state = LineState.inText else line[glyph].color = Color.string glyph = glyph + 1 end else -- inOtherString, inOtherStringAlt, inSingleQuotedString or inDoubleQuotedString -- stay in string state until we see the end sequence, skip escaped characters local endString if state == LineState.inOtherString then endString = language.otherStringEnd elseif state == LineState.inOtherStringAlt then endString = language.otherStringAltEnd elseif state == LineState.inSingleQuotedString then endString = "'" else endString = '"' end if codepoint == language.stringEscape then line[glyph].color = Color.string glyph = glyph + 1 if glyph < e then line[glyph].color = Color.string glyph = glyph + 1 end elseif matches(text, glyph, endString) then setColor(line, glyph, glyph + #endString, Color.string) glyph = glyph + #endString state = LineState.inText else line[glyph].color = Color.string glyph = glyph + 1 end end end return state end -- update state (if required) function Colorizer:update(config, document) -- update all lines on configuration change local configChanged = self.language ~= config.language local lines = document.lines local n = #lines if configChanged then self.language = config.language for l = 1, n do local line = lines[l] if self.language then local state = self:updateLine(line) if l < n then lines[l + 1].state = state end else for _, glyph in ipairs(line) do glyph.color = Color.text end line.state = LineState.inText end line.needsColorizing = false end -- update changed lines when document is updated elseif document.updated then for l = 1, n do local line = lines[l] if line.needsColorizing then if self.language then local state = self:updateLine(line) line.needsColorizing = false local nextLine = lines[l + 1] if nextLine and nextLine.state ~= state then nextLine.state = state nextLine.needsColorizing = true end else for _, glyph in ipairs(line) do glyph.color = Color.text end line.state = LineState.inText line.needsColorizing = false end end end end -- return status return configChanged end -- -- Bracketeer: overlay to manage details about bracketed text -- a BracketPair is { startChar, start = DocPos, endChar, ["end"] = DocPos, level, visible } -- local openers = { [40] = 41, [123] = 125, [91] = 93 } -- ( { [ local closers = { [41] = 40, [125] = 123, [93] = 91 } -- ) } ] @native local function isBracketCandidate(glyph) local color = glyph.color return color == Color.punctuation or color == Color.matchingBracketLevel1 or color == Color.matchingBracketLevel2 or color == Color.matchingBracketLevel3 or color == Color.matchingBracketError end local function bracketIsAfter(pair, location) return pair.start > location end local function bracketIsAround(pair, location) return pair.start < location and pair["end"] >= location end local Bracketeer = {} Bracketeer.__index = Bracketeer function Bracketeer.new() return setmetatable({ list = {}, showMatchingBrackets = false, language = nil, updated = false }, Bracketeer) end local bracketColors = { Color.matchingBracketLevel1, Color.matchingBracketLevel2, Color.matchingBracketLevel3 } -- [Port] invisible (indentation based) blocks are not generated yet (no language uses indentationForBlocks) @native function Bracketeer:update(config, document) -- see if the configuration changed local configChanged = self.showMatchingBrackets ~= config.showMatchingBrackets or self.language ~= config.language self.showMatchingBrackets = config.showMatchingBrackets self.language = config.language if configChanged and not self.showMatchingBrackets then -- if configuration changed, clear the bracket pair list and reset glyph colors table.clear(self.list) for _, line in ipairs(document.lines) do for _, glyph in ipairs(line) do local color = glyph.color if color == Color.matchingBracketLevel1 or color == Color.matchingBracketLevel2 or color == Color.matchingBracketLevel3 or color == Color.matchingBracketError then glyph.color = Color.punctuation end end end elseif self.showMatchingBrackets and (configChanged or document.updated) then -- if configuration or document changed, recalculate bracket pair list local previous = self.list local list = {} local levels = {} local level = 0 -- process all the glyphs -- [Port] the (disjoint) opener/closer lookups come before the colour test: most glyphs are neither for l, line in ipairs(document.lines) do for i, glyph in ipairs(line) do local codepoint = glyph.codepoint -- handle a "bracket opener" that is not in a comment, string or preprocessor statement if openers[codepoint] and isBracketCandidate(glyph) then -- start a new level list[#list + 1] = { startChar = glyph.codepoint, start = newDocPos(l - 1, i - 1), endChar = 0, ["end"] = newDocPos(0, 0), level = level, visible = true } levels[#levels + 1] = #list glyph.color = bracketColors[level % 3 + 1] level = level + 1 -- handle a "bracket closer" that is not in a comment, string or preprocessor statement elseif closers[codepoint] and isBracketCandidate(glyph) then if #levels > 0 then local lastBracket = list[table.remove(levels)] level = level - 1 if lastBracket.startChar == closers[glyph.codepoint] then -- handle matching bracket glyph.color = bracketColors[level % 3 + 1] lastBracket.endChar = glyph.codepoint lastBracket["end"] = newDocPos(l - 1, i - 1) else -- no matching bracket, mark brackets as errors glyph.color = Color.matchingBracketError document:at(lastBracket.start.line)[lastBracket.start.index + 1].color = Color.matchingBracketError table.remove(list) end -- this is a closer without an opener else glyph.color = Color.matchingBracketError end end end end -- handle levels left open and mark them as errors for j = #levels, 1, -1 do local s = list[levels[j]].start document:at(s.line)[s.index + 1].color = Color.matchingBracketError table.remove(list, levels[j]) end self.list = list -- see if things have changed local changed = #previous ~= #list for j = 1, #list do if changed then break end changed = previous[j].start ~= list[j].start or previous[j]["end"] ~= list[j]["end"] end self.updated = changed end end -- find relevant brackets (returns a BracketPair or nil) function Bracketeer:getEnclosingBrackets(first, last) last = last or first local brackets = nil for _, pair in ipairs(self.list) do -- brackets are sorted so no need to go past specified location if bracketIsAfter(pair, first) then break elseif bracketIsAround(pair, first) and bracketIsAround(pair, last) then -- this could be what we're looking for brackets = pair end end return brackets end function Bracketeer:getInnerBrackets(first, last) local list = self.list local outer = self:getEnclosingBrackets(first, last) if outer then local start = table.find(list, outer) for j = start + 1, #list do local pair = list[j] if pair.level <= outer.level then break elseif pair.level == outer.level + 1 and pair.start > first and pair["end"] < last then return pair end end end return nil end function Bracketeer:isUpdated() return self.updated end function Bracketeer:resetUpdated() self.updated = false end TextEditor.Colorizer = Colorizer TextEditor.Bracketeer = Bracketeer -- -- TextEditor -- -- constructor function TextEditor.new() local self = setmetatable({}, TextEditor) self.config = { tabSize = 4, insertSpacesOnTabs = false, lineSpacing = 1.0, readOnly = false, caretsVisible = true, autoIndent = true, showSpaces = true, showTabs = true, showLineNumbers = true, showCurrentLineHighlight = true, showMatchingBrackets = true, completePairedGlyphs = true, overwrite = false, leftMargin = 1, textMargin = 2, language = nil, panMode = false, findReplaceEnabled = true, } self.document = Document.new() self.cursors = Cursors.new() self.transactions = Transactions.new() self.colorizer = Colorizer.new() self.bracketeer = Bracketeer.new() self:SetPalette(defaultPalette) -- rendering state self.markers = {} self.firstFrame = true self.focusOnEditor = false self.totalSize = ImVec2(0, 0) self.glyphSize = ImVec2(1, 1) self.textSize = ImVec2(0, 0) self.cursorScreenPos = ImVec2(0, 0) self.lineNumberLeftOffset, self.lineNumberRightOffset = 0, 0 self.textLeftOffset, self.textRightOffset = 0, 0 self.cursorWidth = 1 self.navigatingVertically = false self.selectingText = false self.lastClickTime = -1 self.completePairCloser = 0 self.completePairLocation = newDocPos(0, 0) self.popupDocPos = newDocPos(0, 0) self.panning = false self.scrolling = false self.scrollStart = ImVec2(0, 0) -- find and replace context self.findButtonLabel = "Find" self.findAllButtonLabel = "Find All" self.replaceButtonLabel = "Replace" self.replaceAllButtonLabel = "Replace All" self.findReplaceVisible = false self.focusOnFind = false self.findText = "" self.replaceText = "" self.caseSensitiveFind = false self.wholeWordFind = false self:resetScrolling() return self end function TextEditor:reset() self.document = Document.new() -- [Port] a fresh document needs a full recolor/rebracket self.colorizer.language = nil self.bracketeer.language = nil self.transactions:reset() self.cursors:clearAll() self:clearMarkers() -- [Port] squiggles not ported yet self:resetScrolling() end -- [Port] normalize helpers accept DocPos or any { line, index } table function TextEditor:normalizePos(pos) return self.document:normalizePos(pos) end function TextEditor:normalizeLine(line) return self.document:normalizeLine(line) end -- configuration function TextEditor:SetTabSize(value) self.config.tabSize = value end function TextEditor:GetTabSize() return self.config.tabSize end function TextEditor:SetInsertSpacesOnTabs(value) self.config.insertSpacesOnTabs = value end function TextEditor:IsInsertSpacesOnTabs() return self.config.insertSpacesOnTabs end function TextEditor:SetReadOnlyEnabled(value) self.config.readOnly = value end function TextEditor:IsReadOnlyEnabled() return self.config.readOnly end -- [Port] short aliases TextEditor.SetReadOnly = TextEditor.SetReadOnlyEnabled TextEditor.IsReadOnly = TextEditor.IsReadOnlyEnabled function TextEditor:SetShowMatchingBrackets(value) self.config.showMatchingBrackets = value end function TextEditor:IsShowingMatchingBrackets() return self.config.showMatchingBrackets end -- color palette support -- [Port] no style alpha is applied yet (updatePalettes is part of rendering) function TextEditor:SetPalette(newPalette) self.paletteBase = table.clone(newPalette) end function TextEditor:GetPalette() return self.paletteBase end -- language support function TextEditor:SetLanguage(language) self.config.language = language if self.languageChangeCallback then self.languageChangeCallback() end end function TextEditor:GetLanguage() return self.config.language end function TextEditor:HasLanguage() return self.config.language ~= nil end function TextEditor:GetLanguageName() if self.config.language == nil then return "None" end return self.config.language.name end function TextEditor:SetLanguageChangeCallback(callback) self.languageChangeCallback = callback end -- [Port] classic API alias TextEditor.SetLanguageDefinition = TextEditor.SetLanguage -- [Port] color of glyph at position (upstream's Document::getColor); runs updateState first function TextEditor:GetGlyphColor(pos) self:updateState() return self.document:getColor(self:normalizePos(pos)) end function TextEditor:SelectToBrackets(includeBrackets) if includeBrackets == nil then includeBrackets = true end self:selectToBrackets(includeBrackets) end -- set/get editor text (UTF-8 encoded) -- [Port] a table of lines is accepted too (upstream's std::vector overload) function TextEditor:SetText(text) self:reset() if type(text) == "table" then text = table.concat(text, "\n") end self.document:setUtf8Text(self.config, text) end function TextEditor:GetText() return self.document:getUtf8Text() end -- get part of text from editor as UTF-8 encoded strings function TextEditor:GetSectionText(s, e) if e == nil then s, e = s.start, s["end"] end return self.document:getSectionText(self:normalizePos(s), self:normalizePos(e)) end function TextEditor:GetCursorText(cursor) if cursor < self.cursors:size() then local c = self.cursors:at(cursor) return self.document:getSectionText(c:getSelectionStart(), c:getSelectionEnd()) end return "" end function TextEditor:GetLineText(line) if line < self.document:size() then return self.document:getLineText(line) end return "" end -- [Port] convenience: text of the current cursor's selection function TextEditor:GetSelectedText() return self:GetCursorText(self.cursors:getCurrentIndex()) end function TextEditor:ReplaceSectionText(s, e, text) if text == nil then text = e; s, e = s.start, s["end"] end if not self.config.readOnly then self:replaceSectionText(self:normalizePos(s), self:normalizePos(e), text) end end function TextEditor:ClearText() self:SetText("") end function TextEditor:IsEmpty() return self.document:isEmpty() end function TextEditor:GetLineCount() return self.document:size() end -- clipboard-free editing operations function TextEditor:Undo() if not self.config.readOnly then self:undo() end end function TextEditor:Redo() if not self.config.readOnly then self:redo() end end function TextEditor:CanUndo() return not self.config.readOnly and self.transactions:canUndo() end function TextEditor:CanRedo() return not self.config.readOnly and self.transactions:canRedo() end function TextEditor:GetUndoIndex() return self.transactions:getUndoIndex() end -- manage cursors and selections function TextEditor:SelectAll() self:selectAll() end function TextEditor:SelectLine(line) self:selectLine(self:normalizeLine(line)) end function TextEditor:SelectLines(s, e) if e < self.document:size() and s <= e then self:selectLines(s, e) end end function TextEditor:SelectRegion(s, e) self:selectRegion(self:normalizePos(s), self:normalizePos(e)) end function TextEditor:AnyCursorHasSelection() return self.cursors:anyHasSelection() end function TextEditor:AllCursorsHaveSelection() return self.cursors:allHaveSelection() end function TextEditor:CursorHasSelection(cursor) return self.cursors:cursorHasSelection(cursor) end function TextEditor:MainCursorHasSelection() return self.cursors:mainCursorHasSelection() end function TextEditor:CurrentCursorHasSelection() return self.cursors:currentCursorHasSelection() end -- [Port] convenience alias TextEditor.HasSelection = TextEditor.AnyCursorHasSelection function TextEditor:ClearCursors() self.cursors:clearAll() end -- [Port] upstream adds cursors via mouse/keyboard only; exposed here for multi-cursor scripting function TextEditor:AddCursor(s, e) s = self:normalizePos(s) if e == nil then e = s else e = self:normalizePos(e) end self.cursors:addCursor(s, e) self.cursors:update(self.document) end -- get cursor positions function TextEditor:GetNumberOfCursors() return self.cursors:size() end function TextEditor:GetCursorPosition(cursor) return self:getCursorPosition(cursor) end function TextEditor:GetMainCursorPosition() return self:getCursorPosition(self.cursors:getMainIndex()) end function TextEditor:GetCurrentCursorPosition() return self:getCursorPosition(self.cursors:getCurrentIndex()) end function TextEditor:GetCursorSelection(cursor) return self:getCursorSelection(cursor) end function TextEditor:GetMainCursorSelection() return self:getCursorSelection(self.cursors:getMainIndex()) end function TextEditor:GetCurrentCursorSelection() return self:getCursorSelection(self.cursors:getCurrentIndex()) end -- specify a new cursor position function TextEditor:SetCursor(pos) self:setCursor(self:normalizePos(pos)) end -- word boundaries function TextEditor:FindWordStart(pos, wholeWord) return self.document:findWordStart(self:normalizePos(pos), wholeWord) end function TextEditor:FindWordEnd(pos, wholeWord) return self.document:findWordEnd(self:normalizePos(pos), wholeWord) end function TextEditor:ReplaceTextInCurrentCursor(text) if not self.config.readOnly then self:replaceTextInCurrentCursor(text) end end function TextEditor:ReplaceTextInAllCursors(text) if not self.config.readOnly then self:replaceTextInAllCursors(text) end end -- specify a transaction callback: callback(changes), change = { insert, start, end, text } function TextEditor:SetTransactionCallback(callback) self.transactions.callback = callback end function TextEditor:ClearTransactionCallback() self.transactions.callback = nil end function TextEditor:HasTransactionCallback() return self.transactions.callback ~= nil end -- -- private implementation -- function TextEditor:selectAll() self:moveTo(self.document:getTop(), false) self:moveTo(self.document:getBottom(), true) end function TextEditor:selectLine(line) self:moveTo(newDocPos(line, 0), false) self:moveTo(self:normalizePos(newDocPos(line + 1, 0)), true) end function TextEditor:selectLines(startLine, endLine) self:moveTo(newDocPos(startLine, 0), false) self:moveTo(newDocPos(endLine, 0), true) end function TextEditor:selectRegion(s, e) if e < s then s, e = e, s end self.cursors:setCursor(s, e) end -- handle possible changes caused by the API or user interactions -- [Port] no folding/typesetter/minimap: a row is a line, the column count is the widest line function TextEditor:updateState() self.colorizer:update(self.config, self.document) self.bracketeer:update(self.config, self.document) self.cursors:update(self.document) local documentChanged = self.document.updated -- [Port] marker/squiggle compression not needed: markers are stored on the line tables -- reset overlay "dirty" flags self.document.updated = false self.bracketeer:resetUpdated() -- get "new" total editor size in pixels -- [Port] the widest line is looked for only when the document (or tab size) changed (every edit goes through -- Document:setUtf8Text/insertText/deleteText, which set document.updated), using the column count cached on -- each line (cleared by insertText/deleteText on the lines they change; new lines have none) local tabSize = self.config.tabSize local columns = self.maxColumns if documentChanged or columns == nil or self.maxColumnsDocument ~= self.document or self.maxColumnsTabSize ~= tabSize then columns = self.maxLineColumns(self.document.lines, tabSize) self.maxColumns, self.maxColumnsDocument, self.maxColumnsTabSize = columns, self.document, tabSize end local width = self.textLeftOffset + columns * self.glyphSize.x + self.cursorWidth local height = self.document:size() * self.glyphSize.y self.totalSize = ImVec2(width, height) return documentChanged end function TextEditor:selectToBrackets(includeBrackets) self:updateState() for _, cursor in ipairs(self.cursors.list) do local bracket = self.bracketeer:getEnclosingBrackets(cursor:getSelectionStart()) if bracket then if includeBrackets then cursor:update(bracket.start, self.document:getRight(bracket["end"])) else cursor:update(self.document:getRight(bracket.start), bracket["end"]) end end end end function TextEditor:moveTo(coordinate, select) self.cursors:clearAdditional() self.cursors:updateCurrentCursor(coordinate, select and true or false) self:makeCursorVisible() self.navigatingVertically = false end function TextEditor:undo() if self.transactions:canUndo() then self.transactions:undo(self.config, self.document, self) self:makeCursorVisible() end end function TextEditor:redo() if self.transactions:canRedo() then self.transactions:redo(self.config, self.document, self) self:makeCursorVisible() end end function TextEditor:getCursorPosition(cursor) cursor = math.min(cursor or 0, self.cursors:size() - 1) return self.cursors:at(cursor):getInteractiveEnd() end function TextEditor:getCursorSelection(cursor) cursor = math.min(cursor or 0, self.cursors:size() - 1) local c = self.cursors:at(cursor) return newDocSelection(c:getSelectionStart(), c:getSelectionEnd()) end function TextEditor:setCursor(pos) self.ensureVisiblePos = pos self.cursors:setCursor(pos) end function TextEditor:startTransaction() local transaction = Transaction.new() transaction:setBeforeState(self.cursors) return transaction end function TextEditor:endTransaction(transaction) if transaction:size() > 0 then self.cursors:update(self.document) transaction:setAfterState(self.cursors) self.transactions:add(transaction) return true end return false end function TextEditor:insertTextIntoAllCursors(transaction, text) -- delete any selection content first self:deleteTextFromAllCursors(transaction) -- insert the text local cursors = self.cursors for c = 0, cursors:size() - 1 do local cursor = cursors:at(c) local s = cursor:getSelectionStart() local e = self:insertText(transaction, s, text) cursor:update(e, false) cursors:adjustForInsert(c, s, e) end end function TextEditor:deleteTextFromAllCursors(transaction) local cursors = self.cursors for c = 0, cursors:size() - 1 do local cursor = cursors:at(c) if cursor:hasSelection() then local s = cursor:getSelectionStart() local e = cursor:getSelectionEnd() self:deleteText(transaction, s, e) cursor:update(s, false) cursors:adjustForDelete(c, s, e) end end end -- update document, add transaction and return position of end of insert -- this function does not change the cursors function TextEditor:insertText(transaction, s, text) local e = self.document:insertText(self.config, s, text) transaction:addInsert(s, e, text) return e end -- update document and add transaction -- this function does not change the cursors function TextEditor:deleteText(transaction, s, e) local text = self.document:getSectionText(s, e) self.document:deleteText(self.config, s, e) transaction:addDelete(s, e, text) end function TextEditor:replaceTextInCurrentCursor(text) local transaction = self:startTransaction() -- first delete old text local index = self.cursors:getCurrentIndex() local cursor = self.cursors:getCurrent() local s = cursor:getSelectionStart() local e = cursor:getSelectionEnd() self:deleteText(transaction, s, e) self.cursors:adjustForDelete(index, s, e) -- now insert new text local newEnd = self:insertText(transaction, s, text) cursor:update(newEnd, false) self.cursors:adjustForInsert(index, s, newEnd) self:endTransaction(transaction) end function TextEditor:replaceTextInAllCursors(text) local transaction = self:startTransaction() self:insertTextIntoAllCursors(transaction, text) self:endTransaction(transaction) end function TextEditor:replaceSectionText(s, e, text) local transaction = self:startTransaction() self:deleteText(transaction, s, e) local newEnd = self:insertText(transaction, s, text) self.cursors:clearAdditional() self.cursors:getMain():update(newEnd, newEnd) self:endTransaction(transaction) end -- -- Rendering and user interaction -- -- [Port] no word wrap, folding, typesetter, minimap, squiggles, decorations or autocomplete yet: -- a visual row is a document line and a visual column is the sum of glyph widths (tabs expand to tabSize). -- VisPos values are passed as separate (row, column) numbers. -- do local bor = bit32.bor local Key = G.ImGuiKey local Mod_Ctrl, Mod_Shift, Mod_Alt, Mod_Super = G.ImGuiMod_Ctrl, G.ImGuiMod_Shift, G.ImGuiMod_Alt, G.ImGuiMod_Super local Repeat = G.ImGuiInputFlags.Repeat TextEditor.Scroll = { alignTop = 0, alignMiddle = 1, alignBottom = 2 } @native local function glyphColumns(codepoint, column, tabSize) if codepoint == 9 then return tabSize - column % tabSize end return CodePoint.getGlyphWidth(codepoint) end @native function TextEditor.lineColumns(line, tabSize) local column = 0 for i = 1, #line do column = column + glyphColumns(line[i].codepoint, column, tabSize) end return column end -- [Port] widest line in columns, through the per-line cache (line.columns for line.columnsTabSize) @native function TextEditor.maxLineColumns(lines, tabSize) local lineColumns = TextEditor.lineColumns local columns = 0 for l = 1, #lines do local line = lines[l] local c = line.columns if c == nil or line.columnsTabSize ~= tabSize then c = lineColumns(line, tabSize) line.columns, line.columnsTabSize = c, tabSize end if c > columns then columns = c end end return columns end local function isPairOpener(ch) return ch == 123 or ch == 91 or ch == 40 or ch == 39 or ch == 34 end local function toPairCloser(ch) if ch == 123 then return 125 elseif ch == 91 then return 93 elseif ch == 40 then return 41 end return ch end -- coordinate conversions @native function TextEditor:docPos2VisPos(pos) local line = self.document:at(pos.line) local tabSize = self.config.tabSize local column = 0 for i = 1, math.min(pos.index, #line) do column = column + glyphColumns(line[i].codepoint, column, tabSize) end return pos.line, column end -- [Port] row is clamped to the document (upstream's normalizePos(VisPos)); column snaps to the nearest glyph boundary function TextEditor:visPos2DocPos(row, column) row = math.clamp(row, 0, self.document:size() - 1) local line = self.document:at(row) local tabSize = self.config.tabSize local col, index = 0, 0 while index < #line do local width = glyphColumns(line[index + 1].codepoint, col, tabSize) if col + width * 0.5 > column then break end col = col + width index = index + 1 end return newDocPos(row, index) end -- [Port] typeSetter.screenPos2DocPos: x/y are in (fractional) glyph units; returns glyphPos, cursorPos function TextEditor:screenPos2DocPos(x, y) local row = math.clamp(math.floor(y), 0, self.document:size() - 1) local line = self.document:at(row) local tabSize = self.config.tabSize local col, index = 0, 0 while index < #line do local width = glyphColumns(line[index + 1].codepoint, col, tabSize) if col + width > x then break end col = col + width index = index + 1 end return newDocPos(row, index), self:visPos2DocPos(row, x) end function TextEditor:resetCursorAnimationTimer() self.cursorAnimationTimer = -0.3 end -- public API (rendering related) -- [Port] Render(title, size?, border?|childFlags?, windowFlags?): a boolean third argument is the classic `border` flag function TextEditor:Render(title, size, childFlags, windowFlags) if childFlags == true then childFlags = G.ImGuiChildFlags.Borders elseif type(childFlags) ~= "number" then childFlags = 0 end if windowFlags == nil then windowFlags = bor(G.ImGuiWindowFlags.NoMove, G.ImGuiWindowFlags.HorizontalScrollbar) end return self:render(title, size or ImVec2(0, 0), childFlags, windowFlags) end function TextEditor:SetFocus() self.focusOnEditor = true end function TextEditor:ScrollToLine(line, alignment) self:scrollToLine(self:normalizeLine(line), alignment or TextEditor.Scroll.alignMiddle) end function TextEditor:GetFirstVisibleRow() return self.firstVisibleRow end function TextEditor:GetLastVisibleRow() return self.lastVisibleRow end function TextEditor:GetFirstVisibleColumn() return self.firstVisibleColumn end function TextEditor:GetLastVisibleColumn() return self.lastVisibleColumn end function TextEditor:SetLineSpacing(value) self.config.lineSpacing = math.max(1.0, math.min(2.0, value)) end function TextEditor:GetLineSpacing() return self.config.lineSpacing end function TextEditor:SetCaretsVisible(value) self.config.caretsVisible = value end function TextEditor:SetAutoIndentEnabled(value) self.config.autoIndent = value end function TextEditor:IsAutoIndentEnabled() return self.config.autoIndent end function TextEditor:SetShowWhitespacesEnabled(value) self.config.showSpaces = value; self.config.showTabs = value end function TextEditor:SetShowSpacesEnabled(value) self.config.showSpaces = value end function TextEditor:SetShowTabsEnabled(value) self.config.showTabs = value end function TextEditor:SetShowLineNumbersEnabled(value) self.config.showLineNumbers = value end function TextEditor:IsShowLineNumbersEnabled() return self.config.showLineNumbers end function TextEditor:SetShowCurrentLineHighlightEnabled(value) self.config.showCurrentLineHighlight = value end function TextEditor:SetCompletePairedGlyphs(value) self.config.completePairedGlyphs = value end function TextEditor:SetOverwriteEnabled(value) self.config.overwrite = value end function TextEditor:IsOverwriteEnabled() return self.config.overwrite end function TextEditor:SetLineNumberLeftMargin(value) self.config.leftMargin = value end function TextEditor:SetTextLeftMargin(value) self.config.textMargin = value end function TextEditor:Cut() if not self.config.readOnly then self:cut() end end function TextEditor:Copy() self:copy() end function TextEditor:Paste() if not self.config.readOnly then self:paste() end end -- marker support function TextEditor:AddMarker(line, lineNumberColor, textColor, lineNumberTooltip, textTooltip) self:addMarker(self:normalizeLine(line), lineNumberColor, textColor, lineNumberTooltip or "", textTooltip or "") end function TextEditor:ClearMarkers() self:clearMarkers() end function TextEditor:HasMarkers() return #self.markers > 0 end -- context menus: callback(popupData) with popupData = { pos = DocPos } function TextEditor:SetLineNumberContextMenuCallback(callback) self.lineNumberContextMenuCallback = callback end function TextEditor:ClearLineNumberContextMenuCallback() self.lineNumberContextMenuCallback = nil end function TextEditor:SetTextContextMenuCallback(callback) self.textContextMenuCallback = callback end function TextEditor:ClearTextContextMenuCallback() self.textContextMenuCallback = nil end -- [Port] markers are stored on the line tables, so they follow line inserts/deletes without compressMarkers function TextEditor:addMarker(line, lineNumberColor, textColor, lineNumberTooltip, textTooltip) if line < self.document:size() then local marker = { lineNumberColor = lineNumberColor, textColor = textColor, lineNumberTooltip = lineNumberTooltip, textTooltip = textTooltip } self.markers[#self.markers + 1] = marker self.document:at(line).marker = marker end end function TextEditor:clearMarkers() for _, line in ipairs(self.document.lines) do line.marker = nil end self.markers = {} end -- update palette with style alpha function TextEditor:updatePalettes() local alpha = ImGui.GetStyle().Alpha self.paletteAlpha = alpha self.paletteSource = self.paletteBase local palette = {} for i, color in ipairs(self.paletteBase) do local a = math.floor(bit32.rshift(color, 24) * alpha + 0.5) palette[i] = bor(bit32.band(color, 0x00FFFFFF), bit32.lshift(a, 24)) end self.palette = palette end -- -- TextEditor::render -- function TextEditor:render(title, size, childFlags, windowFlags) -- track content state changes local documentChanged = false -- special handling for first frame as we can't use SetNextWindowFocus during it if not self.firstFrame then -- ensure editor has focus (if required) if self.focusOnEditor then ImGui.SetNextWindowFocus() self.focusOnEditor = false end else self.firstFrame = false end -- update color palette (if required) -- [Port] done before BeginChild so the background color uses the current palette local style = ImGui.GetStyle() if self.palette == nil or self.paletteAlpha ~= style.Alpha or self.paletteSource ~= self.paletteBase then self:updatePalettes() end local palette = self.palette -- start a new child window ImGui.SetNextWindowContentSize(self.totalSize) ImGui.PushStyleVar(G.ImGuiStyleVar.ItemSpacing, ImVec2(0.0, 0.0)) ImGui.PushStyleColor(G.ImGuiCol.ChildBg, ImGui.ColorConvertU32ToFloat4(palette[Color.background])) if ImGui.BeginChild(title, size, childFlags, windowFlags) then -- perform last part of scrolling reset here (as it requires the correct Dear ImGui context) if self.resetDearImGuiScrolling then ImGui.SetScrollX(0.0) ImGui.SetScrollY(0.0) self.resetDearImGuiScrolling = false end -- get drawList self.drawList = ImGui.GetWindowDrawList() -- get font information self.font = ImGui.GetFont() self.fontSize = ImGui.GetFontSize() local fontScaleDpi = style.FontScaleDpi or 1.0 self.fontScaleDpi = fontScaleDpi self.glyphSize = ImVec2(ImGui.CalcTextSize("#").x, ImGui.GetTextLineHeightWithSpacing() * self.config.lineSpacing) local glyphSize = self.glyphSize -- determine current position and visible size self.cursorScreenPos = ImGui.GetCursorScreenPos() local visibleSize = ImGui.GetCurrentWindow().InnerRect:GetSize() -- determine horizontal offsets for line numbers, decorations and text if self.config.showLineNumbers then local digits = math.floor(math.log10(self.document:size() + 1) + 1.0) self.lineNumberLeftOffset = self.config.leftMargin * glyphSize.x self.lineNumberRightOffset = self.lineNumberLeftOffset + digits * glyphSize.x else self.lineNumberLeftOffset = 0.0 self.lineNumberRightOffset = 0.0 end -- [Port] TODO: line folding indicators and decorations self.textLeftOffset = self.lineNumberRightOffset + self.config.textMargin * glyphSize.x -- [Port] TODO: mini map self.textRightOffset = visibleSize.x self.textSize = ImVec2(self.textRightOffset - self.textLeftOffset, visibleSize.y) -- handle possible state changes caused by API calls before first frame or between frames self:updateState() self:handlePossibleScrolling() -- handle keyboard inputs self:handleKeyboardInputs() documentChanged = self:updateState() -- handle mouse inputs self:handleMouseInteractions() -- determine visible row/column limits self.firstVisibleRow = math.floor(ImGui.GetScrollY() / glyphSize.y) self.lastVisibleRow = math.min(math.ceil((ImGui.GetScrollY() + self.textSize.y) / glyphSize.y), self.document:size() - 1) self.firstVisibleColumn = math.floor(ImGui.GetScrollX() / glyphSize.x) self.lastVisibleColumn = math.ceil((ImGui.GetScrollX() + self.textSize.x) / glyphSize.x) -- determine width of cursor self.cursorWidth = style.InputTextCursorSize or (1.0 * fontScaleDpi) -- setup clipping over the text area local drawList = self.drawList local offset = ImGui.GetWindowPos().x drawList:PushClipRect( ImVec2(offset + self.textLeftOffset - self.cursorWidth, drawList:GetClipRectMin().y), ImVec2(offset + self.textRightOffset + self.cursorWidth, drawList:GetClipRectMax().y), true) -- render parts in the text area self:renderCurrentLineHighlight() self:renderActiveBracketBackground() self:renderSelections() self:renderTextMarkers() self:renderMatchingBracketLines() -- [Port] TODO: renderSquiggles self:renderText() self:renderCursorCarets() -- end clipping drawList:PopClipRect() -- render other parts self:renderLineNumberMarkers() self:renderLineNumbers() -- [Port] TODO: renderDecorations, renderFoldIndicators, renderMiniMap, renderScrollbarMiniMap, -- renderPanScrollIndicator self:renderFindReplace() self:renderPopups() -- handle scrolling caused by actions in this frame self:handlePossibleScrolling() -- [Port] TODO: navigation cursor hacks (ImGuiConfigFlags_NavEnableKeyboard/Gamepad) end ImGui.EndChild() ImGui.PopStyleColor() ImGui.PopStyleVar() -- [Port] TODO: delayed change callback return documentChanged end -- -- TextEditor::renderCurrentLineHighlight -- function TextEditor:renderCurrentLineHighlight() if self.config.showCurrentLineHighlight and not self.cursors:anyHasSelection() then local alreadyDrawn = {} local glyphSize = self.glyphSize -- [Port] upstream uses textLeftOffset/textRightOffset without the window x offset; anchored to the window here local left = ImGui.GetWindowPos().x + self.textLeftOffset local right = ImGui.GetWindowPos().x + self.textRightOffset for _, cursor in ipairs(self.cursors.list) do local lineNumber = cursor:getInteractiveEnd().line if not alreadyDrawn[lineNumber] then alreadyDrawn[lineNumber] = true local topLeft = ImVec2(left, self.cursorScreenPos.y + lineNumber * glyphSize.y) local bottomRight = ImVec2(right, topLeft.y + glyphSize.y) self.drawList:AddRectFilled(topLeft, bottomRight, self.palette[Color.currentLineHighlight]) self.drawList:AddRect(topLeft, bottomRight, self.palette[Color.currentLineHighlightBorder]) end end end end -- -- TextEditor::renderActiveBracketBackground -- function TextEditor:renderActiveBracketBackground() if self.config.showMatchingBrackets and #self.bracketeer.list > 0 then -- render active bracket pair local active = self.bracketeer:getEnclosingBrackets(self.cursors:getMain():getInteractiveEnd()) if active and active.visible then local glyphSize = self.glyphSize for _, pos in ipairs({ active.start, active["end"] }) do local row, column = self:docPos2VisPos(pos) if row >= self.firstVisibleRow and row <= self.lastVisibleRow then local x = self.cursorScreenPos.x + self.textLeftOffset + column * glyphSize.x local y = self.cursorScreenPos.y + row * glyphSize.y self.drawList:AddRectFilled(ImVec2(x, y), ImVec2(x + glyphSize.x, y + glyphSize.y), self.palette[Color.matchingBracketBackground]) end end end end end -- -- TextEditor::renderSelections -- function TextEditor:renderSelections() -- draw background for selections local glyphSize = self.glyphSize for _, cursor in ipairs(self.cursors.list) do if cursor:hasSelection() then local first = cursor:getSelectionStart() local last = cursor:getSelectionEnd() for i = math.max(first.line, self.firstVisibleRow), math.min(last.line, self.lastVisibleRow) do local lineLeft = newDocPos(i, 0) local lineRight = newDocPos(i, #self.document:at(i)) local docLeft = lineLeft if first > lineLeft then docLeft = first end local docRight = lineRight if last < lineRight then docRight = last end local _, visLeft = self:docPos2VisPos(docLeft) local _, visRight = self:docPos2VisPos(docRight) local x = self.cursorScreenPos.x + self.textLeftOffset local y = self.cursorScreenPos.y + i * glyphSize.y self.drawList:AddRectFilled( ImVec2(x + visLeft * glyphSize.x, y), ImVec2(x + visRight * glyphSize.x, y + glyphSize.y), self.palette[Color.selection]) end end end end -- -- TextEditor::renderTextMarkers -- function TextEditor:renderTextMarkers() if #self.markers > 0 then local glyphSize = self.glyphSize for row = self.firstVisibleRow, self.lastVisibleRow do local marker = self.document:at(row).marker if marker and bit32.rshift(marker.textColor, 24) ~= 0 then local y = self.cursorScreenPos.y + row * glyphSize.y local left = self.cursorScreenPos.x + self.textLeftOffset local right = left + self.lastVisibleColumn * glyphSize.x local s = ImVec2(left, y) local e = ImVec2(right, y + glyphSize.y) self.drawList:AddRectFilled(s, e, marker.textColor) if #marker.textTooltip > 0 and ImGui.IsMouseHoveringRect(s, e) then if ImGui.BeginTooltip() then ImGui.PushStyleColor(G.ImGuiCol.PopupBg, marker.textColor) ImGui.TextUnformatted(marker.textTooltip) ImGui.PopStyleColor() ImGui.EndTooltip() end end end end end end -- -- TextEditor::renderMatchingBracketLines -- @native function TextEditor:renderMatchingBracketLines() if self.config.showMatchingBrackets and #self.bracketeer.list > 0 then local active = self.bracketeer:getEnclosingBrackets(self.cursors:getMain():getInteractiveEnd()) local glyphSize = self.glyphSize -- render bracket pair lines for _, bracket in ipairs(self.bracketeer.list) do if bracket.visible and bracket["end"].line - bracket.start.line > 1 then local _, startColumn = self:docPos2VisPos(bracket.start) local _, endColumn = self:docPos2VisPos(bracket["end"]) local lineX = self.cursorScreenPos.x + self.textLeftOffset + math.min(startColumn, endColumn) * glyphSize.x local startY = self.cursorScreenPos.y + (bracket.start.line + 1) * glyphSize.y local endY = self.cursorScreenPos.y + bracket["end"].line * glyphSize.y local color = Color.whitespace if bracket == active then color = Color.matchingBracketActive end -- [Port] one line per bracket pair instead of one per document line self.drawList:AddLine(ImVec2(lineX, startY), ImVec2(lineX, endY), self.palette[color]) end end end end -- -- TextEditor::renderText -- @native function TextEditor:renderText() local glyphSize = self.glyphSize local tabSize = self.config.tabSize local fontSize = self.fontSize local palette = self.palette local drawList = self.drawList local font = self.font local whitespace = palette[Color.whitespace] local rowX = self.cursorScreenPos.x + self.textLeftOffset local rowY = self.cursorScreenPos.y + self.firstVisibleRow * glyphSize.y local firstRenderableColumn = math.floor(self.firstVisibleColumn / tabSize) * tabSize local lastVisibleColumn = self.lastVisibleColumn local charPos = ImVec2(0, 0) -- [Port] scratch glyph position (RenderChar only reads it) -- only process all visible rows for i = self.firstVisibleRow, self.lastVisibleRow do local line = self.document:at(i) local index = 1 local column = 0 -- only process all visible columns while index <= #line and column <= lastVisibleColumn do local glyph = line[index] local codepoint = glyph.codepoint local glyphX = rowX + column * glyphSize.x local width = glyphColumns(codepoint, column, tabSize) -- handle tabs if codepoint == 9 then if self.config.showTabs and column >= firstRenderableColumn then -- [Port] arrow spans the whole (expanded) tab local x1 = glyphX + glyphSize.x * 0.3 local y = rowY + fontSize * 0.5 local x2 = glyphX + glyphSize.x * width drawList:AddLine(ImVec2(x1, y), ImVec2(x2, y), whitespace) drawList:AddLine(ImVec2(x2, y), ImVec2(x2 - fontSize * 0.16, y - fontSize * 0.16), whitespace) drawList:AddLine(ImVec2(x2, y), ImVec2(x2 - fontSize * 0.16, y + fontSize * 0.16), whitespace) end -- handle spaces elseif codepoint == 32 then if self.config.showSpaces and column >= firstRenderableColumn then drawList:AddCircleFilled(ImVec2(glyphX + glyphSize.x * 0.5, rowY + fontSize * 0.5), 1.5, whitespace, 4) end -- handle regular glyphs elseif column >= firstRenderableColumn then charPos.x, charPos.y = glyphX, rowY font:RenderChar(drawList, fontSize, charPos, palette[glyph.color], codepoint) end column = column + width index = index + 1 end rowY = rowY + glyphSize.y end end -- -- TextEditor::renderCursorCarets -- function TextEditor:renderCursorCarets() if self.config.caretsVisible and ImGui.IsWindowFocused() then local io = ImGui.GetIO() self.cursorAnimationTimer = self.cursorAnimationTimer + io.DeltaTime local glyphSize = self.glyphSize for cursorIndex, cursor in ipairs(self.cursors.list) do local row, column = self:docPos2VisPos(cursor:getInteractiveEnd()) if row >= self.firstVisibleRow and row <= self.lastVisibleRow and column >= self.firstVisibleColumn and column <= self.lastVisibleColumn then local caretVisible = not io.ConfigInputTextCursorBlink or self.cursorAnimationTimer <= 0.0 or math.fmod(self.cursorAnimationTimer, 1.2) <= 0.8 local x = self.cursorScreenPos.x + self.textLeftOffset + column * glyphSize.x local y = self.cursorScreenPos.y + row * glyphSize.y -- handle custom caret renderer if self.customCaretCallback then self.customCaretCallback({ drawList = self.drawList, glyphPos = ImVec2(x, y), glyphSize = glyphSize, caretVisible = caretVisible, caretColor = self.palette[Color.cursor], cursorIndex = cursorIndex - 1, }) elseif caretVisible then self.drawList:AddRectFilled(ImVec2(x - self.cursorWidth, y), ImVec2(x, y + glyphSize.y), self.palette[Color.cursor]) end end end end end -- callback(caret) with caret = { drawList, glyphPos, glyphSize, caretVisible, caretColor, cursorIndex } function TextEditor:SetCustomCaretCallback(callback) self.customCaretCallback = callback end function TextEditor:ClearCustomCaretCallback() self.customCaretCallback = nil end -- -- TextEditor::renderLineNumberMarkers -- function TextEditor:renderLineNumberMarkers() if #self.markers > 0 then local glyphSize = self.glyphSize -- [Port] anchored to the window x position (like the line numbers) so markers don't scroll horizontally local windowX = ImGui.GetWindowPos().x for row = self.firstVisibleRow, self.lastVisibleRow do local marker = self.document:at(row).marker if marker and bit32.rshift(marker.lineNumberColor, 24) ~= 0 then local y = self.cursorScreenPos.y + row * glyphSize.y local s = ImVec2(windowX + self.lineNumberLeftOffset, y) local e = ImVec2(windowX + self.lineNumberRightOffset, y + glyphSize.y) self.drawList:AddRectFilled(s, e, marker.lineNumberColor) if #marker.lineNumberTooltip > 0 and ImGui.IsMouseHoveringRect(s, e) then if ImGui.BeginTooltip() then ImGui.PushStyleColor(G.ImGuiCol.PopupBg, marker.lineNumberColor) ImGui.TextUnformatted(marker.lineNumberTooltip) ImGui.PopStyleColor() ImGui.EndTooltip() end end end end end end -- -- TextEditor::renderLineNumbers -- function TextEditor:renderLineNumbers() if self.config.showLineNumbers then local glyphSize = self.glyphSize local curserLine = self.cursors:getCurrent():getInteractiveEnd().line local positionX = ImGui.GetWindowPos().x local positionY = self.cursorScreenPos.y if self.customLineNumberCallback then local width = self.lineNumberRightOffset - self.lineNumberLeftOffset for i = self.firstVisibleRow, self.lastVisibleRow do local color = Color.lineNumber if i == curserLine then color = Color.currentLineNumber end local pos = ImVec2(positionX + self.lineNumberLeftOffset, positionY + i * glyphSize.y) self.customLineNumberCallback({ drawList = self.drawList, pos = pos, size = ImVec2(width, glyphSize.y), digits = math.floor(width / glyphSize.x), lineNumber = i, cursorLineNumber = curserLine, color = self.palette[color], }) end else for i = self.firstVisibleRow, self.lastVisibleRow do local number = tostring(i + 1) local width = #number * glyphSize.x local color = Color.lineNumber if i == curserLine then color = Color.currentLineNumber end local pos = ImVec2(positionX + self.lineNumberRightOffset - width, positionY + i * glyphSize.y) self.drawList:AddText(nil, 0.0, pos, self.palette[color], number, 1, #number + 1) end end end end -- callback(data) with data = { drawList, pos, size, digits, lineNumber, cursorLineNumber, color } function TextEditor:SetCustomLineNumberCallback(callback) self.customLineNumberCallback = callback end function TextEditor:ClearCustomLineNumberCallback() self.customLineNumberCallback = nil end -- -- TextEditor::renderPopups -- -- [Port] TODO: TextHoverPopup and autocomplete popup function TextEditor:renderPopups() local popupData = { pos = self.popupDocPos } if ImGui.BeginPopup("LineNumberContextMenu") then if self.lineNumberContextMenuCallback then self.lineNumberContextMenuCallback(popupData) else ImGui.CloseCurrentPopup() end ImGui.EndPopup() end if ImGui.BeginPopup("TextContextMenu") then if self.textContextMenuCallback then self.textContextMenuCallback(popupData) else ImGui.CloseCurrentPopup() end ImGui.EndPopup() end end -- -- TextEditor::handleKeyboardInputs -- function TextEditor:handleKeyboardInputs() if not ImGui.IsWindowFocused() then return end local io = ImGui.GetIO() local macOS = io.ConfigMacOSXBehaviors local readOnly = self.config.readOnly local Shortcut = ImGui.Shortcut local wordMod = Mod_Ctrl local altMod = Mod_Alt if macOS then wordMod = Mod_Alt; altMod = Mod_Super end local pageSize = math.max(self.lastVisibleRow - self.firstVisibleRow - 2, 1) local cursors = self.cursors -- cursor movements and selections if Shortcut(Key.UpArrow, Repeat) then self:moveUp(1, false) elseif Shortcut(bor(Mod_Shift, Key.UpArrow), Repeat) then self:moveUp(1, true) elseif Shortcut(Key.DownArrow, Repeat) then self:moveDown(1, false) elseif Shortcut(bor(Mod_Shift, Key.DownArrow), Repeat) then self:moveDown(1, true) elseif Shortcut(bor(altMod, Mod_Shift, Key.LeftArrow)) then self:shrinkSelections() elseif Shortcut(bor(altMod, Mod_Shift, Key.RightArrow)) then self:growSelections() elseif Shortcut(Key.LeftArrow, Repeat) then self:moveLeft(false, false) elseif Shortcut(bor(Mod_Shift, Key.LeftArrow), Repeat) then self:moveLeft(true, false) elseif Shortcut(bor(wordMod, Key.LeftArrow), Repeat) then self:moveLeft(false, true) elseif Shortcut(bor(wordMod, Mod_Shift, Key.LeftArrow), Repeat) then self:moveLeft(true, true) elseif Shortcut(Key.RightArrow, Repeat) then self:moveRight(false, false) elseif Shortcut(bor(Mod_Shift, Key.RightArrow), Repeat) then self:moveRight(true, false) elseif Shortcut(bor(wordMod, Key.RightArrow), Repeat) then self:moveRight(false, true) elseif Shortcut(bor(wordMod, Mod_Shift, Key.RightArrow), Repeat) then self:moveRight(true, true) elseif Shortcut(Key.PageUp, Repeat) then self:moveUp(pageSize, false) elseif Shortcut(bor(Mod_Shift, Key.PageUp), Repeat) then self:moveUp(pageSize, true) elseif Shortcut(Key.PageDown, Repeat) then self:moveDown(pageSize, false) elseif Shortcut(bor(Mod_Shift, Key.PageDown), Repeat) then self:moveDown(pageSize, true) elseif Shortcut(bor(Mod_Ctrl, Key.UpArrow)) or Shortcut(bor(Mod_Ctrl, Key.Home)) then self:moveTo(self.document:getTop(), false) elseif Shortcut(bor(Mod_Ctrl, Mod_Shift, Key.UpArrow)) or Shortcut(bor(Mod_Ctrl, Mod_Shift, Key.Home)) then self:moveTo(self.document:getTop(), true) elseif Shortcut(bor(Mod_Ctrl, Key.DownArrow)) or Shortcut(bor(Mod_Ctrl, Key.End)) then self:moveTo(self.document:getBottom(), false) elseif Shortcut(bor(Mod_Ctrl, Mod_Shift, Key.DownArrow)) or Shortcut(bor(Mod_Ctrl, Mod_Shift, Key.End)) then self:moveTo(self.document:getBottom(), true) elseif Shortcut(Key.Home) then self:moveTo(self.document:getStartOfLine(cursors:getCurrent():getInteractiveEnd()), false) elseif Shortcut(bor(Mod_Shift, Key.Home)) then self:moveTo(self.document:getStartOfLine(cursors:getCurrent():getInteractiveEnd()), true) elseif Shortcut(Key.End) then self:moveTo(self.document:getEndOfLine(cursors:getCurrent():getInteractiveEnd()), false) elseif Shortcut(bor(Mod_Shift, Key.End)) then self:moveTo(self.document:getEndOfLine(cursors:getCurrent():getInteractiveEnd()), true) elseif Shortcut(bor(Mod_Ctrl, Key.A)) then self:selectAll() elseif cursors:currentCursorHasSelection() and Shortcut(bor(Mod_Ctrl, Key.D)) then self:addNextOccurrence(false) elseif cursors:currentCursorHasSelection() and Shortcut(bor(Mod_Ctrl, Mod_Alt, Key.D)) then self:addNextOccurrence(true) elseif cursors:currentCursorHasSelection() and Shortcut(bor(Mod_Ctrl, Mod_Alt, Key.L)) then self:addNextOccurrence(true) elseif cursors:currentCursorHasSelection() and Shortcut(bor(Mod_Ctrl, Mod_Shift, Key.D)) then self:selectAllOccurrences(false) elseif cursors:currentCursorHasSelection() and Shortcut(bor(Mod_Ctrl, Mod_Alt, Mod_Shift, Key.D)) then self:selectAllOccurrences(true) -- clipboard operations -- [Port] upstream allows cut in read-only mode (copy + no-op delete); guarded here elseif not readOnly and (Shortcut(bor(Mod_Ctrl, Key.X)) or Shortcut(bor(Mod_Ctrl, Key.Delete))) then self:cut() elseif Shortcut(bor(Mod_Ctrl, Key.C)) or Shortcut(bor(Mod_Ctrl, Key.Insert)) then self:copy() elseif not readOnly and (Shortcut(bor(Mod_Ctrl, Key.V), Repeat) or Shortcut(bor(Mod_Shift, Key.Insert), Repeat)) then self:paste() elseif not readOnly and Shortcut(bor(Mod_Ctrl, Key.Z), Repeat) then self:undo() elseif not readOnly and Shortcut(bor(Mod_Ctrl, Mod_Shift, Key.Z), Repeat) then self:redo() elseif not readOnly and Shortcut(bor(Mod_Ctrl, Key.Y), Repeat) then self:redo() -- remove text elseif not readOnly and Shortcut(Key.Delete, Repeat) then self:handleDelete(false) elseif not readOnly and Shortcut(bor(altMod, Key.Delete), Repeat) then self:handleDelete(true) elseif not readOnly and Shortcut(Key.Backspace, Repeat) then self:handleBackspace(false) elseif not readOnly and Shortcut(bor(altMod, Key.Backspace), Repeat) then self:handleBackspace(true) elseif not readOnly and Shortcut(bor(Mod_Ctrl, Mod_Shift, Key.K)) then self:removeSelectedLines() -- text manipulation elseif not readOnly and Shortcut(bor(Mod_Ctrl, Key.LeftBracket), Repeat) then self:deindentLines() elseif not readOnly and Shortcut(bor(Mod_Ctrl, Key.RightBracket), Repeat) then self:indentLines() elseif not readOnly and Shortcut(bor(Mod_Alt, Key.UpArrow)) then self:moveUpLines() elseif not readOnly and Shortcut(bor(Mod_Alt, Key.DownArrow)) then self:moveDownLines() elseif not readOnly and self.config.language and Shortcut(bor(Mod_Ctrl, Key.Slash)) then self:toggleComments() elseif not readOnly and self.config.language and Shortcut(bor(Mod_Ctrl, Key.L)) then self:toggleComments() -- find/replace support elseif self.config.findReplaceEnabled and Shortcut(bor(Mod_Ctrl, Key.F)) then self:openFindReplace() elseif self.config.findReplaceEnabled and Shortcut(bor(Mod_Ctrl, Mod_Shift, Key.F)) then self:findAll() elseif self.config.findReplaceEnabled and Shortcut(bor(Mod_Ctrl, Key.G), Repeat) then self:findNext() -- [Port] TODO: autocomplete trigger -- change insert mode elseif Shortcut(Key.Insert) then self.config.overwrite = not self.config.overwrite -- handle new line elseif not readOnly and (Shortcut(Key.Enter, Repeat) or Shortcut(Key.KeypadEnter, Repeat)) then self:handleCharacter(10) elseif not readOnly and (Shortcut(bor(Mod_Ctrl, Key.Enter), Repeat) or Shortcut(bor(Mod_Ctrl, Key.KeypadEnter), Repeat)) then self:insertLineBelow() elseif not readOnly and (Shortcut(bor(Mod_Shift, Key.Enter), Repeat) or Shortcut(bor(Mod_Shift, Key.KeypadEnter), Repeat)) then self:insertLineAbove() -- handle tabs elseif not readOnly and Shortcut(Key.Tab, Repeat) then if cursors:anyHasSelection() then self:indentLines() else self:handleCharacter(9) end elseif not readOnly and Shortcut(bor(Mod_Shift, Key.Tab), Repeat) then self:deindentLines() -- handle escape key elseif (self.findReplaceVisible or cursors:hasMultiple()) and Shortcut(Key.Escape) then if self.findReplaceVisible then self:closeFindReplace() else cursors:clearAdditional() end end -- handle regular text local queue = io.InputQueueCharacters if queue.Size > 0 then -- ignore Ctrl inputs, but need to allow Alt+Ctrl as some keyboards (e.g. German) use AltGR (which is Alt+Ctrl) to input certain characters if readOnly then elseif queue.Size > 1 then -- [Port] several chars in one frame = a paste delivered as characters (e.g. the Roblox text -- proxy): insert as one text block, without auto-pairing/auto-indent (else "(x)" became "(x))") local parts = table.create(queue.Size) for i = 1, queue.Size do local character = queue.Data[i] if character == 10 or character == 9 or character >= 32 then table.insert(parts, utf8.char(character)) end end local transaction = self:startTransaction() self:insertTextIntoAllCursors(transaction, table.concat(parts)) self:endTransaction(transaction) elseif not (ImGui.IsKeyDown(Mod_Ctrl) and not ImGui.IsKeyDown(Mod_Alt)) then for i = 1, queue.Size do local character = queue.Data[i] if character == 10 or character >= 32 then self:handleCharacter(character) end end end queue:resize(0) end -- notify OS of text input position for IME (and, in the port, the selected text for the Roblox text proxy) if not readOnly then local ime = ImGui.GetCurrentContext().PlatformImeData ime.WantVisible = true ime.WantTextInput = true -- at the main cursor: the top left of its line (as in Dear ImGui's InputText) local row, column = self:docPos2VisPos(self:getCursorPosition(cursors:getMainIndex())) ime.InputPos = ImVec2(self.cursorScreenPos.x + self.textLeftOffset + column * self.glyphSize.x - 1, self.cursorScreenPos.y + row * self.glyphSize.y) ime.InputLineHeight = self.glyphSize.y local viewport = ImGui.GetCurrentWindow().Viewport if viewport then ime.ViewportId = viewport.ID end ime.SelectedText = self:GetSelectedText() or "" end -- tell app to ignore keyboard inputs ImGui.SetNextFrameWantCaptureKeyboard(true) end -- -- TextEditor::handleMouseInteractions -- -- [Port] TODO: minimap scrollbar dragging, text hover popup, pan/scroll indicator function TextEditor:handleMouseInteractions() local io = ImGui.GetIO() local mouse = ImGui.GetMousePos() local windowPos = ImGui.GetWindowPos() local glyphSize = self.glyphSize local mouseX = mouse.x - self.cursorScreenPos.x local mouseY = mouse.y - self.cursorScreenPos.y local absoluteMouseX = mouse.x - windowPos.x local overLineNumbers = self.config.showLineNumbers and absoluteMouseX > self.lineNumberLeftOffset and absoluteMouseX < self.lineNumberRightOffset local overText = mouseX - ImGui.GetScrollX() > self.textLeftOffset and mouseX - ImGui.GetScrollX() < self.textRightOffset and mouseY - ImGui.GetScrollY() >= 0 and mouseY - ImGui.GetScrollY() < self.textSize.y local glyphPos, cursorPos = self:screenPos2DocPos((mouseX - self.textLeftOffset) / glyphSize.x, mouseY / glyphSize.y) local cursors = self.cursors local document = self.document local absoluteMouseY = mouse.y - windowPos.y self.panning = self.panning and self.config.panMode and ImGui.IsMouseDown(2) -- handle middle mouse button panning if self.panning and ImGui.IsMouseDragging(2) then local windowSize = ImGui.GetWindowSize() local mouseDelta = ImGui.GetMouseDragDelta(2) local deltaX, deltaY = mouseDelta.x, mouseDelta.y local dragFactor = io.DeltaTime * 15.0 local marginX, marginY = glyphSize.x * 4.0, glyphSize.y * 2.0 if absoluteMouseX < self.textLeftOffset + marginX then deltaX = (absoluteMouseX - (self.textLeftOffset + marginX)) * dragFactor elseif absoluteMouseX > windowSize.x - marginX then deltaX = (absoluteMouseX - (windowSize.x - marginX)) * dragFactor end if absoluteMouseY < marginY then deltaY = (absoluteMouseY - marginY) * dragFactor elseif absoluteMouseY > windowSize.y - marginY then deltaY = (absoluteMouseY - (windowSize.y - marginY)) * dragFactor end ImGui.SetScrollX(ImGui.GetScrollX() - deltaX) ImGui.SetScrollY(ImGui.GetScrollY() - deltaY) ImGui.ResetMouseDragDelta(2) -- handle middle mouse button scrolling elseif self.scrolling then local deadzone = glyphSize.x local offsetX = self.scrollStart.x - absoluteMouseX local offsetY = self.scrollStart.y - absoluteMouseY if offsetX < 0.0 then offsetX = math.min(offsetX + deadzone, 0.0) else offsetX = math.max(offsetX - deadzone, 0.0) end if offsetY < 0.0 then offsetY = math.min(offsetY + deadzone, 0.0) else offsetY = math.max(offsetY - deadzone, 0.0) end local scrollFactor = io.DeltaTime * 5.0 ImGui.SetScrollX(ImGui.GetScrollX() - offsetX * scrollFactor) ImGui.SetScrollY(ImGui.GetScrollY() - offsetY * scrollFactor) if ImGui.IsMouseClicked(0) or ImGui.IsMouseClicked(2) or ImGui.IsMouseClicked(1) then self.scrolling = false end -- handle left mouse button dragging elseif ImGui.IsMouseDragging(0) then -- update selection with dragging left mouse button if self.selectingText and overLineNumbers then local cursor = cursors:getCurrent() local s = newDocPos(cursorPos.line, 0) local e = self:normalizePos(newDocPos(cursorPos.line + 1, 0)) if cursor:getInteractiveEnd() < cursor:getInteractiveStart() then cursor:update(s) else cursor:update(e) end self:makeCursorVisible() elseif self.selectingText and overText then cursors:updateCurrentCursor(cursorPos) self:makeCursorVisible() end elseif ImGui.IsMouseReleased(0) then self.selectingText = false -- ignore other interactions when the editor is not hovered elseif ImGui.IsWindowHovered() then -- show text cursor if required if ImGui.IsWindowFocused() and overText then ImGui.SetMouseCursor(G.ImGuiMouseCursor.TextInput) end if ImGui.IsMouseClicked(2) then -- start panning/scrolling mode on middle mouse click if self.config.panMode then self.panning = true else self.scrolling = true self.scrollStart = ImVec2(absoluteMouseX, absoluteMouseY) end elseif ImGui.IsMouseClicked(1) then -- handle right clicks by setting up context menu (if required) if overLineNumbers and self.lineNumberContextMenuCallback then self.popupDocPos = glyphPos ImGui.OpenPopup("LineNumberContextMenu") elseif overText and self.textContextMenuCallback then self.popupDocPos = glyphPos ImGui.OpenPopup("TextContextMenu") end elseif ImGui.IsMouseClicked(0) then -- handle left mouse button actions self.selectingText = overText or overLineNumbers local doubleClick = ImGui.IsMouseDoubleClicked(0) local now = ImGui.GetTime() local tripleClick = not doubleClick and self.lastClickTime ~= -1 and (now - self.lastClickTime) < io.MouseDoubleClickTime if tripleClick then self.lastClickTime = -1 else self.lastClickTime = now end if tripleClick then -- left mouse button triple click if overText then local s = document:getStartOfLine(cursorPos) local e = self:normalizePos(newDocPos(s.line + 1, 0)) cursors:updateCurrentCursor(s, e) end elseif doubleClick then -- left mouse button double click if overText then local codepoint = document:getCodePoint(glyphPos) local handled = false -- select bracketed section (if required) if openers[codepoint] then local brackets = self.bracketeer:getEnclosingBrackets(document:getRight(glyphPos)) if brackets then if ImGui.IsKeyDown(Mod_Shift) then cursors:setCursor(brackets.start, document:getRight(brackets["end"])) else cursors:setCursor(document:getRight(brackets.start), brackets["end"]) end handled = true end elseif closers[codepoint] then local brackets = self.bracketeer:getEnclosingBrackets(glyphPos) if brackets then cursors:setCursor(brackets.start, document:getRight(brackets["end"])) handled = true end end -- select "word" if it wasn't a bracketed section -- run of whitespaces are considered "words" as are operator sequences if not handled and not document:isEndOfLine(glyphPos) then local word = document:getWholeWord(glyphPos) if word.start ~= word["end"] then cursors:updateCurrentCursor(word.start, word["end"]) end end end else -- left mouse button single click local extendCursor = ImGui.IsKeyDown(Mod_Shift) local addCursor if io.ConfigMacOSXBehaviors then addCursor = ImGui.IsKeyDown(Mod_Alt) else addCursor = ImGui.IsKeyDown(Mod_Ctrl) end if overLineNumbers then -- handle line number clicks local s = newDocPos(cursorPos.line, 0) local e = self:normalizePos(newDocPos(cursorPos.line + 1, 0)) if extendCursor then local cursor = cursors:getCurrent() if cursor:getInteractiveEnd() < cursor:getInteractiveStart() then cursor:update(s) else cursor:update(e) end elseif addCursor then cursors:addCursor(s, e) else cursors:setCursor(s, e) end self:makeCursorVisible() elseif overText then -- handle mouse clicks in text if extendCursor then cursors:growCurrentCursor(cursorPos) elseif addCursor then cursors:addCursor(cursorPos) else cursors:setCursor(cursorPos) end self:makeCursorVisible() end end end -- update cursors and reset vertical navigation if any button was pressed if ImGui.IsMouseDown(0) or ImGui.IsMouseDown(1) then cursors:update(document) self.navigatingVertically = false end end end -- -- scrolling -- function TextEditor:scrollToLine(line, alignment, fraction) self.ensureVisiblePos = nil self.scrollToLineNumber = math.min(line, self.document:size()) self.scrollToAlignment = alignment self.scrollToFraction = fraction or 0.0 end function TextEditor:handlePossibleScrolling() -- apply scrolling (if needed) local scrollX = -1.0 local scrollY = -1.0 local glyphSize = self.glyphSize local textSize = self.textSize -- do we need to make a certain position visible if self.ensureVisiblePos then if self.lastVisibleRow == 0 and self.lastVisibleColumn == 0 then -- this is a hack to handle a chicken and egg issue when the user called SetCursor before the first frame self.lastVisibleRow = math.min(math.ceil(textSize.y / glyphSize.y), self.document:size() - 1) self.lastVisibleColumn = math.ceil(textSize.x / glyphSize.x) end local row, column = self:docPos2VisPos(self:normalizePos(self.ensureVisiblePos)) if row <= self.firstVisibleRow + 1 then scrollY = math.max(0.0, (row - 2.0) * glyphSize.y) elseif row >= self.lastVisibleRow - 1 then scrollY = math.max(0.0, (row + 2.0) * glyphSize.y - textSize.y) end if column <= self.firstVisibleColumn + 1 then scrollX = math.max(0.0, (column - 2.0) * glyphSize.x) elseif column >= self.lastVisibleColumn - 1 then scrollX = math.max(0.0, (column + 2.0) * glyphSize.x - textSize.x) end self.ensureVisiblePos = nil end -- scroll to specified line (if required) if self.scrollToLineNumber then local row = self.scrollToLineNumber local visibleRows = textSize.y / glyphSize.y scrollX = 0.0 if self.scrollToAlignment == TextEditor.Scroll.alignTop then scrollY = (row + self.scrollToFraction) * glyphSize.y elseif self.scrollToAlignment == TextEditor.Scroll.alignMiddle then scrollY = math.max(0.0, (row - visibleRows / 2.0) * glyphSize.y) else scrollY = math.max(0.0, (row - (visibleRows - 1.0)) * glyphSize.y) end self.scrollToLineNumber = nil end -- set scroll (if required) if scrollX >= 0.0 then ImGui.SetScrollX(scrollX) end if scrollY >= 0.0 then ImGui.SetScrollY(scrollY) end end function TextEditor:makeCursorVisible() self.ensureVisiblePos = self.cursors:getCurrent():getInteractiveEnd() self.scrollToLineNumber = nil self:resetCursorAnimationTimer() end function TextEditor:resetScrolling() -- reset state related parameters self.ensureVisiblePos = nil self.scrollToLineNumber = nil self.firstVisibleRow = 0 self.lastVisibleRow = 0 self.firstVisibleColumn = 0 self.lastVisibleColumn = 0 self:resetCursorAnimationTimer() -- we can't reset the Dear ImGui scrolling here as we don't necessarily have the right context -- so we just set a flag and the render function will handle it self.resetDearImGuiScrolling = true end -- -- cursor movements -- function TextEditor:moveUp(rows, select) -- these must be done with visual coordinates for _, cursor in ipairs(self.cursors.list) do local row, column = self:docPos2VisPos(cursor:getInteractiveEnd()) if self.navigatingVertically then column = cursor.preferredColumn else cursor.preferredColumn = column end row = math.max(row - rows, 0) cursor:update(self:visPos2DocPos(row, column), select) end self:makeCursorVisible() self.navigatingVertically = true end function TextEditor:moveDown(rows, select) for _, cursor in ipairs(self.cursors.list) do local row, column = self:docPos2VisPos(cursor:getInteractiveEnd()) if self.navigatingVertically then column = cursor.preferredColumn else cursor.preferredColumn = column end cursor:update(self:visPos2DocPos(row + rows, column), select) end self:makeCursorVisible() self.navigatingVertically = true end function TextEditor:moveLeft(select, wordMode) for _, cursor in ipairs(self.cursors.list) do if cursor:hasSelection() and not select and not wordMode then cursor:resetToStart() else cursor:update(self.document:getLeft(cursor:getInteractiveEnd(), wordMode), select) end end self:makeCursorVisible() self.navigatingVertically = false end function TextEditor:moveRight(select, wordMode) for _, cursor in ipairs(self.cursors.list) do if cursor:hasSelection() and not select and not wordMode then cursor:resetToEnd() else cursor:update(self.document:getRight(cursor:getInteractiveEnd(), wordMode), select) end end self:makeCursorVisible() self.navigatingVertically = false end -- -- clipboard -- function TextEditor:cut() -- copy selections to clipboard and remove them self:copy() local transaction = self:startTransaction() self:deleteTextFromAllCursors(transaction) self.cursors:getCurrent():resetToStart() self:endTransaction(transaction) end function TextEditor:copy() -- copy all selections and put them on the clipboard -- empty cursors copy the entire line local parts = {} local document = self.document if self.cursors:anyHasSelection() then for _, cursor in ipairs(self.cursors.list) do if cursor:hasSelection() then parts[#parts + 1] = document:getSectionText(cursor:getSelectionStart(), cursor:getSelectionEnd()) else parts[#parts + 1] = document:getLineText(cursor:getSelectionStart().line) end end ImGui.SetClipboardText(table.concat(parts, "\n")) else for _, cursor in ipairs(self.cursors.list) do parts[#parts + 1] = document:getLineText(cursor:getSelectionStart().line) .. "\n" end ImGui.SetClipboardText(table.concat(parts)) end end function TextEditor:paste() -- ignore non-text clipboard content local clipboard = ImGui.GetClipboardText() if clipboard then local transaction = self:startTransaction() self:insertTextIntoAllCursors(transaction, clipboard) self:endTransaction(transaction) end end -- -- text editing -- function TextEditor:handleCharacter(character) local transaction = self:startTransaction() local cursors = self.cursors local document = self.document local config = self.config local opener = character local isPaired = not config.overwrite and config.completePairedGlyphs and isPairOpener(opener) local closer = toPairCloser(opener) -- ignore input if it was the closing character for a pair that was automatically inserted if self.completePairCloser ~= 0 then if self.completePairCloser == character and self.completePairLocation == cursors:getCurrent():getSelectionEnd() then self.completePairCloser = 0 self:moveRight(false, false) return end self.completePairCloser = 0 end if cursors:anyHasSelection() and isPaired then -- encapsulate the current selections with the requested pairs for c = 0, cursors:size() - 1 do local cursor = cursors:at(c) if cursor:hasSelection() then local s = cursor:getSelectionStart() local e = cursor:getSelectionEnd() -- insert the closing glyph local end1 = self:insertText(transaction, e, utf8.char(closer)) cursors:adjustForInsert(c, s, end1) -- insert the opening glyph local end2 = self:insertText(transaction, s, utf8.char(opener)) cursors:adjustForInsert(c, s, end2) -- update old selection cursor:update(document:getRight(s), document:getRight(e)) end end elseif isPaired then -- insert the requested pair local pair = utf8.char(opener) .. utf8.char(closer) for c = 0, cursors:size() - 1 do local cursor = cursors:at(c) local s = cursor:getSelectionStart() local e = self:insertText(transaction, s, pair) cursors:adjustForInsert(c, s, e) cursor:update(document:getRight(s), false) end -- remember the closer self.completePairCloser = closer self.completePairLocation = cursors:getCurrent():getSelectionEnd() elseif not config.overwrite and config.autoIndent and character == 10 then -- handle auto indent case self:autoIndentAllCursors(transaction) else -- handle overwrite by deleting next glyph before insert if config.overwrite then for c = 0, cursors:size() - 1 do local cursor = cursors:at(c) if not cursor:hasSelection() then local s = cursor:getSelectionStart() if s ~= document:getEndOfLine(s) then local e = document:getRight(s) self:deleteText(transaction, s, e) cursors:adjustForDelete(c, s, e) end end end end -- just insert a regular character self:insertTextIntoAllCursors(transaction, utf8.char(character)) end self:endTransaction(transaction) -- [Port] upstream relies on autocomplete/typesetter to scroll; make the caret visible after typing self:makeCursorVisible() -- [Port] TODO: autocomplete.startTyping end function TextEditor:autoIndentAllCursors(transaction) local cursors = self.cursors local document = self.document for c = 0, cursors:size() - 1 do local cursor = cursors:at(c) local s = cursor:getSelectionStart() -- delete any selections if cursor:hasSelection() then local e = cursor:getSelectionEnd() self:deleteText(transaction, s, e) cursors:adjustForDelete(c, s, e) end -- get previous and next character local index = s.index local line = document:at(s.line) local previousChar = 0 if index > 0 then previousChar = line[index].codepoint end local nextChar = 0 if index < #line then nextChar = line[index + 1].codepoint end -- remove extra whitespaces if required if CodePoint.isWhiteSpace(nextChar) then while index < #line and CodePoint.isWhiteSpace(line[index + 1].codepoint) do index = index + 1 end local e = newDocPos(s.line, index) self:deleteText(transaction, s, e) cursors:adjustForDelete(c, s, e) end -- determine whitespace at start of current line local whitespace = {} local i = 1 while i <= #line and CodePoint.isWhiteSpace(line[i].codepoint) do whitespace[#whitespace + 1] = utf8.char(line[i].codepoint) i = i + 1 end local ws = table.concat(whitespace) -- determine text to insert local insert = "\n" .. ws local newCursorIndex = #whitespace -- handle special cases if previousChar == 123 or previousChar == 91 then -- add to an existing block insert = insert .. "\t" newCursorIndex = newCursorIndex + 1 -- [Port] the tab may expand to spaces (insertSpacesOnTabs) if self.config.insertSpacesOnTabs then newCursorIndex = newCursorIndex - 1 + self.config.tabSize - #whitespace % self.config.tabSize end if (previousChar == 123 and nextChar == 125) or (previousChar == 91 and nextChar == 93) then -- open a new block insert = insert .. "\n" .. ws end end -- insert new text local e = self:insertText(transaction, s, insert) cursors:adjustForInsert(c, s, e) -- set new cursor location cursor:update(newDocPos(s.line + 1, newCursorIndex), false) end end function TextEditor:handleBackspace(wordMode) local transaction = self:startTransaction() local cursors = self.cursors -- remove selections or characters to the left of the cursor for c = 0, cursors:size() - 1 do local cursor = cursors:at(c) local s if cursor:hasSelection() then s = cursor:getSelectionStart() else s = self.document:getLeft(cursor:getSelectionStart(), wordMode) end local e = cursor:getSelectionEnd() self:deleteText(transaction, s, e) cursor:update(s, false) cursors:adjustForDelete(c, s, e) end self:endTransaction(transaction) self:makeCursorVisible() end function TextEditor:handleDelete(wordMode) local transaction = self:startTransaction() local cursors = self.cursors -- remove selections or characters to the right of the cursor for c = 0, cursors:size() - 1 do local cursor = cursors:at(c) local s = cursor:getSelectionStart() local e if cursor:hasSelection() then e = cursor:getSelectionEnd() else e = self.document:getRight(cursor:getSelectionEnd(), wordMode) end self:deleteText(transaction, s, e) cursor:update(s, false) cursors:adjustForDelete(c, s, e) end self:endTransaction(transaction) self:makeCursorVisible() end function TextEditor:removeSelectedLines() local transaction = self:startTransaction() local cursors = self.cursors for c = 0, cursors:size() - 1 do local cursor = cursors:at(c) local s = self.document:getStartOfLine(cursor:getSelectionStart()) local e = cursor:getSelectionEnd() if e.index ~= 0 then e = self.document:getNextLine(e) end self:deleteText(transaction, s, e) cursor:update(s, false) cursors:adjustForDelete(c, s, e) end self:endTransaction(transaction) end function TextEditor:insertLineAbove() local transaction = self:startTransaction() local cursors = self.cursors for c = 0, cursors:size() - 1 do local cursor = cursors:at(c) local s = self.document:getStartOfLine(cursor:getSelectionStart()) local e = self:insertText(transaction, s, "\n") cursor:update(s, false) cursors:adjustForInsert(c, s, e) end self:endTransaction(transaction) end function TextEditor:insertLineBelow() local transaction = self:startTransaction() local cursors = self.cursors for c = 0, cursors:size() - 1 do local cursor = cursors:at(c) local s = cursor:getSelectionEnd() if s.index ~= 0 then s = self.document:getNextLine(s) end local e = self:insertText(transaction, s, "\n") cursor:update(s, false) cursors:adjustForInsert(c, s, e) end self:endTransaction(transaction) end function TextEditor:indentLines() local transaction = self:startTransaction() local cursors = self.cursors -- process all cursors for c = 0, cursors:size() - 1 do local cursor = cursors:at(c) local cursorStart = cursor:getSelectionStart() local cursorEnd = cursor:getSelectionEnd() -- process all lines in this cursor for line = cursorStart.line, cursorEnd.line do if (not cursor:hasSelection() or newDocPos(line, 0) ~= cursorEnd) and #self.document:at(line) > 0 then local insertStart = newDocPos(line, 0) local insertEnd = self:insertText(transaction, insertStart, "\t") cursors:adjustForInsert(c, insertStart, insertEnd, true) end end end self:endTransaction(transaction) end function TextEditor:deindentLines() local transaction = self:startTransaction() local cursors = self.cursors -- process all cursors for c = 0, cursors:size() - 1 do local cursor = cursors:at(c) local cursorStart = cursor:getSelectionStart() local cursorEnd = cursor:getSelectionEnd() for line = cursorStart.line, cursorEnd.line do local glyphs = self.document:at(line) if (not cursor:hasSelection() or newDocPos(line, 0) ~= cursorEnd) and #glyphs > 0 then -- determine how many whitespaces are available at the start with a max of tabSize columns local column = 0 local index = 0 while column < self.config.tabSize and index < #glyphs and (glyphs[index + 1].codepoint == 32 or glyphs[index + 1].codepoint == 9) do column = column + glyphColumns(glyphs[index + 1].codepoint, column, self.config.tabSize) index = index + 1 end -- delete that whitespace (if required) local deleteStart = newDocPos(line, 0) local deleteEnd = newDocPos(line, index) if deleteEnd ~= deleteStart then self:deleteText(transaction, deleteStart, deleteEnd) cursors:adjustForDelete(c, deleteStart, deleteEnd, true) end end end end self:endTransaction(transaction) end -- -- occurrences -- -- [Port] Document::findText: returns start, end (or nil when not found); search wraps around the document function Document:findText(from, text, caseSensitive, wholeWord) local search = CodePoint.decode(text) if #search == 0 then return nil end if not caseSensitive then for j, ch in ipairs(search) do if ch < 128 then search[j] = string.byte(string.lower(string.char(ch))) end end end local function lower(ch) if not caseSensitive and ch < 128 then return string.byte(string.lower(string.char(ch))) end return ch end local searchLine = from.line local searchIndex = from.index repeat local line = searchLine local index = searchIndex local lineSize = #self:at(line) local done = false local j = 1 while not done and j <= #search do if search[j] == 10 then if index == lineSize and line ~= #self.lines - 1 then line = line + 1 index = 0 lineSize = #self:at(line) j = j + 1 else done = true end elseif index == lineSize then done = true elseif lower(self:at(line)[index + 1].codepoint) == search[j] then index = index + 1 j = j + 1 else done = true end end if j > #search then local s = newDocPos(searchLine, searchIndex) local e = newDocPos(line, index) if not wholeWord or self:isWholeWord(s, e) then return s, e end end if searchIndex == #self:at(searchLine) then if searchLine == #self.lines - 1 then searchLine = 0 else searchLine = searchLine + 1 end searchIndex = 0 else searchIndex = searchIndex + 1 end until searchLine == from.line and searchIndex == from.index return nil end function TextEditor:addNextOccurrence(wholeWord) local cursor = self.cursors:getCurrent() local text = self.document:getSectionText(cursor:getSelectionStart(), cursor:getSelectionEnd()) local s, e = self.document:findText(cursor:getSelectionEnd(), text, true, wholeWord) if s then self.cursors:addCursor(s, e) -- [Port] merge immediately so wrapping onto an existing cursor doesn't duplicate it self.cursors:update(self.document) self:makeCursorVisible() end end function TextEditor:selectAllOccurrencesOf(text, caseSensitive, wholeWord) local document = self.document local s, e = document:findText(newDocPos(0, 0), text, caseSensitive, wholeWord) if s then self.cursors:setCursor(s, e) while true do local nextStart, nextEnd = document:findText(self.cursors:getCurrent():getSelectionEnd(), text, caseSensitive, wholeWord) if nextStart == s and nextEnd == e then break end self.cursors:addCursor(nextStart, nextEnd) end else self.cursors:clearAdditional(true) end end function TextEditor:selectAllOccurrences(wholeWord) local cursor = self.cursors:getCurrent() local text = self.document:getSectionText(cursor:getSelectionStart(), cursor:getSelectionEnd()) self:selectAllOccurrencesOf(text, true, wholeWord) end function TextEditor:SelectNextOccurrenceOf(text, caseSensitive, wholeWord) local s, e = self.document:findText(self.cursors:getCurrent():getSelectionEnd(), text, caseSensitive ~= false, wholeWord) if s then self.cursors:setCursor(s, e) self:makeCursorVisible() else self.cursors:clearAdditional(true) end end function TextEditor:SelectAllOccurrencesOf(text, caseSensitive, wholeWord) self:selectAllOccurrencesOf(text, caseSensitive ~= false, wholeWord) end function TextEditor:AddNextOccurrence() self:addNextOccurrence(false) end function TextEditor:SelectAllOccurrences() self:selectAllOccurrences(false) end function TextEditor:SelectFirstOccurrenceOf(text, caseSensitive, wholeWord) self:selectFirstOccurrenceOf(text, caseSensitive ~= false, wholeWord) end function TextEditor:selectFirstOccurrenceOf(text, caseSensitive, wholeWord) local s, e = self.document:findText(newDocPos(0, 0), text, caseSensitive, wholeWord) if s then self.cursors:setCursor(s, e) self:makeCursorVisible() else self.cursors:clearAdditional(true) end end function TextEditor:selectNextOccurrenceOf(text, caseSensitive, wholeWord) self:SelectNextOccurrenceOf(text, caseSensitive, wholeWord) end -- -- grow/shrink selections -- local function isBracketOpener(ch) return ch == 123 or ch == 91 or ch == 40 end function TextEditor:growSelections() local document = self.document for _, cursor in ipairs(self.cursors.list) do if cursor:hasSelection() then local s = cursor:getSelectionStart() local e = cursor:getSelectionEnd() local startCodePoint = document:getCodePoint(document:getLeft(s)) local endCodePoint = document:getCodePoint(e) if isBracketOpener(startCodePoint) and endCodePoint == toPairCloser(startCodePoint) then cursor:update(document:getLeft(s), document:getRight(e)) else local bracket = self.bracketeer:getEnclosingBrackets(s, e) if bracket then cursor:update(document:getRight(bracket.start), bracket["end"]) end end else local pos = cursor:getSelectionEnd() cursor:update(document:findWordStart(pos), document:findWordEnd(pos)) end end end function TextEditor:shrinkSelections() local document = self.document for _, cursor in ipairs(self.cursors.list) do if cursor:hasSelection() then local s = cursor:getSelectionStart() local e = cursor:getSelectionEnd() local startCodePoint = document:getCodePoint(s) local endCodePoint = document:getCodePoint(document:getLeft(e)) if isBracketOpener(startCodePoint) and endCodePoint == toPairCloser(startCodePoint) then cursor:update(document:getRight(s), document:getLeft(e)) else local bracket = self.bracketeer:getInnerBrackets(s, e) if bracket then cursor:update(bracket.start, document:getRight(bracket["end"])) end end end end end -- -- move lines -- function TextEditor:moveUpLines() local cursors = self.cursors local document = self.document -- don't move up if first line is in one of the cursors if cursors:at(0):getSelectionStart().line ~= 0 then local transaction = self:startTransaction() for c = 0, cursors:size() - 1 do local cursor = cursors:at(c) local s = cursor:getSelectionStart() local e = cursor:getSelectionEnd() -- delete existing lines local deleteStart = document:getStartOfLine(s) local deleteEnd = e if e.index ~= 0 then deleteEnd = document:getNextLine(e) end local text = document:getSectionText(deleteStart, deleteEnd) self:deleteText(transaction, deleteStart, deleteEnd) cursors:adjustForDelete(c, deleteStart, deleteEnd) -- insert text one line up local insertStart = newDocPos(deleteStart.line - 1, 0) local insertEnd = self:insertText(transaction, insertStart, text) cursors:adjustForInsert(c, insertStart, insertEnd) -- update cursor cursor:update(newDocPos(s.line - 1, s.index), newDocPos(e.line - 1, e.index)) end self:endTransaction(transaction) end end function TextEditor:moveDownLines() local cursors = self.cursors local document = self.document -- don't move down if last line is in one of the cursors -- [Port] upstream tests the last cursor's selection start; a selection ending on the last line would be lost if not document:isLastLine(cursors:at(cursors:size() - 1):getSelectionEnd().line) then local transaction = self:startTransaction() for c = 0, cursors:size() - 1 do local cursor = cursors:at(c) local s = cursor:getSelectionStart() local e = cursor:getSelectionEnd() -- delete existing lines local deleteStart = document:getStartOfLine(s) local deleteEnd = e if e.index ~= 0 then deleteEnd = document:getNextLine(e) end local text = document:getSectionText(deleteStart, deleteEnd) self:deleteText(transaction, deleteStart, deleteEnd) cursors:adjustForDelete(c, deleteStart, deleteEnd) -- insert text one line down local insertStart = document:getNextLine(deleteStart) -- [Port] when the next line is the last one (no trailing newline), upstream glues the moved text onto it if insertStart.line == deleteStart.line and string.sub(text, -1) == "\n" then text = "\n" .. string.sub(text, 1, -2) end local insertEnd = self:insertText(transaction, insertStart, text) cursors:adjustForInsert(c, insertStart, insertEnd) -- update cursor cursor:update(newDocPos(s.line + 1, s.index), newDocPos(e.line + 1, e.index)) end self:endTransaction(transaction) end end -- -- toggle comments -- function TextEditor:toggleComments() local document = self.document local cursors = self.cursors local comment = CodePoint.decode(self.config.language.singleLineComment or "") if #comment == 0 then return end local transaction = self:startTransaction() -- process all cursors for c = 0, cursors:size() - 1 do local cursor = cursors:at(c) local cursorStart = cursor:getSelectionStart() local cursorEnd = cursor:getSelectionEnd() -- process all lines in this cursor for line = cursorStart.line, cursorEnd.line do local glyphs = document:at(line) if (not cursor:hasSelection() or newDocPos(line, 0) ~= cursorEnd) and #glyphs > 0 then -- see if line starts with a comment (after possible leading whitespaces) local start = 0 local i = 0 while start < #glyphs and CodePoint.isWhiteSpace(glyphs[start + 1].codepoint) do start = start + 1 end while start + i < #glyphs and i < #comment and glyphs[start + i + 1].codepoint == comment[i + 1] do i = i + 1 end if i == #comment then local deleteStart = newDocPos(line, start) local endOfComment = start + i if endOfComment < #glyphs - 1 and glyphs[endOfComment + 1].codepoint == 32 then endOfComment = endOfComment + 1 end local deleteEnd = newDocPos(line, endOfComment) self:deleteText(transaction, deleteStart, deleteEnd) cursors:adjustForDelete(c, deleteStart, deleteEnd, true) else local insertStart = newDocPos(line, start) local insertEnd = self:insertText(transaction, insertStart, self.config.language.singleLineComment .. " ") cursors:adjustForInsert(c, insertStart, insertEnd, true) end end end end self:endTransaction(transaction) end -- -- filters -- -- [Port] upstream re-runs the filter once per selected line; running it once per selection is equivalent function TextEditor:filterSelections(filter) local cursors = self.cursors local transaction = self:startTransaction() -- process all cursors for c = 0, cursors:size() - 1 do local cursor = cursors:at(c) if cursor:hasSelection() then local s = cursor:getSelectionStart() local e = cursor:getSelectionEnd() -- get original text and run it through filter local before = self.document:getSectionText(s, e) local after = filter(before) -- update selection if anything changed if after ~= before then self:deleteText(transaction, s, e) cursors:adjustForDelete(c, s, e) local newEnd = self:insertText(transaction, s, after) cursor:update(s, newEnd) cursors:adjustForInsert(c, s, newEnd) end end end self:endTransaction(transaction) end -- [Port] CodePoint::toLower/toUpper: string.lower/upper only touch ASCII bytes, so UTF-8 stays intact (non-ASCII unchanged) function TextEditor:selectionToLowerCase() self:filterSelections(string.lower) end function TextEditor:selectionToUpperCase() self:filterSelections(string.upper) end function TextEditor:stripTrailingWhitespaces() local document = self.document local transaction = self:startTransaction() -- process all the lines for i = 0, document:size() - 1 do local line = document:at(i) local lineSize = #line local whitespace = nil -- look for first non-whitespace glyph at the end of the line local index = lineSize while index > 0 and CodePoint.isWhiteSpace(line[index].codepoint) do index = index - 1 whitespace = index end -- remove whitespaces (if required) if whitespace then self:deleteText(transaction, newDocPos(i, whitespace), newDocPos(i, lineSize)) end end -- update cursor if transaction wasn't empty if self:endTransaction(transaction) then self.cursors:setCursor(self:normalizePos(self.cursors:getCurrent():getSelectionEnd())) end end function TextEditor:filterLines(filter) local document = self.document local transaction = self:startTransaction() -- process all the lines for i = 0, document:size() - 1 do -- get original text and run it through filter local before = document:getLineText(i) local after = filter(before) -- update line if anything changed if after ~= before then local s = newDocPos(i, 0) self:deleteText(transaction, s, document:getEndOfLine(s)) self:insertText(transaction, s, after) end end -- update cursor if transaction wasn't empty if self:endTransaction(transaction) then self.cursors:setCursor(self:normalizePos(self.cursors:getCurrent():getSelectionEnd())) end end function TextEditor:tabsToSpaces() local tabSize = self.config.tabSize self:filterLines(function(input) local output = {} local columns = 0 for _, codepoint in utf8.codes(input) do if codepoint == 9 then local spaces = tabSize - (columns % tabSize) output[#output + 1] = string.rep(" ", spaces) columns = columns + spaces else output[#output + 1] = utf8.char(codepoint) columns = columns + CodePoint.getGlyphWidth(codepoint) end end return table.concat(output) end) end function TextEditor:spacesToTabs() local tabSize = self.config.tabSize self:filterLines(function(input) local output = {} local columns = 0 local spaces = 0 for _, codepoint in utf8.codes(input) do if codepoint == 32 then spaces = spaces + 1 else while spaces > 0 do local spacesUntilNextTab = tabSize - (columns % tabSize) if spacesUntilNextTab == 1 then output[#output + 1] = " " columns = columns + 1 spaces = spaces - 1 elseif spaces >= spacesUntilNextTab then output[#output + 1] = "\t" columns = columns + spacesUntilNextTab spaces = spaces - spacesUntilNextTab elseif codepoint ~= 9 then output[#output + 1] = string.rep(" ", spaces) columns = columns + spaces spaces = 0 else spaces = 0 end end if codepoint == 9 then output[#output + 1] = "\t" columns = columns + tabSize - (columns % tabSize) else output[#output + 1] = utf8.char(codepoint) columns = columns + CodePoint.getGlyphWidth(codepoint) end end end -- [Port] upstream drops trailing spaces here; keep them (stripTrailingWhitespaces is the explicit command) output[#output + 1] = string.rep(" ", spaces) return table.concat(output) end) end -- public API function TextEditor:GrowSelections() self:growSelections() end function TextEditor:ShrinkSelections() self:shrinkSelections() end function TextEditor:MoveUpLines() if not self.config.readOnly then self:moveUpLines() end end function TextEditor:MoveDownLines() if not self.config.readOnly then self:moveDownLines() end end function TextEditor:ToggleComments() if not self.config.readOnly and self.config.language then self:toggleComments() end end function TextEditor:SelectionToLowerCase() if not self.config.readOnly then self:selectionToLowerCase() end end function TextEditor:SelectionToUpperCase() if not self.config.readOnly then self:selectionToUpperCase() end end function TextEditor:StripTrailingWhitespaces() if not self.config.readOnly then self:stripTrailingWhitespaces() end end -- filter(text: string) -> string, applied to each selection / each line (UTF-8) function TextEditor:FilterSelections(filter) if not self.config.readOnly then self:filterSelections(filter) end end function TextEditor:FilterLines(filter) if not self.config.readOnly then self:filterLines(filter) end end function TextEditor:TabsToSpaces() if not self.config.readOnly then self:tabsToSpaces() end end function TextEditor:SpacesToTabs() if not self.config.readOnly then self:spacesToTabs() end end function TextEditor:SetMiddleMousePanMode() self.config.panMode = true end function TextEditor:SetMiddleMouseScrollMode() self.config.panMode = false end function TextEditor:IsMiddleMousePanMode() return self.config.panMode end -- -- find/replace -- function TextEditor:SetFindReplaceEnabled(value) self.config.findReplaceEnabled = value if not value then self:closeFindReplace() end end function TextEditor:IsFindReplaceEnabled() return self.config.findReplaceEnabled end function TextEditor:OpenFindReplaceWindow() if self.config.findReplaceEnabled then self:openFindReplace() end end function TextEditor:CloseFindReplaceWindow() if self.config.findReplaceEnabled then self:closeFindReplace() end end function TextEditor:IsFindReplaceWindowVisible() return self.findReplaceVisible end function TextEditor:HasFindString() return #self.findText > 0 end -- [Port] programmatic access to the find/replace window state function TextEditor:SetFindString(text) self.findText = text end function TextEditor:GetFindString() return self.findText end function TextEditor:SetReplaceString(text) self.replaceText = text end function TextEditor:GetReplaceString() return self.replaceText end function TextEditor:SetFindCaseSensitive(value) self.caseSensitiveFind = value end function TextEditor:SetFindWholeWord(value) self.wholeWordFind = value end function TextEditor:Find() self:find() end function TextEditor:FindNext() self:findNext() end function TextEditor:FindAll() self:findAll() end function TextEditor:Replace() if not self.config.readOnly then self:replace() end end function TextEditor:ReplaceAll() if not self.config.readOnly then self:replaceAll() end end -- internationalize find window labels (strings must be UTF-8 encoded) function TextEditor:SetFindButtonLabel(label) self.findButtonLabel = label end function TextEditor:SetFindAllButtonLabel(label) self.findAllButtonLabel = label end function TextEditor:SetReplaceButtonLabel(label) self.replaceButtonLabel = label end function TextEditor:SetReplaceAllButtonLabel(label) self.replaceAllButtonLabel = label end local function latchButton(label, value, size) local colors = ImGui.GetStyle().Colors local Col = G.ImGuiCol if value then ImGui.PushStyleColor(Col.Button, colors[Col.ButtonActive]) ImGui.PushStyleColor(Col.ButtonHovered, colors[Col.ButtonActive]) ImGui.PushStyleColor(Col.ButtonActive, colors[Col.TableBorderLight]) else ImGui.PushStyleColor(Col.Button, colors[Col.TableBorderLight]) ImGui.PushStyleColor(Col.ButtonHovered, colors[Col.TableBorderLight]) ImGui.PushStyleColor(Col.ButtonActive, colors[Col.ButtonActive]) end ImGui.Button(label, size) local changed = ImGui.IsItemClicked(0) ImGui.PopStyleColor(3) return changed end -- [Port] inputString: InputText edits a fixed byte buffer (no CallbackResize); synced with the string field local inputBufferSize = 256 local function inputString(self, label, field, flags) local bufferField = field .. "Buffer" if self[bufferField] == nil or self[field .. "BufferText"] ~= self[field] then self[bufferField] = ImGui.NewTextBuffer(self[field], inputBufferSize) end local changed = ImGui.InputText(label, self[bufferField], inputBufferSize, bor(flags or 0, G.ImGuiInputTextFlags.NoUndoRedo)) if changed then self[field] = ImGui.TextBufferToString(self[bufferField]) end self[field .. "BufferText"] = self[field] return changed end function TextEditor:renderFindReplace() -- render find/replace window (if required) if not self.findReplaceVisible then return end -- save current screen position local currentScreenPosition = ImGui.GetCursorScreenPos() local readOnly = self.config.readOnly -- calculate sizes ImGui.PushStyleVar(G.ImGuiStyleVar.ItemSpacing, ImVec2(6.0, 4.0)) local style = ImGui.GetStyle() local spacingX, spacingY = style.ItemSpacing.x, style.ItemSpacing.y local fieldWidth = 250.0 * (style.FontScaleDpi or 1.0) local button1Width = ImGui.CalcTextSize(self.findButtonLabel).x + spacingX * 2.0 local button2Width = ImGui.CalcTextSize(self.findAllButtonLabel).x + spacingX * 2.0 local optionWidth = ImGui.CalcTextSize("Aa").x + spacingX * 2.0 local windowHeight = style.ChildBorderSize * 2.0 + style.WindowPadding.y * 2.0 + ImGui.GetFrameHeight() if not readOnly then button1Width = math.max(button1Width, ImGui.CalcTextSize(self.replaceButtonLabel).x + spacingX * 2.0) button2Width = math.max(button2Width, ImGui.CalcTextSize(self.replaceAllButtonLabel).x + spacingX * 2.0) windowHeight = windowHeight + spacingY + ImGui.GetFrameHeight() end local windowWidth = style.ChildBorderSize * 2.0 + style.WindowPadding.x * 2.0 + fieldWidth + spacingX + button1Width + spacingX + button2Width + spacingX + optionWidth * 3.0 + spacingX * 2.0 -- create window local availableSpace = ImGui.GetWindowWidth() if ImGui.GetCurrentWindow().ScrollbarY then availableSpace = availableSpace - style.ScrollbarSize end local windowPos = ImGui.GetWindowPos() ImGui.SetNextWindowPos(ImVec2(windowPos.x + availableSpace - windowWidth - spacingX, windowPos.y + spacingY * 2.0)) ImGui.SetNextWindowSize(ImVec2(windowWidth, windowHeight)) ImGui.SetNextWindowBgAlpha(0.75) ImGui.BeginChild("find-replace", ImVec2(windowWidth, windowHeight), G.ImGuiChildFlags.Borders) ImGui.SetNextItemWidth(fieldWidth) if self.focusOnFind then ImGui.SetKeyboardFocusHere() self.focusOnFind = false end if inputString(self, "###find", "findText", G.ImGuiInputTextFlags.AutoSelectAll) then if #self.findText > 0 then self:selectFirstOccurrenceOf(self.findText, self.caseSensitiveFind, self.wholeWordFind) else self.cursors:clearAll() end end if ImGui.IsItemDeactivated() then if ImGui.IsKeyPressed(Key.Escape) then self:closeFindReplace() elseif ImGui.IsKeyPressed(Key.Enter) or ImGui.IsKeyPressed(Key.KeypadEnter) then self.focusOnEditor = true self.focusOnFind = false end end local disableFindButtons = #self.findText == 0 if disableFindButtons then ImGui.BeginDisabled() end ImGui.SameLine() if ImGui.Button(self.findButtonLabel, ImVec2(button1Width, 0.0)) then self:find() end ImGui.SameLine() if ImGui.Button(self.findAllButtonLabel, ImVec2(button2Width, 0.0)) then self:findAll() end if disableFindButtons then ImGui.EndDisabled() end ImGui.SameLine() if latchButton("Aa", self.caseSensitiveFind, ImVec2(optionWidth, 0.0)) then self.caseSensitiveFind = not self.caseSensitiveFind self:find() end ImGui.SameLine() if latchButton("[]", self.wholeWordFind, ImVec2(optionWidth, 0.0)) then self.wholeWordFind = not self.wholeWordFind self:find() end ImGui.SameLine() if ImGui.Button("x", ImVec2(optionWidth, 0.0)) then self:closeFindReplace() end if not readOnly then ImGui.SetNextItemWidth(fieldWidth) inputString(self, "###replace", "replaceText") ImGui.SameLine() local disableReplaceButtons = #self.findText == 0 or #self.replaceText == 0 if disableReplaceButtons then ImGui.BeginDisabled() end if ImGui.Button(self.replaceButtonLabel, ImVec2(button1Width, 0.0)) then self:replace() end ImGui.SameLine() if ImGui.Button(self.replaceAllButtonLabel, ImVec2(button2Width, 0.0)) then self:replaceAll() end if disableReplaceButtons then ImGui.EndDisabled() end end if ImGui.IsWindowFocused() and not disableFindButtons and ImGui.IsKeyChordPressed(bor(Mod_Ctrl, Key.G)) then ImGui.SetWindowFocus(nil) self:find() end ImGui.EndChild() ImGui.PopStyleVar() ImGui.SetCursorScreenPos(currentScreenPosition) end function TextEditor:openFindReplace() -- get main cursor location local cursor = self.cursors:getMain() -- see if we have a current selection that's on one line if cursor:hasSelection() then if cursor:getSelectionStart().line == cursor:getSelectionEnd().line then -- use it as the default search self.findText = self.document:getSectionText(cursor:getSelectionStart(), cursor:getSelectionEnd()) end else -- if cursor is inside a "real" word, use that as the default local selection = self.document:getWholeWord(cursor:getSelectionStart(), true) if selection.start ~= selection["end"] then self.findText = self.document:getSectionText(selection.start, selection["end"]) end end self.findReplaceVisible = true self.focusOnFind = true end function TextEditor:closeFindReplace() if self.findReplaceVisible then self.findReplaceVisible = false self.focusOnEditor = true self.focusOnFind = false end end function TextEditor:find() if #self.findText > 0 then self:selectNextOccurrenceOf(self.findText, self.caseSensitiveFind, self.wholeWordFind) self.focusOnEditor = true self.focusOnFind = false end end function TextEditor:findNext() self:find() end function TextEditor:findAll() if #self.findText > 0 then self:selectAllOccurrencesOf(self.findText, self.caseSensitiveFind, self.wholeWordFind) self.focusOnEditor = true self.focusOnFind = false end end function TextEditor:replace() if #self.findText > 0 then if not self.cursors:anyHasSelection() then self:selectNextOccurrenceOf(self.findText, self.caseSensitiveFind, self.wholeWordFind) end self:replaceTextInCurrentCursor(self.replaceText) self:selectNextOccurrenceOf(self.findText, self.caseSensitiveFind, self.wholeWordFind) self.focusOnEditor = true self.focusOnFind = false end end function TextEditor:replaceAll() if #self.findText > 0 then self:selectAllOccurrencesOf(self.findText, self.caseSensitiveFind, self.wholeWordFind) self:replaceTextInAllCursors(self.replaceText) self.focusOnEditor = true self.focusOnFind = false end end end return TextEditor end