fork/home-manager

git clone https://git.julia.blue/fork/home-manager

sisyphushappyqutebrowser: add greasemonkey userscript option3433206e

master
10.9 KiB339 linesraw
1{ config, lib, pkgs, ... }:
2
3with lib;
4
5let
6
7  cfg = config.programs.qutebrowser;
8
9  formatLine = o: n: v:
10    let
11      formatValue = v:
12        if builtins.isNull v then
13          "None"
14        else if builtins.isBool v then
15          (if v then "True" else "False")
16        else if builtins.isString v then
17          ''"${v}"''
18        else if builtins.isList v then
19          "[${concatStringsSep ", " (map formatValue v)}]"
20        else
21          builtins.toString v;
22    in if builtins.isAttrs v then
23      concatStringsSep "\n" (mapAttrsToList (formatLine "${o}${n}.") v)
24    else
25      "${o}${n} = ${formatValue v}";
26
27  formatDictLine = o: n: v: ''${o}['${n}'] = "${v}"'';
28
29  formatKeyBindings = m: b:
30    let
31      formatKeyBinding = m: k: c:
32        ''config.bind("${k}", "${escape [ ''"'' ] c}", mode="${m}")'';
33    in concatStringsSep "\n" (mapAttrsToList (formatKeyBinding m) b);
34
35  formatQuickmarks = n: s: "${n} ${s}";
36
37in {
38  options.programs.qutebrowser = {
39    enable = mkEnableOption "qutebrowser";
40
41    package = mkOption {
42      type = types.package;
43      default = pkgs.qutebrowser;
44      defaultText = literalExpression "pkgs.qutebrowser";
45      description = "Qutebrowser package to install.";
46    };
47
48    aliases = mkOption {
49      type = types.attrsOf types.str;
50      default = { };
51      description = ''
52        Aliases for commands.
53      '';
54    };
55
56    loadAutoconfig = mkOption {
57      type = types.bool;
58      default = false;
59      description = ''
60        Load settings configured via the GUI.
61      '';
62    };
63
64    searchEngines = mkOption {
65      type = types.attrsOf types.str;
66      default = { };
67      description = ''
68        Search engines that can be used via the address bar. Maps a search
69        engine name (such as `DEFAULT`, or
70        `ddg`) to a URL with a `{}`
71        placeholder. The placeholder will be replaced by the search term, use
72        `{{` and `}}` for literal
73        `{/}` signs. The search engine named
74        `DEFAULT` is used when
75        `url.auto_search` is turned on and something else than
76        a URL was entered to be opened. Other search engines can be used by
77        prepending the search engine name to the search term, for example
78        `:open google qutebrowser`.
79      '';
80      example = literalExpression ''
81        {
82          w = "https://en.wikipedia.org/wiki/Special:Search?search={}&go=Go&ns0=1";
83          aw = "https://wiki.archlinux.org/?search={}";
84          nw = "https://nixos.wiki/index.php?search={}";
85          g = "https://www.google.com/search?hl=en&q={}";
86        }
87      '';
88    };
89
90    settings = mkOption {
91      type = types.attrsOf types.anything;
92      default = { };
93      description = ''
94        Options to add to qutebrowser {file}`config.py` file.
95        See <https://qutebrowser.org/doc/help/settings.html>
96        for options.
97      '';
98      example = literalExpression ''
99        {
100          colors = {
101            hints = {
102              bg = "#000000";
103              fg = "#ffffff";
104            };
105            tabs.bar.bg = "#000000";
106          };
107          tabs.tabs_are_windows = true;
108        }
109      '';
110    };
111
112    keyMappings = mkOption {
113      type = types.attrsOf types.str;
114      default = { };
115      description = ''
116        This setting can be used to map keys to other keys. When the key used
117        as dictionary-key is pressed, the binding for the key used as
118        dictionary-value is invoked instead. This is useful for global
119        remappings of keys, for example to map Ctrl-[ to Escape. Note that when
120        a key is bound (via `bindings.default` or
121        `bindings.commands`), the mapping is ignored.
122      '';
123    };
124
125    enableDefaultBindings = mkOption {
126      type = types.bool;
127      default = true;
128      description = ''
129        Disable to prevent loading default key bindings.
130      '';
131    };
132
133    keyBindings = mkOption {
134      type = with types; attrsOf (attrsOf (separatedString " ;; "));
135      default = { };
136      description = ''
137        Key bindings mapping keys to commands in different modes. This setting
138        is a dictionary containing mode names and dictionaries mapping keys to
139        commands: `{mode: {key: command}}` If you want to map
140        a key to another key, check the `keyMappings` setting
141        instead. For modifiers, you can use either `-` or
142        `+` as delimiters, and these names:
143
144        Control
145        : `Control`, `Ctrl`
146
147        Meta
148        : `Meta`, `Windows`, `Mod4`
149
150        Alt
151        : `Alt`, `Mod1`
152
153        Shift
154        : `Shift`
155
156        For simple keys (no `<>`-signs), a capital
157        letter means the key is pressed with Shift. For special keys (with
158        `<>`-signs), you need to explicitly add
159        `Shift-` to match a key pressed with shift. If you
160        want a binding to do nothing, bind it to the `nop`
161        command. If you want a default binding to be passed through to the
162        website, bind it to null. Note that some commands which are only useful
163        for bindings (but not used interactively) are hidden from the command
164        completion. See `:help` for a full list of available
165        commands. The following modes are available:
166
167        `normal`
168        : Default mode, where most commands are invoked.
169
170        `insert`
171        : Entered when an input field is focused on a website, or by
172          pressing `i` in normal mode. Passes through almost all keypresses
173          to the website, but has some bindings like
174          `<Ctrl-e>` to open an external editor.
175          Note that single keys can't be bound in this mode.
176
177        `hint`
178        : Entered when `f` is pressed to select links with the keyboard. Note
179          that single keys can't be bound in this mode.
180
181        `passthrough`
182        : Similar to insert mode, but passes through all keypresses except
183          `<Escape>` to leave the mode. It might be
184          useful to bind `<Escape>` to some other
185          key in this mode if you want to be able to send an Escape key to
186          the website as well. Note that single keys can't be bound in this
187          mode.
188
189        `command`
190        : Entered when pressing the `:` key in order to enter a command. Note
191          that single keys can't be bound in this mode.
192
193        `prompt`
194        : Entered when there's a prompt to display, like for download
195          locations or when invoked from JavaScript.
196
197        `yesno`
198        : Entered when there's a yes/no prompt displayed.
199
200        `caret`
201        : Entered when pressing the `v` mode, used to select text using the
202          keyboard.
203
204        `register`
205        : Entered when qutebrowser is waiting for a register name/key for
206          commands like `:set-mark`.
207      '';
208      example = literalExpression ''
209        {
210          normal = {
211            "<Ctrl-v>" = "spawn mpv {url}";
212            ",p" = "spawn --userscript qute-pass";
213            ",l" = '''config-cycle spellcheck.languages ["en-GB"] ["en-US"]''';
214            "<F1>" = mkMerge [
215              "config-cycle tabs.show never always"
216              "config-cycle statusbar.show in-mode always"
217              "config-cycle scrolling.bar never always"
218            ];
219          };
220          prompt = {
221            "<Ctrl-y>" = "prompt-yes";
222          };
223        }
224      '';
225    };
226
227    quickmarks = mkOption {
228      type = types.attrsOf types.str;
229      default = { };
230      description = ''
231        Quickmarks to add to qutebrowser's {file}`quickmarks` file.
232        Note that when Home Manager manages your quickmarks, you cannot edit them at runtime.
233      '';
234      example = literalExpression ''
235        {
236          nixpkgs = "https://github.com/NixOS/nixpkgs";
237          home-manager = "https://github.com/nix-community/home-manager";
238        }
239      '';
240    };
241
242    greasemonkey = mkOption {
243      type = types.listOf types.package;
244      default = [ ];
245      example = literalExpression ''
246        [
247          (pkgs.fetchurl {
248            url = "https://raw.githubusercontent.com/afreakk/greasemonkeyscripts/1d1be041a65c251692ee082eda64d2637edf6444/youtube_sponsorblock.js";
249            sha256 = "sha256-e3QgDPa3AOpPyzwvVjPQyEsSUC9goisjBUDMxLwg8ZE=";
250          })
251          (pkgs.writeText "some-script.js" '''
252            // ==UserScript==
253            // @name  Some Greasemonkey script
254            // ==/UserScript==
255          ''')
256        ]
257      '';
258      description = ''
259        Greasemonkey userscripts to add to qutebrowser's {file}`greasemonkey`
260        directory.
261      '';
262    };
263
264    extraConfig = mkOption {
265      type = types.lines;
266      default = "";
267      description = ''
268        Extra lines added to qutebrowser {file}`config.py` file.
269      '';
270    };
271  };
272
273  config = let
274    qutebrowserConfig = concatStringsSep "\n" ([
275      (if cfg.loadAutoconfig then
276        "config.load_autoconfig()"
277      else
278        "config.load_autoconfig(False)")
279    ] ++ mapAttrsToList (formatLine "c.") cfg.settings
280      ++ mapAttrsToList (formatDictLine "c.aliases") cfg.aliases
281      ++ mapAttrsToList (formatDictLine "c.url.searchengines") cfg.searchEngines
282      ++ mapAttrsToList (formatDictLine "c.bindings.key_mappings")
283      cfg.keyMappings
284      ++ optional (!cfg.enableDefaultBindings) "c.bindings.default = {}"
285      ++ mapAttrsToList formatKeyBindings cfg.keyBindings
286      ++ optional (cfg.extraConfig != "") cfg.extraConfig);
287
288    quickmarksFile = optionals (cfg.quickmarks != { }) concatStringsSep "\n"
289      ((mapAttrsToList formatQuickmarks cfg.quickmarks));
290
291    greasemonkeyDir = optionals (cfg.greasemonkey != [ ]) pkgs.linkFarmFromDrvs
292      "greasemonkey-userscripts" cfg.greasemonkey;
293  in mkIf cfg.enable {
294    home.packages = [ cfg.package ];
295
296    home.file.".qutebrowser/config.py" =
297      mkIf pkgs.stdenv.hostPlatform.isDarwin { text = qutebrowserConfig; };
298
299    home.file.".qutebrowser/quickmarks" =
300      mkIf (cfg.quickmarks != { } && pkgs.stdenv.hostPlatform.isDarwin) {
301        text = quickmarksFile;
302      };
303
304    xdg.configFile."qutebrowser/config.py" =
305      mkIf pkgs.stdenv.hostPlatform.isLinux {
306        text = qutebrowserConfig;
307        onChange = ''
308          hash="$(echo -n "$USER" | md5sum | cut -d' ' -f1)"
309          socket="''${XDG_RUNTIME_DIR:-/run/user/$UID}/qutebrowser/ipc-$hash"
310          if [[ -S $socket ]]; then
311            command=${
312              escapeShellArg (builtins.toJSON {
313                args = [ ":config-source" ];
314                target_arg = null;
315                protocol_version = 1;
316              })
317            }
318            echo "$command" | ${pkgs.socat}/bin/socat -lf /dev/null - UNIX-CONNECT:"$socket"
319          fi
320          unset hash socket command
321        '';
322      };
323
324    xdg.configFile."qutebrowser/quickmarks" =
325      mkIf (cfg.quickmarks != { } && pkgs.stdenv.hostPlatform.isLinux) {
326        text = quickmarksFile;
327      };
328
329    home.file.".qutebrowser/greasemonkey" =
330      mkIf (cfg.greasemonkey != [ ] && pkgs.stdenv.hostPlatform.isDarwin) {
331        source = greasemonkeyDir;
332      };
333
334    xdg.configFile."qutebrowser/greasemonkey" =
335      mkIf (cfg.greasemonkey != [ ] && pkgs.stdenv.hostPlatform.isLinux) {
336        source = greasemonkeyDir;
337      };
338  };
339}