Godot Version
4.4-rc1
Question
I’m trying to write an editor plugin that adds some generated code to existing scripts in the project. If the script being updated is open in the editor, I’d like to reload the text in the editor to reflect the changes.
I found this snippet from GitHub which has a solution if I already have a reference to a TextEdit
, but in my case I only know about the Script
. Basically, what I want is something like this, but I don’t know how to implement get_editor_for_script
:
@tool
extends EditorPlugin
# _enter_tree(), _exit_tree(), etc...
# ...
func update_script(script: Script) -> void:
var some_generated_code := "..."
script.source_code += generated_code
ResourceSaver.save(script, script.resource_path)
var editor := get_editor_for_script(script)
if editor != null:
reload_script(editor, script.source_code)
func get_editor_for_script(script: Script) -> CodeEdit:
# ^^^^^ How do I implement this method?
static func reload_script(text_edit: TextEdit, source_code: String) -> void:
# Copy the solution from
# https://github.com/godotengine/godot/pull/83267#issue-1941991896
TextEdit
and CodeEdit
don’t seem to have references to a resource path, so it’s not clear how to search based on the Script
. I tried something like the following, but it doesn’t work unless only script are open in the editor (for example, it breaks if a .txt
file is open):
func get_editor_for_script(script: Script) -> CodeEdit:
var script_editor := get_editor_interface().get_script_editor()
var open_scripts := script_editor.get_open_scripts()
for i in range(open_scripts.size()):
var open_script := open_scripts[i]
if open_script.resource_path == script.resource_path:
var script_editors := script_editor.get_open_script_editors()
# [BUG!] We incorrectly assume that script i is open in editor i
return script_editors[i].get_base_editor()
Is it possible to correctly implement get_editor_for_script
?
Thanks in advance!