SyntaxHighlighter in Godot – Complete Guide

Welcome to our tutorial on the SyntaxHighlighter class in Godot 4 – a powerful yet understated feature that can elevate the coding experience within the Godot Integrated Development Environment (IDE). Learning how to implement syntax highlighting can not only make your code more readable but also accelerate your development process by allowing you to quickly identify code structures and keywords. Whether you’re just embarking on your coding voyage or looking to polish your already capable skills, understanding the SyntaxHighlighter class will contribute significantly to your Godot expertise.

What Is SyntaxHighlighter?

The SyntaxHighlighter class in Godot 4 serves as the foundational framework for creating custom syntax highlighters. A syntax highlighter is crucial for a TextEdit node, as it facilitates the differentiation of various elements in the code by color-coding them, enhancing readability and reducing errors. For Godot users, the SyntaxHighlighter offers a way to create nuanced text highlighting that caters to the specific syntax of custom languages or special use cases.

What Is SyntaxHighlighter Used For?

Primarily, SyntaxHighlighter is used in connecting with a TextEdit node to display syntax highlighting. This functionality is invaluable for developers who spend a great deal of time writing and reviewing code. Having a clear visual distinction between elements like variables, functions, keywords, and comments can significantly ease the understanding and debugging of the script.

Why Should I Learn SyntaxHighlighter?

Mastering the SyntaxHighlighter class in Godot 4 can have numerous benefits:
– **Customization:** Tailor the look of your script exactly to your liking, or to fit a particular coding style or language.
– **Efficiency:** Spot errors and navigate through complex codebases more swiftly.
– **Advanced Development:** As you delve deeper into Godot’s functionalities, understanding and using classes like SyntaxHighlighter can offer you finer control over the editor’s behavior, streamlining your workflow.
Learning how to use SyntaxHighlighter is not just about making your code look pretty—it’s about pushing the boundaries of what you can do within the Godot engine.

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Creating a Basic SyntaxHighlighter

Before diving into complex examples, let’s start with a basic SyntaxHighlighter setup in Godot 4. We need to subclass the SyntaxHighlighter class, and then we can override methods to define our syntax rules.

class_name CustomSyntaxHighlighter
extends SyntaxHighlighter

func _highlight_text(base: TextEdit):
    # Example of highlighting 'print' keyword
    var keyword_color = Color(1.0, 0.0, 0.0) # Red color
    base.add_keyword_color("print", keyword_color)

This snippet creates a custom syntax highlighter that would highlight the ‘print’ keyword in red.

Using Custom SyntaxHighlighter with TextEdit

After we’ve created our CustomSyntaxHighlighter class, we need to apply it to a TextEdit node. Here’s how you can set the custom syntax highlighter in Godot:

# Assuming we have a TextEdit node named 'code_editor'
var code_editor = $TextEdit
var syntax_highlighter = CustomSyntaxHighlighter.new()
code_editor.syntax_highlighter = syntax_highlighter

This script sets our CustomSyntaxHighlighter to a TextEdit node, so it will begin using the defined highlighting rules.

Adding Multiple Keywords

SyntaxHighlighter also allows us to highlight multiple keywords. Here’s how you can highlight a list of keywords:

func _highlight_text(base: TextEdit):
    var keywords = ["func", "var", "extends"]
    var keyword_color = Color(0.0, 0.0, 1.0) # Blue color
    
    for keyword in keywords:
        base.add_keyword_color(keyword, keyword_color)

This code will highlight ‘func’, ‘var’, and ‘extends’ in blue.

Highlighting Strings and Comments

Highlighting strings and comments is as essential as keywords. Below is an example of how to add rules for strings and comments:

func _highlight_text(base: TextEdit):
    # Setting the color for strings
    base.add_color_region('"', '"', Color(0.0, 1.0, 0.0), false)
    
    # Setting the color for comments
    base.add_color_region("#", "\n", Color(0.5, 0.5, 0.5), false)

This example makes all text between double quotes green (representing strings) and grays out any text following a hashtag until the end of the line (representing comments).

By breaking down these basic steps and applying various rules, you can start creating a productive environment within the Godot IDE that suits your project’s needs. Stay tuned, as we will soon expand our SyntaxHighlighter functionality with even more capabilities in the following parts.Let’s enhance our SyntaxHighlighter with a few more advanced features, like adding support for multi-line comments, customizing the color for specific data types, and setting up function recognition. Keep in mind that while these examples may not cover every potential use case, they will provide a solid foundation for you to build upon for your specific needs.

Highlighting Multi-line Comments

Multi-line comments are common in many programming languages. Here’s how you could implement highlighting for such comments in Godot:

func _highlight_text(base: TextEdit):
    # Multi-line comment in GDScript is enclosed with ''' symbols
    base.add_color_region("'''", "'''", Color(0.5, 0.5, 0.5), true)

This code snippet will ensure that any text between triple quotes is treated as a comment and highlighted in grey, even if the comment spans multiple lines.

Custom Colors for Data Types

Assigning distinct colors to data types can quickly convey what kind of data is being manipulated. Let’s set some custom colors for common GDScript data types:

func _highlight_text(base: TextEdit):
    var data_types = ["int", "float", "String", "Array", "Dictionary", "bool"]
    var data_type_color = Color(0.8, 0.3, 0.8) # Purple color
    
    for data_type in data_types:
        base.add_keyword_color(data_type, data_type_color)

This will highlight data types like ‘int’, ‘float’, ‘String’, etc., in purple, making them instantly recognizable.

Function and Variable Recognition

Being able to distinguish functions and variables at a glance can be quite helpful. Below are code examples to define various highlighter rules for this purpose:

For functions:

func _highlight_text(base: TextEdit):
    var func_color = Color(0.2, 0.6, 0.8) # Cyan color
    
    # Regular expression pattern to match function declarations
    var pattern = "func\\s+([a-zA-Z_]\\w*)"
    base.add_regex_color(pattern, func_color)

For variables:

func _highlight_text(base: TextEdit):
    var variable_color = Color(0.9, 0.9, 0.2) # Yellow color
    
    # Regular expression pattern to match variable declarations
    var pattern = "var\\s+([a-zA-Z_]\\w*)"
    base.add_regex_color(pattern, variable_color)

These snippets use regular expressions to define a pattern that matches function and variable declarations, highlighting them in cyan and yellow, respectively.

Syntax Highlighter Optimization

Finally, when working on larger code bases with a custom syntax highlighter, performance can become an issue. Here’s how you can accommodate that:

func _update_highlighting(base: TextEdit):
    # Disconnect the signal to prevent running while updating
    base.disconnect("text_changed", self, "_update_highlighting")

    # Run the highlighting logic
    _highlight_text(base)
    
    # Reconnect the signal after updates
    base.connect("text_changed", self, "_update_highlighting")

By disconnecting the ‘text_changed’ signal before updating the highlighting and reconnecting it afterward, we prevent the syntax highlighter from running multiple times unnecessarily, which could slow down the editor for large scripts.

Remember, the power of a custom SyntaxHighlighter is in the details. Tailor your syntax highlighting to fit the unique nature of your project, and you’ll see a significant improvement in your development experience. With the skills you’ve honed in this tutorial, the coding aspect of your Godot projects will be more intuitive and visually organized than ever before.In this section, we will explore additional code examples to further refine the capabilities of your SyntaxHighlighter in Godot 4. We will look at distinguishing function calls from declarations, highlighting custom classes, handling edge cases, and improving readability for numbers in code.

Function Calls vs. Declarations

Differentiating between when a function is called and when it is declared can be quite useful. For function declarations, we often use a regular expression to find the pattern. However, for calls, it’s a bit different. You might want to use a simpler heuristic if your language allows it, like looking for the function name followed by an open parenthesis.

func _highlight_text(base: TextEdit):
    # Highlight function calls in green
    var func_call_color = Color(0.4, 0.8, 0.4)
    var func_declaration_color = Color(0.2, 0.6, 0.8)

    # Assume functions end with '()' and are not preceded by 'func '
    var functions = base.get_text().split(" ")
    for word in functions:
        if word.ends_with("()") and not word.begins_with("func "):
            var func_name = word.replace("()", "").strip()
            base.add_keyword_color(func_name, func_call_color)

    # Highlight function declarations in cyan
    var pattern = "func\\s+([a-zA-Z_]\\w*)"
    base.add_regex_color(pattern, func_declaration_color)

Highlighting Custom Classes

If you’re creating your classes in Godot, it’s practical to highlight their names to recognize them instantly. Here’s a simple method for doing so:

func _highlight_text(base: TextEdit):
    # Custom class color
    var class_color = Color(1.0, 0.5, 0.0)
    
    # Assuming custom classes start with 'C_' prefix
    var pattern = "(C_\\w+)"
    base.add_regex_color(pattern, class_color)

This regular expression matches any word that starts with “C_” and applies a custom color to it, indicating a custom class name.

Handling Edge Cases

Syntax highlighting can sometimes yield false positives. For example, certain keywords may not be keywords in all contexts. Here’s an example of excluding false positives through more specific regular expressions:

func _highlight_text(base: TextEdit):
    var keyword_color = Color(0.0, 0.0, 1.0)
    
    # Exclude 'if' from being highlighted within strings
    var pattern = "(?<!\")\\bif\\b(?!\")"
    base.add_regex_color(pattern, keyword_color)

In the above example, we want to highlight the keyword ‘if’, but avoid highlighting it when it appears inside a string. The regular expressions used here ensure that ‘if’ is not preceded or followed by a double-quote.

Improving Readability for Numbers

To enhance the readability of numbers in your code, consider giving them a unique color. This approach helps them stand out from the rest of the text, making them easier to identify.

func _highlight_text(base: TextEdit):
    # Color for numbers
    var number_color = Color(1.0, 0.6, 0.2)

    # This pattern matches integers and floating-point numbers
    var pattern = "\\b\\d+\\.?\\d*\\b"
    base.add_regex_color(pattern, number_color)

The regular expression `\\b\\d+\\.?\\d*\\b` matches whole numbers and floats, allowing us to highlight them distinctively in the code.

Remember that the strength of your SyntaxHighlighter lies in its flexibility to adapt to various coding situations. With these examples as your guide, continue to craft a highlighter that best suits the unique characteristics of your project’s code and the Godot 4 IDE.

Continuing Your Godot Journey

Now that you’ve got a taste of the power of syntax highlighting in Godot 4 and have begun to tailor your development environment, you’re well on your way to becoming a proficient Godot developer. This is just the tip of the iceberg, and there’s so much more to explore within Godot’s extensive capabilities. To keep leveling up your skills, we invite you to delve into the Godot Game Development Mini-Degree offered by Zenva Academy.

Our Mini-Degree covers a breadth of essential topics to give you effective, hands-on experience with not only GDScript but also the nuts and bolts of game design and development with Godot 4. You’ll learn to build cross-platform games from scratch, understand the ins and outs of both 2D and 3D gameplay, and shape your prowess in creating engaging user experiences through various game genres. This curriculum has something for everyone, from beginners to those looking to build on existing expertise.

If you’re eager to explore more about what Godot has to offer, check out our full range of Godot courses. Each course is designed to help expand your knowledge base, polish your skill set, and work towards building a compelling portfolio to showcase your development acumen. Take the next step in your coding journey with Zenva, where you can transition from beginner to professional at your pace, and on your schedule.

Conclusion

The art of coding is in the details, and with the SyntaxHighlighter class in Godot 4, those details come to life in vivid color. By now, you should have the skills to not only apply syntax highlighting to your projects but also understand the transformative effect it can have on your coding practice. Whether you’re debugging complex scripts or writing new functions, having a tailored, color-coded view makes all the difference.

Don’t stop here – your journey as a developer is boundless, and continuing to learn is key to unlocking your full potential. We at Zenva are committed to supporting you every step of the way with our comprehensive Godot Game Development Mini-Degree. Dive deeper into the world of Godot with us, and craft the games you’ve always dreamed of making. Happy coding!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.