Skip to content

Instantly share code, notes, and snippets.

@samyeyo
Created June 30, 2022 18:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samyeyo/460d38d0d2ccb4c8709e71a60d7d35f7 to your computer and use it in GitHub Desktop.
Save samyeyo/460d38d0d2ccb4c8709e71a60d7d35f7 to your computer and use it in GitHub Desktop.
LuaRT syntax highlighting example with Edit widget
--
-- luaRT syntax.lua example
-- A syntax higlighting Edit widget
-- Author: Samir Tine
--
local ui = require "ui"
local SyntaxEdit = Object(ui.Edit)
function SyntaxEdit:constructor(...)
local keyword_color = 0xCC2020
local keywords = { ["and"] = true, ["break"] = true, ["do"] = true, ["else"] = true, ["elseif"] = true,
["end"] = true, ["for"] = true, ["function"] = true, ["goto"] = true, ["if"] = true, ["in"] = true,
["local"] = true, ["not"] = true, ["or"] = true, ["repeat"] = true, ["return"] = true, ["then"] = true, ["until"] = true, ["while"] = true }
-- keywords property => Get/set a table with keywords
function self:get_keywords()
return keywords
end
function self:set_keywords(keywords_table)
keywords = keywords_table
end
-- kwcolor property => Get/set the keywords color
function self:get_kwcolor()
return keyword_color
end
function self:set_kwcolor(c)
keyword_color = c
end
ui.Edit.constructor(self, ...)
end
-- onChange event : parse and recolorize the keywords in the text
function SyntaxEdit:onChange()
local from = self.selection.from
local to = self.selection.to
self.selection.from = 1
self.selection.to = 0
self.selection.color = 0x000000
local start = 1
local text = self.text:gsub("\r\n", "\n")
while start < string.len(text) do
local s, e = text:find("%w+", start)
if s ~= nil then
local word = text:sub(s, e)
start = e+1
if self.keywords[word] ~= nil then
self.selection.from = s
self.selection.to = start
self.selection.color = 0xCC2020
end
else
break;
end
end
self.selection.from = from
self.selection.to = to
end
-- create a simple window
local win = ui.Window("Syntax highlighting sample", "fixed", 520, 460)
local edit = SyntaxEdit(win, "", 10, 10, 500, 440)
-- set edit.properties
edit.autovscroll = false
edit.font = "Lucida Console"
edit.fontsize = 9
edit.wordwrap = true
win:show()
-- update user interface
repeat
ui.update()
until not win.visible
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment