TransWikia.com

Implement modal interface in a major mode

Emacs Asked by nephewtom on November 4, 2020

I am creating a major mode, and would like to have modal interface (such as vi) on it.
I want to have a special key that toggles the behaviour on arrow keys.
So, for example, if the special key is hit, arrows move the char underneath.
And when the special key is hit again, arrows behave as normally.

How can I implement such thing?
I suspect it could work creating two different keymaps for the mode.
And then switching from one to the other after the special key press.
But not really sure if that would be the way to do it.

And honestly, I do not really know how to make that special key, so it can rebind other keys on the fly.
Hmmm… I should probably look for the code of a mode that implements a modal interface…

2 Answers

So, following @Tyler advice I came with this:

;; Major mode
(defvar pletter-mode-keymap (make-sparse-keymap))
(define-key pletter-mode-keymap (kbd "C-q") 'move-pletter-mode)

(define-derived-mode pletter-mode fundamental-mode "pletter"
  "pletter-mode is a major mode for playing with letters and words.
\{pletter-mode-map}"
  (use-local-map pletter-mode-keymap) ;; not needed
  )

;; Minor mode
(defvar move-pletter-mode-keymap (make-sparse-keymap))
(define-key move-pletter-mode-keymap (kbd "<left>") 'movechar-to-left)
(define-key move-pletter-mode-keymap (kbd "<right>") 'movechar-to-right)

(define-minor-mode move-pletter-mode
  "Minor mode to toggle arrows bindings for pletter-mode."
  nil " move" move-pletter-mode-keymap
  (message "Toggle move-pletter"))

(provide 'pletter-mode)

which seems to work for me.

Answered by nephewtom on November 4, 2020

You could create a minor mode that binds the arrow keys to the functions you want. Then your 'special' key only needs to toggle the minor mode on and off. You would bind the 'special' key in your major mode map, and make the minor mode buffer-local, so it would only change the behaviour in files in that major mode.

Answered by Tyler on November 4, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP