aboutsummaryrefslogtreecommitdiffstats
path: root/fzf-url.sh
blob: 4fe501c9e8ac15263f56474408b11fbd5931900e (plain)
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#!/usr/bin/env bash
#===============================================================================
#   Author: Wenxuan
#    Email: wenxuangm@gmail.com
#  Created: 2018-04-06 12:12
#===============================================================================
get_fzf_options() {
    local fzf_options
    local fzf_default_options='-d 35% -m -0 --no-preview --no-border'
    fzf_options="$(tmux show -gqv '@fzf-url-fzf-options')"
    [ -n "$fzf_options" ] && echo "$fzf_options" || echo "$fzf_default_options"
}

fzf_filter() {
  eval "fzf-tmux $(get_fzf_options)"
}

open_url() {
    #set -x
    #echo "browser is $BROWSER"
    if [[ -n $BROWSER ]]; then
        nohup "$BROWSER" "$@"
    elif hash xdg-open &>/dev/null; then
        nohup xdg-open "$@"
    elif hash open &>/dev/null; then
        nohup open "$@"
    fi
    #set +x
}

# source user environment before running xdg-open or $BROWSER if they
# redefine it.
if [ -e ~/.config/shell/environment ]; then
    source ~/.config/shell/environment
fi


limit='screen'
[[ $# -ge 2 ]] && limit=$2

if [[ $limit == 'screen' ]]; then
    content="$(tmux capture-pane -J -p)"
else
    content="$(tmux capture-pane -J -p -S -"$limit")"
fi

# debug
#exec >/tmp/url.log 2>&1
#set -x

regexes=(
    '(\[\d+\]\s*)?(https?|ftp|file):/?//[-A-Za-z0-9+&@#/%?=~_|!:,.;]*[-A-Za-z0-9+&@#/%=~_|]'
    '(\[\d+\]\s*)?\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(:\d{1,5})?(/\S+)*'
    '(\[\d+\)\s*)?(ssh://)?git@\S*'
)

urls=()
for regex in "${regexes[@]}"; do
    mapfile -t -O "${#urls[@]}" urls < \
        <(printf "%s\n" "$content" | grep -Po -- "$regex")
done

[ "${#urls[@]}" -eq 0 ] && tmux display 'tmux-fzf-url: no URLs found' && exit

mapfile -t chosen < <(fzf_filter <<< "$(printf "%s\n" "${urls[@]}")")

for item in "${chosen[@]}"; do
    open_url "$(printf "%s" "$item" | grep -Po '^\s*(\[\d+\])?\s*\K.*$')" &>"/tmp/tmux-$(id -u)-fzf-url.log"
done