Here's how I would handle this:
extends Node
const FILE_PATH := "res://MyTextFile.txt" # replace
const SYMBOL := {
START = "code: `",
END = "`"
}
const CODE_BLOCK := {
BEFORE = "BEFORE",
INSIDE = "INSIDE",
AFTER = "AFTER"
}
var Text := {
CODE_BLOCK.BEFORE: "",
CODE_BLOCK.INSIDE: "",
CODE_BLOCK.AFTER: "",
}
func get_TextEdit_text() -> String: # Replace with actual getter
return "<Your TextEdit code here>"
func append_line(where: String, line: String) -> void:
assert(Text.has(where))
Text[where] = str(Text[where], line, "\n")
func replace_code_block_text_in_file():
var file := File.new()
assert(file.file_exists(FILE_PATH), str("Invalid filepath: ", FILE_PATH))
file.open(FILE_PATH, file.READ_WRITE)
var file_text := file.get_as_text()
file.close()
var file_text_lines: Array = file_text.split("\n")
var where: String = CODE_BLOCK.BEFORE
for i in file_text_lines.size():
var line: String = file_text_lines[i]
match where:
CODE_BLOCK.BEFORE:
append_line(where, line)
if line.begins_with(SYMBOL.START):
where = CODE_BLOCK.INSIDE
CODE_BLOCK.INSIDE:
if line.begins_with(SYMBOL.END):
where = CODE_BLOCK.AFTER
append_line(where, line)
CODE_BLOCK.AFTER:
pass
_:
assert(false)
var old_file_text := str(Text.BEFORE, Text.INSIDE, Text.AFTER)
var new_file_text := str(Text.BEFORE, get_TextEdit_text(), "\n", Text.AFTER)
while new_file_text.begins_with("\n"): # Deleting newlines at beginning
new_file_text = new_file_text.trim_prefix("\n")
while new_file_text.ends_with("\n"): # Deleting newlines at end
new_file_text = new_file_text.trim_suffix("\n")
# Replacing file
var dir := Directory.new()
assert(dir.file_exists(FILE_PATH))
dir.remove(FILE_PATH)
file = File.new()
file.open(FILE_PATH, file.WRITE)
file.store_string(new_file_text)
file.close()
print("--- OLD FILE TEXT ---")
print(old_file_text)
print("--- NEW FILE TEXT ---")
print(new_file_text)
func _ready():
replace_code_block_text_in_file()
Prints:
--- OLD FILE TEXT ---
module.exports = ({
name: "NAME",
code: `
Old Code Line 1
Old Code Line 2
Old Code Line 3
`})
--- NEW FILE TEXT ---
module.exports = ({
name: "NAME",
code: `
<Your TextEdit code here>
`})