How would I go about making syntax highlighting?

So I’m making a custom console to run commands and stuff in and I wanna make syntax highlighting because its cool :sunglasses: but I haven’t had any experience in doing that kind of stuff, and I don’t know how to work with richtext in scripts either. so can someone please help me? thanks in advance!
– food
also heres a idea of what i want to make, i also dont know how to add a “>” at the end of each line so if you could help me with that too then i would be really happy!


heres the code i have right now:

--// variables \\--

local console = script.Parent.console
local cmdbar = console.cmdbar
local output = console.output
local hotkey = Enum.KeyCode.P
local UIS = game:GetService("UserInputService")
local word = string.split(cmdbar.Text, ' ')


--// syntax & colors \\--

local syntax = {
	
}

--idk how to do the colors but i do know that you use richtext

This is a REALLY weird hacky way to do text highlighting but here it is:

local keywords = {
    foo = "255,0,0";
    bar = "0,255,0";
    --keyword = rgb color;
}

function insertHighlights(txt) --txt is the text you want to highlight
    txt = " " .. txt .. " " --add some padding because my string pattern smells
    for i,v in next, keywords do --loop through keywords
        txt = txt:gsub("%A"..i.."%A",function(x) --replace keyword with result of function
            return x:gsub(i,function(y) --remove %A and %A used to see if its a freestanding word (ig. foob wouldnt highlight)
                return "<font color=\"rgb("..v..")\">"..y.."</font>" --richtext junk
            end)
        end)
    end
    return txt:sub(2,#txt-1) --remove padding added line #1 of function
end

print(insertHighlights("a foo eats a bar"))

a <font color="rgb(255,0,0)">foo</font> eats a <font color="rgb(0,255,0)">bar</font>

image

6 Likes

Sorry if this is a bit much, but could you tell me how to put them under categories? like a specified color, and then all words that are variables or something else would be in a group that use that color? Sorry if i didnt make sense there.

You can make syntax collection such categories with the colors.
Here is an Example.

local Syntax = {
	["Red"] = {
		Highlight = "255,0,0",
		KeyWords = {
			"function",
			"print",
			"foo"
		}
	},
	["Green"] = {
		Highlight = "0,255,0",
		KeyWords = {
			"mod",
			"bar",
			"test"
		}
	}
}

Highlight References to the Highlighting color
Keywords reference to the Words that will be highlighted under within that category.

Hopefully this helped you. :+1:

3 Likes

Sorry to bump in but you can fork this: Best Syntax Highlighter - Roblox

1 Like