summaryrefslogtreecommitdiffstats
path: root/lass/3modules/klem.nix
blob: a297adcd184efda9926206b1b8b5d19412cde8b1 (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
70
71
72
73
74
75
{ config, pkgs, ... }: with import <stockholm/lib>; let
  cfg = config.lass.klem;
in {
  options.lass.klem = mkOption {
    default = {};
    type = types.attrsOf (types.submodule ({ config, ...}: {
      options = {
        target = mkOption {
          default = ".*";
          description = ''
            regex of valid targets
            can be shown with xclip -selection clipboard -t TARGETS
            the first hit is taken as target argument
          '';
          type = types.str;
        };
        script = mkOption {
          description = ''
            file to run if entry is selected
          '';
          type = types.path;
        };
        label = mkOption {
          default = config._module.args.name;
          description = ''
            label to show in dmenu for this script
          '';
          type = types.str;
        };
      };
    }));
  };
  config = let
    klem = pkgs.writers.writeDashBin "klem" ''
      set -x

      labels=""
      # match filetype against patterns
      ${concatMapStringsSep "\n" (script: ''
        ${pkgs.xclip}/bin/xclip -selection clipboard -target TARGETS -out \
          | grep -q '${script.target}'
        if [ $? -eq 0 ]; then
          labels="$labels:${script.label}"
        fi
      '') (attrValues cfg)}

      #remove empty line, feed into dmenu
      script=$(echo "$labels" \
        | ${pkgs.gnused}/bin/sed 's/^://;s/:/\n/g' \
        | ${pkgs.dmenu}/bin/dmenu)

      #run the chosen script
      case $script in
        ${concatMapStringsSep "\n" (script: indent ''
          ${script.label})
            target=$(${pkgs.xclip}/bin/xclip -selection clipboard -target TARGETS -out \
              | ${pkgs.gnugrep}/bin/grep '${script.target}' \
              | ${pkgs.gnugrep}/bin/grep -v TARGETS \
              | ${pkgs.coreutils}/bin/head -1)
            ${pkgs.xclip}/bin/xclip -selection clipboard -target "$target" -out \
            | ${script.script} \
            | ${pkgs.xclip}/bin/xclip -selection clipboard -in
          ;;
        '') (attrValues cfg)}
      esac
    '';
  in mkIf (cfg != {}) {
    environment.systemPackages = [ klem ];
    nixpkgs.overlays = [
      (self: super: {
        klem = klem;
      })
    ];
  };
}