If you’re tired of manually reordering your GDScript code to match the official style guide, I’ve got something for you.
Why code order matters?
A code with standard order is more easier to read, specially when you read it from top to bottom. Also, it helps developers reading the code for the first time to understand how it works.
Manual way
You can reorder your code manually with this guide, but
- It takes a lot of time for each script
- You have to go back to the help page many times
- You might forget something
And you have to repeat it over and over, there’s even a joke about it here (I had pinned this help page in my browser before this guide😅)
Automatic way
So let’s start real solution. For this you need a simple setup:
- Text Forge v0.1+ (it’s available for download for Windows and Linux here) ~30MB
- Text Forge GDScript Mode v1.1+ (direct link to mode file) ~5KB
First step is installing mode, for this run Text Forge (you can find full setup guide here) and go to Settings > Mode Manager…, then click on Import Mode / Mode Kit and select .tfmode file you was downloaded. Now, close Mode Manager window and just open your .gd file (you can use Ctrl + O as shortcut) and press Ctrl + Shift + F or use Format > Auto Format option, editor will use GDScript mode to:
- Move each block
extedns,class,func,static func,var,@onready var, etc to correct place - Cleanup whitespaces
- Sort each block type in public-private and alphabetical order
- Move comments to correct place
Now you can save your script to apply changes.
Some details
How does it work?
Breaks the code into blocks, categorizes the blocks, sorts each category, and arranges the categories sequentially to form the complete code.
Is it possible for the code’s functionality to change?
Generally, no, because it doesn’t change the logic or remove any blocks.
Limitations:
- Does not support regions; it moves them all to the top of the code for you to remove yourself.
- Does not support nested sorting to prevent changes in code behavior.
- Treats standalone comments (not attached to any code) as notes and moves them to the top of the code.
- Does not sort export variables precisely.
Directly in Godot?
Unfortunately, I don’t have a plugin to do this directly in Godot, but since Text Forge and all its modes (including the GDScript mode which has this capability) are written in GDScript, it’s not too difficult to implement. This mode is available under the MIT license in this GitHub repository:
If you develop a plugin with the Auto Format section of this code, please comment it here so that others can use it as well.
Thanks,
– Mahan