My code to replace text in a file between 2 points doesn't work correctly

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By zen

The file is:

module.exports = ({
name: "NAME",
code: `
Code here
`})

When I execute the function, it should take the text i have on a textedit, and replace the code between ‘code: ' and '})’. So in this case it is Code here.
However, if I execute the function with the text:
These are some lines
it will work as intended and replace the “Code here” with the text. But then if i try to replace THAT text with something else, it just clips off the beginning. This is the code that handles that:

var cmdToSave = ReverseText($Commands/Borders/EditCommand/EditSpace.text)
var file = File.new()
file.open(dir.get_current_dir().plus_file(fileName), File.READ)
var start = "code: `"
var end = "\n`})"
var fileContent = file.get_as_text()
var previousContent = fileContent
var prev1 = fileContent.find(start, 0)+len(start)
var prev2 = fileContent.find(end, 0)
fileContent = previousContent.replace(previousContent, cmdToSave)
var temp = previousContent.lstrip(previousContent.left(prev1)).rstrip(previousContent.right(prev2))
var temp2 = fileContent
print('Temp1: ', temp)
print('Temp2: ', temp2)
fileContent = previousContent.replace(temp, temp2)
print('FileContent: ', fileContent)
file.open(dir.get_current_dir().plus_file(fileName), File.WRITE)
file.store_string(fileContent)
file.close()
$Commands/Borders/EditCommand/EditSpace.text = temp2
$Commands/Borders/SaveCommand/savedCommand.visible = true
$Commands/Borders/SaveCommand/iconTimer.start()
return

If anyone could redirect me to how to properly do this or give me a snippet of code to actually handles this then that would be cool too. Thank you in advance for reading this

:bust_in_silhouette: Reply From: Error7Studios

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>
`})