Kai Mx
Kai Mx

Reputation: 15

Electric-pair-mode not detected for some characters with German keyboard layout

So I am trying to get a grip on Emacs 24.5 running on Mac Os 10.10.4.
I have a German keyboard and decided to keep the alt -key as Meta. As I still have to use it for some essential characters such as [ , | and } (resembling alt-5, alt-6 and alt-9) it decided to go with this solution:

(global-set-key "\M-5" (lambda () (interactive) (insert “[“)))
(global-set-key "\M-6" (lambda () (interactive) (insert “]”)))
(global-set-key "\M-7" (lambda () (interactive) (insert “|”)))
...

When I am enabling electric pair mode in the init-file with (electric-pair-mode 1) , it works just fine with ( ) and " ", but not with [ ], { } and ' '.

I then tried a different appraoch by using this code to swap the keys:

(defun redefine-key (key char)
  (define-key function-key-map key char)
  (global-unset-key key))
(redefine-key "\M-5" "[")
(redefine-key "\M-6" "]")
...

Interestingly, the pair feature now works for the square brackets [ ], but not the curly ones { }. Although the ' key on the German keyboard is not even related to the alt-key (it's accessed by the shift-key), it doesn't work at all.
Same results for the autopair package, btw.

Please, anyone? Thanks so much!

Upvotes: 1

Views: 187

Answers (1)

Thomas
Thomas

Reputation: 17422

The way electric-pair-mode works is by installing a callback function ("hook") called electric-pair-post-self-insert-function. As the name suggests, this hook gets invoked by Emacs after the function self-insert-command runs -- which is after you type a key.

And that's your problem here: calling insert is not the same as typing a key. It does not invoke self-insert-command and consequently, the above hook function never gets called. Even worse, you cannot simply invoke self-insert-command programmatically because, unlike insert, it doesn't take a parameter for the character to insert. You have to jump through hoops a bit, but you could try the following:

(global-set-key "\M-5" (lambda (&optional N) (interactive "P") (insert-as-self ?\[ N)))
(global-set-key "\M-6" (lambda (&optional N) (interactive "P") (insert-as-self ?\] N)))
(global-set-key "\M-7" (lambda (&optional N) (interactive "P") (insert-as-self ?\| N)))

(defun insert-as-self (CHAR N)
  (let ((last-command-event CHAR)
        (repeat (if N N 1)))
    (self-insert-command repeat)))

Here, we locally set the special variable last-command-event to "fake" a key stroke before calling self-insert-command.

For curly braces and quotes to work, you have to do two things: First, add the respective (global-set-key ...) definitions to your .emacs file, similar to the ones above. Then let electric-pair-mode know that you want quotes and curlies to be handled by it by adding the following line to your .emacs file:

(setq electric-pair-pairs '((?\' . ?\') (?\" . ?\") (?\{ . ?\}))) –  

Upvotes: 0

Related Questions