#!/bin/bash

# set -x

#
# starts an editor (asynchronous)
#
# if the environment variable ARB_TEXTEDIT is set (to the name of an editor) that editor will be used as default.
# Example setting for bash users (add to ~/.bashrc):
#
#           export ARB_TEXTEDIT="gedit"
#
# If ARB_TEXTEDIT is set to a value not listed in X_EDITORS below,
# it is assumed that the editor needs a console window to run.
#
# known editors (most preferable first):
X_EDITORS="xed gedit kate kwrite textedit xedit xdg-open xemacs emacs"
CONSOLE_EDITORS="vim vi editor edit"
ALL_EDITORS="$X_EDITORS $CONSOLE_EDITORS"

show_envar_notes() {
    echo "Note: Please set the environment variable \$ARB_TEXTEDIT to the"
    echo "      name of your preferred text editor, by adding a line like"
    echo "              ARB_TEXTEDIT=gedit"
    echo "      into your ~/.bashrc (or similar if not using bash)."
}

exit_with_message() {
    local MSG="$1" ; shift
    arb_message "Error running arb_textedit: $MSG (see console for further information)"
    exit 1
}

if [ -z "$ARB_TEXTEDIT" ]; then
    echo '$ARB_TEXTEDIT is not defined - looking for known editors ..'

    # try to find one of the editors listed above
    for EDITOR in $ALL_EDITORS; do
        if [ -z "$ARB_TEXTEDIT" ]; then
            if [ -x "`which $EDITOR`" ]; then
                ARB_TEXTEDIT=$EDITOR
            fi
        fi
    done

    if [ -z "$ARB_TEXTEDIT" ]; then
        echo "Error: ARB could not detect an editor that can be used to edit textfiles."
        show_envar_notes
        echo "You may as well install any of the editors known by ARB:"
        echo "    $X_EDITORS"
        exit_with_message "Failed to auto-detect a text editor\n(set environment variable ARB_TEXTEDIT to the name of your editor, e.g. 'ARB_TEXTEDIT=gedit')"
    fi
    echo "Using '$ARB_TEXTEDIT' as text editor."
else
    echo "Using user-defined '$ARB_TEXTEDIT' as text editor."
fi

if [ -z "$1" ]; then
    echo "Usage: arb_textedit filename"
    echo "Edits a file using $ARB_TEXTEDIT"
    exit_with_message "missing argument"
else
    IS_X_EDITOR=0
    for EDI in $X_EDITORS; do
        if [ "$EDI" = "$ARB_TEXTEDIT" ]; then
            IS_X_EDITOR=1
        fi
    done

    ERRMSG="Error running text-editor '$ARB_TEXTEDIT' - please check ARB_TEXTEDIT"

    if [ "$IS_X_EDITOR" = "1" ]; then
        echo "[ editor command: $ARB_TEXTEDIT \"$1\" & ]"
        ($ARB_TEXTEDIT "$1" || arb_message "$ERRMSG") &
    else
        if [ -z "$ARB_XCMD" ]; then
            if [ -z "$ARB_XTERM" ]; then
                ARB_XTERM="xterm -sl 1000 -sb -geometry 130x20"
            fi
            ARB_XCMD="$ARB_XTERM -e"
        fi
        echo "[ editor command: $ARB_XCMD $ARB_TEXTEDIT \"$1\" & ]"
        ($ARB_XCMD $ARB_TEXTEDIT "$1" || arb_message "$ERRMSG" ) &
    fi
fi


