Mac – How to get the .emacs init files to load correctly with emacs server

emacsemacsclient

My init files are set up such that my .emacs file is a symlink pointing to an OS-specific init that in turn loads the main init file with configs that are unaffected by OS. I've had no problems with this setup for non-server emacs.

However, it does not work right when using emacsclient. For example, I have a setting for org-mode so that in Terminal on OSX, S-Tab is mapped to backtab so that it works correctly instead of throwing an error about undefined key. This setting works fine if I'm not using emacs server. When I'm using emacsclient, I get the error of undefined keybinding.

I know all my init files are getting loaded without error because any (message "whatever") lines I put in the files show fine when the server is started. So it's not like the emacs server is missing the files somehow. It's as if the mapped keys get loaded for the server but forgotten when a client connects in. I've even tried eval of the key mappings once in an emacsclient buffer, but while no errors, no change. Any ideas?

(btw, --debug-init doesn't show anything strange. Everything is loading without error.)

Best Answer

I think your problem is that your .emacs file sets something like local-function-key-map or input-decode-map but these variables are terminal-local, which means that every "terminal" (your GUI is one "terminal", and every emacsclient connection over a text-teminal will be another "terminal") gets a different value of this variable.

So you need to re-run that code for every new terminal. You can do that from after-make-frame-functions as suggested by reza.safiyat, tho it will be run more often than needed (once per frame, rather than once per terminal). But since this is probably only needed for "xterm" terminals, another good option is to do it from terminal-init-xterm-hook:

(defun my-text-terminal-keys ()
  (define-key input-decode-map ...)
  (define-key local-function-key-map ...))
(add-hook 'terminal-init-xterm-hook #'my-text-terminal-keys)

BTW, sometimes an alternative is to use function-key-map, since that's a global variable and applies equally to all terminals.

Related Question