From d16227bb2c205869b1c78a16093dfff16d6817e4 Mon Sep 17 00:00:00 2001 From: "Dustin C. Hatch" Date: Tue, 14 Jun 2016 14:06:12 -0500 Subject: [PATCH] dmenu_snips: Copy text blocks to clipboard using dmenu --- dmenu_snips.py | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100755 dmenu_snips.py diff --git a/dmenu_snips.py b/dmenu_snips.py new file mode 100755 index 0000000..5607466 --- /dev/null +++ b/dmenu_snips.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python +import argparse +import locale +import os +import subprocess +import yaml + + +SNIPS_PATH = os.path.expanduser(os.environ.get('SNIPS_PATH', '~/.snips')) + + +codec = locale.getpreferredencoding() + + +def dmenu(options, args=None): + cmd = ['dmenu'] + if args: + cmd += args + p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE) + with p.stdout: + with p.stdin: + for option in options: + p.stdin.write(option.encode(codec) + b'\n') + return p.stdout.read().strip().decode(codec) + + +def load_snips(path): + with open(path) as f: + return yaml.safe_load(f) + + +def xclip(data, selection='clipboard'): + cmd = ['xclip', '-selection', selection] + p = subprocess.Popen(cmd, stdin=subprocess.PIPE) + with p.stdin: + p.stdin.write(data.encode(codec)) + + +def parse_args(): + parser = argparse.ArgumentParser() + parser.add_argument( + 'snips', nargs='?', default=SNIPS_PATH, + help='Path to snips YAML document', + ) + parser.add_argument( + '--selection', '-s', default='clipboard', + help='X11 selection (clipboard) to use', + ) + return parser.parse_args() + + +def main(): + args = parse_args() + snips = load_snips(args.snips) + selected = dmenu(sorted(snips.keys()), ['-i']) + xclip(snips[selected], args.selection) + + +if __name__ == '__main__': + main()