This works for me, and it correctly goes to the end of the selection.
I just added the osascript part in the previous answer, and put it in the code that was in the original R bundle written by Hans-Jörg Bibiko.
Set "scope selector" to "source.r" and "output" to "discard".
Set "Input" to "line" and it does what I need: send the line if nothing is selected, and send the selection otherwise.
edit: it works perfectly with selections, but not with line. When you do not select text it just re-runs everything from the top of the file
edit2: solved, I wrote to Hans-Jörg Bibiko and he pointed me to the "Input" selection.
#!/usr/bin/env bash
# input is selection or document
rawText="$(cat | sed 's/ / /g;')"
curDir=''
if [[ ${#TM_DIRECTORY} -gt 0 ]]; then
curDir="$TM_DIRECTORY"
fi
osascript -e 'on run(theCode)' \
-e ' tell application "Terminal"' \
-e ' do script theCode in window 1' \
-e ' end tell' \
-e 'end run' -- "$rawText"
if [ "$TM_LINE_NUMBER" != "" ]; then
"$TM_MATE" -l "$(($TM_LINE_NUMBER+1)):1000000"
elif [[ $TM_SELECTION =~ [1-9][0-9]*:?[0-9]*-([1-9][0-9]*):?[0-9]* ]]; then
# Regular Selection
"$TM_MATE" -l "$((${BASH_REMATCH[1]}+1)):1000000"
elif [[ $TM_SELECTION =~ [1-9][0-9]*:?[0-9]*x([1-9][0-9]*):?[0-9]* ]]; then
# Block (option) selection
"$TM_MATE" -l "$((${BASH_REMATCH[1]}+1)):1000000"
else
"$TM_MATE"
fi