public
Last active

Vim function for your .bashrc. Turns "vim file1:42 file2:1337" into "/usr/bin/vim file1 file2 -S (script that moves the cursor to the correct line)"

  • Download Gist
bashrc.append
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
# vim file:34 otherfile:1337 -> Open files at respective lines. And in tabs!
vim() {
declare -a args
let fcount=0
hit_dashdash=
for arg in "$@" ;do
if [[ "$arg" =~ ^- && ! "$hit_dashdash" ]] ;then
args+=("$arg")
[[ "$arg" = "--" ]] && hit_dashdash=1
continue
fi
let fcount+=1
if [[ "$arg" =~ : && -e "${arg%:*}" && "${arg##*:}" =~ ^[0-9]+*$ ]] ;then
args+=("${arg%:*}")
lines[$fcount]=${arg##*:}
else
args+=("$arg")
fi
done
script=$'tab all\ntablast\n'
while [[ $fcount -gt 0 ]] ;do
script+="${lines[$fcount]}"$'\n'
let fcount-=1
[[ $fcount -gt 0 ]] && script+=$'tabprev\n'
done
`type -P vim` -S <(echo "$script") "${args[@]}"
}

FWIW, I am currently using this one in ~/bin/view (with a symlink ~/bin/vimtoview`):

#!/bin/bash
vim_args=()
for arg; do
    case $arg in
    [-+]*)
        vim_args+=("$arg")
        shift
        ;;
    *)
        break
        ;;
    esac
done
if [[ $1 == *:* ]] && [ ! -e "$1" ]; then
    cmd=()
    for arg; do
        if [ ! -e "${arg%%:}" ] && ! [[ $arg =~ ^.+:[0-9]+.*$ ]]; then
            cmd=()
            break
        fi
        file=${arg%%:*}
        line=
        if [[ $arg == *:* ]]; then
            line=${arg#$file:}
            line=${line%%:*}
        fi
        if [ ${#cmd[@]} -eq 0  ]; then
            [ -z "$line" ] || cmd+=("+$line")
            cmd+=("$file")
        else
            file="${file/ /\ }"
            cmd+=("+tabnew ${line:++$line} ${file}")
        fi
    done
    if [ ${#cmd[@]} -eq 0 ]; then
        # example: foo.c:123:some grep stuff
        file="${1%%:*}" # foo.c
        lineno="${1#$file:}"    # 123:some grep stuff
        lineno="${lineno%%:*}"  # 123
        shift
        cmd=("$file")
        ! [[ $lineno =~ ^[0-9]+$ ]] || cmd+=(+$lineno)
        cmd+=("$@")
    fi
    set -- "${cmd[@]}"
fi
app="${0##*/}"
program=
for dir in /usr/local/bin /usr/bin; do
    if [ -x "$dir/$app" ]; then
        program="$dir/$app"
        break
    fi
done

exec "$program" "${vim_args[@]}" "$@"

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.