aboutsummaryrefslogtreecommitdiff
path: root/vipaste
blob: 15cc89292259704d8c9560ef0038d4030ab96bdf (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
#!/bin/bash

usage() {
  cat <<EOF
$SELF - edit X11 selection buffer

Usage: $SELF [-n]

Loads the current contents of the X11 selection (copy/paste) buffer
into an editor. After editing & exiting the editor, the results are
copied back into the selection buffer, for pasting elsewhere.

The last line (only line, for 1-line selections) will have its newline
removed, if there is one.

If the file is empty after editing, or if the editor exits with
non-zero (error) status, the selection buffer won't be altered.

To start with an empty buffer rather than the current selection, use
the -n option.

The editor to be run is set via VISUAL in the environment. If it's not
set, EDITOR is used if set. If neither is set, vi is used. If you're
going to run this without a terminal (e.g. using xbindkeys or a "Run
Program" dialog), you'll want to set VISUAL to something that doesn't
require a terminal (e.g. a GUI editor like gvim or gedit).

Requires xsel and perl on the PATH.

Written by B. Watson <yalhcru@gmail.com> and released under the WTFPL.
EOF
  exit $1
}

set -e

SELF="$( basename $0 )"
CMD="xsel -o"

[ "$1"  = "--help" ] && usage 0
[ "$1"  = "-n"     ] && CMD=":"  && shift
[ "$1" != ""       ] && usage 1

TMPFILE="$( mktemp -t $SELF.XXXXXX )"
trap "rm -f \"$TMPFILE\"" EXIT

$CMD > "$TMPFILE"
${VISUAL:-${EDITOR:-vi}} "$TMPFILE"

# remove the newline(s) from the end of the file
perl -i -0777 -pe 's/\n*$//' "$TMPFILE"

[ -s "$TMPFILE" ] && xsel -i < "$TMPFILE"