Possible to add custom highlight syntax for file types?

Godot Version

4.2.1.stable

Question

I was wondering if it’s possible to add custom syntax to specific file types?
I’m writing a “dialogue script” parser for my dialogue system and I currently read from .txt files, but was wondering if I could easily add highlightable syntax specifically for the txt file type, or somehow add it if I have a custom file type (.dialogue as eg.)? Having the highlightable syntax for my dialogue would make it so much easier to read, eg. easier to see any misspellings.

Yes, you can create a plugin and register a new syntax highlighter with ScriptEditor.register_syntax_highlighter()

Example:

@tool
extends EditorPlugin


var dialogue_highlighter:DialogueHighlighter


func _enter_tree() -> void:
	dialogue_highlighter = DialogueHighlighter.new()
	var script_editor = EditorInterface.get_script_editor()
	script_editor.register_syntax_highlighter(dialogue_highlighter)


func _exit_tree() -> void:
	if is_instance_valid(dialogue_highlighter):
		var script_editor = EditorInterface.get_script_editor()
		script_editor.unregister_syntax_highlighter(dialogue_highlighter)
		dialogue_highlighter = null


class DialogueHighlighter extends EditorSyntaxHighlighter:


	func _get_name() -> String:
		return "Dialogue"


	func _get_supported_languages() -> PackedStringArray:
		return ["TextFile"]


	func _get_line_syntax_highlighting(line: int) -> Dictionary:
		var color_map = {}
		var text_editor = get_text_edit()
		var str = text_editor.get_line(line)

		if str.strip_edges().begins_with("#"):
			color_map[0] = { "color": Color.RED }

		var name_dialog_separator = str.find("::")

		if name_dialog_separator > -1:
			color_map[0] = { "color": Color.BLUE }
			color_map[name_dialog_separator] = { "color": Color.GREEN }
			color_map[name_dialog_separator + 2] = { "color": Color.WHITE }

		return color_map

Result:

image

More info on how to make plugins Making plugins — Godot Engine (stable) documentation in English

2 Likes

Would there be a way to access autoload variables with this script? I’m having issues with that, eg.
image

No, scripts running in the editor can’t access Autoloads.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.