help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: local key swap? alternatives?


From: Kevin Rodgers
Subject: Re: local key swap? alternatives?
Date: Wed, 07 Sep 2005 11:47:41 -0600
User-agent: Mozilla Thunderbird 0.9 (X11/20041105)

Francisco Borges wrote:
> That does not work because both keys are bound to
> self-insert-command. That's the reason I had failed to do it myself.

Yes, that's a tricky situation.

> I (finally) solved the problem by doing something as ugly as:
>
> (defun my-four ()
>   (interactive)
>   (insert-char (string-to-char "4") 1))
>
> (defun my-dollar ()
>   (interactive)
>   (insert-char (string-to-char "$") 1))
>
> (local-set-key "$" (quote my-four))
> (local-set-key "4" (quote my-dollar))
>
> Would there be a better way to do it? I don't really know Lisp...

Just a few minor points: You could allow a prefix argument to insert
multiple characters, provide a doc string, and avoid converting from a
single-character string to the character:

(defun my-four (&optional arg)
"Insert \"4\" at point.
With a prefix ARG, insert that many characters."
  (interactive "p")
  (insert-char ?4 (or arg 1)))

(defun my-dollar ()
"Insert \"$\" at point.
With a prefix ARG, insert that many characters."
  (interactive "p")
  (insert-char ?$ (or arg 1)))

(local-set-key "$" 'my-four)
(local-set-key "4" 'my-dollar)

If you have many such functions, you'd want to abstract the common parts
with a function-defining macro:

(defmacro define-my-insert (name char)
  "Define the `my-NAME' command, to insert CHAR."
  `(defun ,(intern (format "my-%s" name)) (&optional arg)
     ,(format "Insert \"%c\" at point.
With a prefix ARG, insert that many characters."
              char)
     (interactive "p")
     (insert-char ,char (or arg 1))))

(define-my-insert four ?4)
(define-my-insert dollar ?$)

> I think that the right thing to do is to use a function such as the one
> you send and treat self-insert-command cases specially, but with my
> knowledge of Lisp making these changes to the code above would take more
> than the free time I have to spend on it...

If the define-my-insert macro were rewritten to evalutate the NAME and
CHAR arguments, you could add this to swap-keys:

(when (eq binding-1 'self-insert-command)
  (setq binding-1
        (define-my-insert (intern key-1) (string-to-char key-1))))
(when (eq binding-2 'self-insert-command)
  (setq binding-2
        (define-my-insert (intern key-2) (string-to-char key-2))))

--
Kevin Rodgers





reply via email to

[Prev in Thread] Current Thread [Next in Thread]