Keep Emacs alive through X crashes by running it in the background with –daemon

I periodically have to kill and restart my X server when it freezes. I probably have the wrong configuration, since it starts off in low-graphics mode until I manually restart the graphical login manager (I’m using sddm). Anyway, since it’s been hard to debug and fix that issue, I figured I’d address the part that really bugs me when I restart X: dealing with ungraceful Emacs exits. M-x recover-session does a decent job of restoring my modified files and I usually remember to call it from the scratch screen, but sometimes I forget, and then I end up losing changes.

I started taking advantage of the fact that I used (server-start) to enable other Emacs clients to connect to the same process. Whenever I needed to restart X, I’d first switch to a console, use emacsclient -c to connect to Emacs, and use M-x save-buffers-kill-emacs to close my Emacs neatly. Still, starting my Emacs from X meant that I had to restart Emacs each time I restarted X.

It turns out that you can run Emacs as a background process with emacs --daemon and then connect to it with emacsclient -c. When I did that, though, the emacsclient frame didn’t have my color theme applied. This after-make-frame-functions addition fixes that:

(defun my/setup-color-theme ()
  (interactive)
  (color-theme-solarized-dark)
  (set-face-foreground 'secondary-selection "darkblue")
  (set-face-background 'secondary-selection "lightblue")
  (set-face-background 'font-lock-doc-face "black")
  (set-face-foreground 'font-lock-doc-face "wheat")
  (set-face-background 'font-lock-string-face "black")
  (set-face-foreground 'org-todo "green")
  (set-face-background 'org-todo "black"))
(add-hook 'after-make-frame-functions
          (lambda (frame)
            (select-frame frame)
            (my/setup-color-theme)))

Once I got emacs --daemon and emacsclient -c working to my satisfaction, I decided to go one step further and get it to run automatically when I start my computer. I tried the init script at https://www.emacswiki.org/emacs/EmacsAsDaemon . My Linux install uses systemd, so enabling the init script resulted in a message about a missing service file. I removed the init script and created this ~/.config/systemd/user/emacs.service instead:

[Unit]
Description=Emacs: the extensible, self-documenting text editor

[Service]
Type=forking
ExecStart=/usr/local/bin/emacs --daemon
ExecStop=/usr/local/bin/emacsclient --eval "(progn (setq kill-emacs-hook 'nil) (kill-emacs))"
Restart=always
TimeoutStartSec=0

[Install]
WantedBy=default.target

and then I ran these commands as my regular user account:

systemctl --user enable emacs
systemctl --user start emacs

Then I changed the emacs in my ~/.xsession to emacsclient -c, so that a new X session would connect to the existing session instead of starting a new one. That way, Emacs automatically started as my user whenever I restarted the computer, and I connected to that process when I started X.

Still, restarting X caused the Emacs daemon to crash. This is a GTK-related bug which emacs --daemon warns you about. I recompiled Emacs using ./configure --with-x-toolkit=lucid; make; make install. It seems to work fine now; I can ungracefully restart X, and my Emacs stays the same. Bonus: because Emacs gets initialized when I start my computer and all I need to do is connect to that process, when I log in, it feels like Emacs starts up really quickly.

Final touches: I noticed that TRAMP couldn’t find my SSH keyring, so it got stuck waiting for my passphrase when I tried running remote scripts in Org Babel like so:

#+begin_src sh :dir [email protected]:~
perl library-new.pl Business
#+end_src

Because my SSH socket looks like /tmp/ssh-BLAHBLAHBLAH/agent.PROCESSID, the SSH_AUTH_SOCK setting (Environment=SSH_AUTH_SOCK=%t/keyring/ssh) described on EmacsWiki didn’t work for me. This snippet from https://github.com/nhoffman/.emacs.d/blob/master/init.org worked, though.

(defun my/ssh-refresh ()
  "Reset the environment variable SSH_AUTH_SOCK"
  (interactive)
  (let (ssh-auth-sock-old (getenv "SSH_AUTH_SOCK"))
    (setenv "SSH_AUTH_SOCK"
            (car (split-string
                  (shell-command-to-string
                   "ls -t $(find /tmp/ssh-* -user $USER -name 'agent.*' 2> /dev/null)"))))
    (message
     (format "SSH_AUTH_SOCK %s --> %s"
             ssh-auth-sock-old (getenv "SSH_AUTH_SOCK")))))
(my/ssh-refresh)

Also, emacs --daemon didn’t pick up the default browser I’d configured in KDE. Opening URL links from Org Mode started a separate Chromium process instead of using Google Chrome. I fixed that by switching from browse-url-default-browser to browse-url-generic, like so:

(setq browse-url-generic-program "google-chrome")
(setq browse-url-browser-function 'browse-url-generic)

Let’s see how this works!

2016-04-18 Emacs News

Links from reddit.com/r/emacs, /r/orgmode, Hacker News, planet.emacsen.org, Youtube, the changes to the Emacs NEWS file, and emacs-devel.

Past Emacs News round-ups

Weekly review: Week ending April 15, 2016

Graduated from midwife care this week. A-‘s slow weight gain is something to keep an eye on, but we’re not going to worry until the pediatrician tells us to worry. Might be related to her ventricular septal defect, since that’s a common symptom. She’s alert and looks happy, though, so that’s good.

I made it out to Hacklab for Eric’s practice talk on his Epic Quest of Awesome. It was great to hear the update to his talk, and I picked up a couple of new tips (including an impressive chart from the Actionable Gamification website). We gave him some feedback on his talk, too.

It finally feels like spring, so I’m working on making salads part of our household routine. Lots of walking, too: 37k steps over 5.5 hours total over the whole week, including a nice walk to the midwives.

Filed our personal taxes, yay! I did most of the data entry last month, and I doublechecked everything this week. I compared it to 2014 for extra safety, too. Nice to still be able to crunch the numbers!

Kaizen tweaks this week:

  • Adding buttons to my tracker makes updating baby-related data much easier (nursing, mood, sleep).
  • If I brush my teeth and shower after dinner instead of before bed, then that gives us more flexibility for A-‘s bedtime routine.
  • Wearing cargo pants or scrubs means that I can keep a notepad and a pen handy, which lets me jot down ideas while nursing or settling A-.
  • Using peep-dired and writing an Emacs Lisp function to rename files makes organizing photos easier.
  • Red peppers do okay in the freezer, so I put together a bunch of fajita starters to make future dinners smoother.
  • Grapes and celery can be pre-sliced for Waldorf salad.

2016-04-17a Week ending 2016-04-15 -- index card #journal #weekly output

Blog posts

Sketches

Focus areas and time review

  • Business (1.1h – 0%)
    • Earn (0.0h – 0% of Business)
    • Build (0.5h – 50% of Business)
      • Drawing (0.0h)
      • Paperwork (0.5h)
    • Connect (0.5h – 49% of Business)
  • Relationships (4.9h – 2%)
    • ☑ Add more functions to baby tracker
    • ☑ Hang out with Jen
    • ☑ Check out Eric Boyd’s talk at Hacklab
    • ☑ Midwife final checkup
    • ☑ Maybe check out babywearing social
  • Discretionary – Productive (9.5h – 5%)
    • Emacs (1.1h – 0% of all)
      • ☑ Fix evil plan SVGs
      • ☑ Write some Emacs Lisp to help with organizing photos
      • ☑ Keep Emacs alive through X crashes by running it in the background with –daemon
    • ☑ Update credit card for Paypal
    • ☑ Clean up yard
    • ☑ Plant peas
    • Sewing (0.0h)
      • ☑ Look for a baby sun hat pattern
    • Writing (0.3h)
  • Discretionary – Play (1.7h – 1%)
  • Personal routines (21.1h – 12%)
  • Unpaid work (76.2h – 45%)
    • Childcare (66.8h – 39% of total)
  • Sleep (53.6h – 31% – average of 7.7 per day)

2016-04-11 Emacs News

Links from reddit.com/r/emacs, /r/orgmode, Hacker News, planet.emacsen.org, Youtube, the changes to the Emacs NEWS file, and emacs-devel.

Past Emacs News round-ups

Monthly review: March 2016

March was all about adjusting to life with a newborn. Sleep is still a little patchy, but our routines are gradually getting smoother as we figure out little improvements. I’ve been able to do some cooking and go on various errands. I was pleasantly surprised to find that I was still able to do a little bit of coding, writing, and sewing. I got back to posting Emacs News after a short hiatus. I even managed to check on my consulting clients: they’re doing well and things are running smoothly, hooray. =)

A- was officially diagnosed with microphthalmia, and we’re waiting for the ocularist to schedule the next steps. She also has a medium-sized ventricular septal defect which may or may not resolve itself over time; we’ll see. Thank goodness for public health.

This April, I’m looking forward to:

  • working more closely with the healthcare system and learning more about what to do
  • improving our routines and tools
  • gradually building a habit of going out (parent/baby groups, exercise, etc.)

2016-04-03b March 2016 -- index card #monthly #review output

Blog posts

Sketches

Time

Category Period 1 % Period 2 % Diff h/wk Diff h/wk
Business – Build 0.8 0.2 -0.6 0.3 -1.0
Discretionary – Play 8.6 1.5 -7.1 2.8 -11.9
Unpaid work 17.9 41.6 23.7 74.6 39.9
Unpaid work – Childcare 3.8 35.6 31.8 63.9 53.4
Discretionary – Social 1.2 0.7 -0.5 1.3 -0.8
Discretionary – Family 2.5 0.7 -1.8 1.2 -3.1
Sleep 34.9 36.9 2.0 66.1 3.4
Business – Connect 0.7 0.5 -0.2 0.8 -0.4
Business – Earn 4.0 0.3 -3.6 0.6 -6.1
Discretionary – Productive 8.8 6.5 -2.3 11.7 -3.9
Personal 20.7 11.1 -9.6 20.0 -16.1

An average of 9.4 hours of sleep a day still feels a little short when it’s broken up into 1-2 hour chunks, but that’s okay, I’ll adapt.

Weekly review: Week ending April 8, 2016

This week was a busy one in terms of talking to medical professionals. Met with genetics to kick off the process of testing, met with cardiology for an update, and went to a Toronto Public Health breastfeeding clinic to pick up some tips. It’s so nice to have all these resources.

I’m getting better at getting out of the house for discretionary stuff, too. I made it out to the La Leche League meeting and another session of Baby Time at the library. I even went for a long walk all the way to Dufferin, yay! The ring sling came in handy for that one, since it meant I could keep A- tucked in her snowsuit.

Back to basics this week, I think. I’m going to focus on feeding A-. It looks like A- can take in a little more milk than she gets from nursing, so we’re going to try supplementing (eyedropper, cup, and/or bottle), and increasing skin to skin contact. Her weight gain hasn’t been flagged as an issue yet, but I want to keep on top of that. Once we’ve gotten that sorted out, I can go back to working on improving other parts of our routines. =) Kaizen all the everything!

2016-04-10a Week ending 2016-04-08 -- index card #journal #weekly output

Blog posts

Sketches

Focus areas and time review

  • Business (6.8h – 4%)
    • Earn (0.0h – 0% of Business)
    • Build (0.0h – 0% of Business)
      • Drawing (0.0h)
      • Paperwork (0.0h)
    • Connect (6.8h – 100% of Business)
  • Relationships (3.2h – 1%)
    • ☑ Return carrier
    • ☑ Call genetics and note clinodactyly
    • ☑ Follow up with aboutface for connecting with other anophthalmia/microphthalmia families
    • ☑ Ask about lactation consultant referral
    • ☑ Follow up with cardiologist
  • Discretionary – Productive (8.0h – 4%)
    • Emacs (1.3h – 0% of all)
      • ☑ Do another Emacs News review
      • ☑ Set up Emacs as a daemon
      • ☐ [#A] Do another Emacs News review
    • Sewing (1.3h)
      • ☑ Prototype arm warmers
      • ☑ Mend pants
    • Writing (1.5h)
    • ☑ Set up phone as remote keyboard
  • Discretionary – Play (0.4h – 0%)
  • Personal routines (16.0h – 9%)
  • Unpaid work (76.5h – 45%)
    • Childcare (64.5h – 38% of total)
  • Sleep (57.2h – 34% – average of 8.2 per day)