# @yaml
# signature: "replace\n<replacement_text>\nend_replace"
# docstring: replaces *all* of the lines in the currently open window with the replacement_text. The replacement text is terminated by a line with only end_replace on it. All of the <replacement_text> will be entered, so make sure your indentation is formatted properly.
# end_name: end_replace
replace() {
    if [ -z "$CURRENT_FILE" ]
    then
        echo 'No file open. Use the `open` command first.'
        return
    fi

    local max_line=$(awk 'END {print NR}' $CURRENT_FILE)
    local start_line=$(jq -n "[1 + $CURRENT_LINE - $WINDOW/ 2, 1] | max")
    local end_line=$(jq -n "[$CURRENT_LINE + $WINDOW/2, $max_line] | min")

    # Bash array starts at 0, so let's adjust
    local start_line=$((start_line - 1))
    local end_line=$((end_line))  # we don't need to subtract 1 since the replacement is [start_line, end_line)

    local replacement=()
    while IFS= read -r line
    do
        replacement+=("$line")
    done

    # Read the file line by line into an array
    mapfile -t lines < "$CURRENT_FILE"
    local new_lines=("${lines[@]:0:$start_line}" "${replacement[@]}" "${lines[@]:$((end_line))}")
    # Write the new stuff directly back into the original file
    printf "%s\n" "${new_lines[@]}" >| "$CURRENT_FILE"

    echo "Your changes have been applied successfully. Here's what it looks like now:"
    _constrain_line
    _print
    echo "File updated. Please review the changes and make sure they are correct (correct indentation, no duplicate lines, etc). Edit the file again if necessary."
}
