fork/home-manager

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

Robert HelgessonMerge PR #421575790441

master
7.0 KiB210 linesraw
1{ config, lib, pkgs, ... }:
2
3with lib;
4
5let
6
7  cfg = config.services.emacs;
8  emacsCfg = config.programs.emacs;
9  emacsBinPath = "${cfg.package}/bin";
10  emacsVersion = getVersion cfg.package;
11
12  clientWMClass =
13    if versionAtLeast emacsVersion "28" then "Emacsd" else "Emacs";
14
15  # Adapted from upstream emacs.desktop
16  clientDesktopItem = pkgs.writeTextDir "share/applications/emacsclient.desktop"
17    (generators.toINI { } {
18      "Desktop Entry" = {
19        Type = "Application";
20        Exec = "${emacsBinPath}/emacsclient ${
21            concatStringsSep " " cfg.client.arguments
22          } %F";
23        Terminal = false;
24        Name = "Emacs Client";
25        Icon = "emacs";
26        Comment = "Edit text";
27        GenericName = "Text Editor";
28        MimeType =
29          "text/english;text/plain;text/x-makefile;text/x-c++hdr;text/x-c++src;text/x-chdr;text/x-csrc;text/x-java;text/x-moc;text/x-pascal;text/x-tcl;text/x-tex;application/x-shellscript;text/x-c;text/x-c++;";
30        Categories = "Development;TextEditor;";
31        Keywords = "Text;Editor;";
32        StartupWMClass = clientWMClass;
33      };
34    });
35
36  # Match the default socket path for the Emacs version so emacsclient continues
37  # to work without wrapping it.
38  socketDir = "%t/emacs";
39  socketPath = "${socketDir}/server";
40
41in {
42  meta.maintainers = [ maintainers.tadfisher ];
43
44  options.services.emacs = {
45    enable = mkEnableOption "the Emacs daemon";
46
47    package = mkOption {
48      type = types.package;
49      default = if emacsCfg.enable then emacsCfg.finalPackage else pkgs.emacs;
50      defaultText = literalExpression ''
51        if config.programs.emacs.enable then config.programs.emacs.finalPackage
52        else pkgs.emacs
53      '';
54      description = "The Emacs package to use.";
55    };
56
57    extraOptions = mkOption {
58      type = with types; listOf str;
59      default = [ ];
60      example = [ "-f" "exwm-enable" ];
61      description = ''
62        Extra command-line arguments to pass to {command}`emacs`.
63      '';
64    };
65
66    client = {
67      enable = mkEnableOption "generation of Emacs client desktop file";
68      arguments = mkOption {
69        type = with types; listOf str;
70        default = [ "-c" ];
71        description = ''
72          Command-line arguments to pass to {command}`emacsclient`.
73        '';
74      };
75    };
76
77    # Attrset for forward-compatibility; there may be a need to customize the
78    # socket path, though allowing for such is not easy to do as systemd socket
79    # units don't perform variable expansion for 'ListenStream'.
80    socketActivation = {
81      enable = mkEnableOption "systemd socket activation for the Emacs service";
82    };
83
84    startWithUserSession = mkOption {
85      type = with types; either bool (enum [ "graphical" ]);
86      default = !cfg.socketActivation.enable;
87      defaultText =
88        literalExpression "!config.services.emacs.socketActivation.enable";
89      example = "graphical";
90      description = ''
91        Whether to launch Emacs service with the systemd user session. If it is
92        `true`, Emacs service is started by
93        `default.target`. If it is
94        `"graphical"`, Emacs service is started by
95        `graphical-session.target`.
96      '';
97    };
98
99    defaultEditor = mkOption rec {
100      type = types.bool;
101      default = false;
102      example = !default;
103      description = ''
104        Whether to configure {command}`emacsclient` as the default
105        editor using the {env}`EDITOR` environment variable.
106      '';
107    };
108  };
109
110  config = mkIf cfg.enable (mkMerge [
111    {
112      assertions = [
113        (lib.hm.assertions.assertPlatform "services.emacs" pkgs
114          lib.platforms.linux)
115      ];
116
117      systemd.user.services.emacs = {
118        Unit = {
119          Description = "Emacs text editor";
120          Documentation =
121            "info:emacs man:emacs(1) https://gnu.org/software/emacs/";
122
123          After = optional (cfg.startWithUserSession == "graphical")
124            "graphical-session.target";
125          PartOf = optional (cfg.startWithUserSession == "graphical")
126            "graphical-session.target";
127
128          # Avoid killing the Emacs session, which may be full of
129          # unsaved buffers.
130          X-RestartIfChanged = false;
131        } // optionalAttrs (cfg.socketActivation.enable) {
132          # Emacs deletes its socket when shutting down, which systemd doesn't
133          # handle, resulting in a server without a socket.
134          # See https://github.com/nix-community/home-manager/issues/2018
135          RefuseManualStart = true;
136        };
137
138        Service = {
139          Type = "notify";
140
141          # We wrap ExecStart in a login shell so Emacs starts with the user's
142          # environment, most importantly $PATH and $NIX_PROFILES. It may be
143          # worth investigating a more targeted approach for user services to
144          # import the user environment.
145          ExecStart = ''
146            ${pkgs.runtimeShell} -l -c "${emacsBinPath}/emacs --fg-daemon${
147            # In case the user sets 'server-directory' or 'server-name' in
148            # their Emacs config, we want to specify the socket path explicitly
149            # so launching 'emacs.service' manually doesn't break emacsclient
150            # when using socket activation.
151              optionalString cfg.socketActivation.enable
152              "=${escapeShellArg socketPath}"
153            } ${escapeShellArgs cfg.extraOptions}"'';
154
155          # Emacs will exit with status 15 after having received SIGTERM, which
156          # is the default "KillSignal" value systemd uses to stop services.
157          SuccessExitStatus = 15;
158
159          Restart = "on-failure";
160        } // optionalAttrs (cfg.socketActivation.enable) {
161          # Use read-only directory permissions to prevent emacs from
162          # deleting systemd's socket file before exiting.
163          ExecStartPost =
164            "${pkgs.coreutils}/bin/chmod --changes -w ${socketDir}";
165          ExecStopPost =
166            "${pkgs.coreutils}/bin/chmod --changes +w ${socketDir}";
167        };
168      } // optionalAttrs (cfg.startWithUserSession != false) {
169        Install = {
170          WantedBy = [
171            (if cfg.startWithUserSession == true then
172              "default.target"
173            else
174              "graphical-session.target")
175          ];
176        };
177      };
178
179      home = {
180        packages = optional cfg.client.enable (hiPrio clientDesktopItem);
181
182        sessionVariables = mkIf cfg.defaultEditor {
183          EDITOR = getBin (pkgs.writeShellScript "editor" ''
184            exec ${
185              getBin cfg.package
186            }/bin/emacsclient "''${@:---create-frame}"'');
187        };
188      };
189    }
190
191    (mkIf cfg.socketActivation.enable {
192      systemd.user.sockets.emacs = {
193        Unit = {
194          Description = "Emacs text editor";
195          Documentation =
196            "info:emacs man:emacs(1) https://gnu.org/software/emacs/";
197        };
198
199        Socket = {
200          ListenStream = socketPath;
201          FileDescriptorName = "server";
202          SocketMode = "0600";
203          DirectoryMode = "0700";
204        };
205
206        Install = { WantedBy = [ "sockets.target" ]; };
207      };
208    })
209  ]);
210}