Repository: susam/devil Branch: main Commit: c2dc9fc28864 Files: 8 Total size: 97.8 KB Directory structure: gitextract_3h1b_6cj/ ├── CHANGES.org ├── CONTRIBUTING.org ├── LICENSE.org ├── MANUAL.org ├── Makefile ├── README.org ├── devil-tests.el └── devil.el ================================================ FILE CONTENTS ================================================ ================================================ FILE: CHANGES.org ================================================ #+options: num:nil * Changelog ** Version 0.7.0 (2023-08-12) :PROPERTIES: :CUSTOM_ID: 0.7.0 :END: *** Added - Repeatable key sequence =, m e=. - Repeatable key sequence =, x u=. - Repeatable key sequence group for =, m @= and =, m h=. - Repeatable key sequence group for =, x [= and =, x ]=. - Repeatable key sequence group for =, x ^= and =, x {= and =, x }=. - Repeatable key sequences =, a= and =, e= added to group for =, p=. - Repeatable key sequences =, m a= and =, m e= added to group for =, m b=. - Customisable variable =devil-global-sets-buffer-default= that, when set to =t=, makes enabling =global-devil-mode= also enable Devil in all new buffers. *** Changed - Support for repeatable key groups. When a Devil key sequence in a repeatable group is typed, then that key sequence or any another key sequence in the same group can be executed and repeated merely by typing the last character of that key sequence. - Repeatable key groups defined in =devil-repeatable-keys= is not ignored anymore when =devil-all-keys-repeatable= is set to non-nil. - Devil key sequences =, p= and =, n= and =, b= and =, f= have been grouped together into a repeatable key group. - Devil key sequences =, m f= and =, m b= have been grouped together into a repeatable key group. *** Fixed - Prevent special key sequences from being repeatable. ** Version 0.6.0 (2023-07-30) :PROPERTIES: :CUSTOM_ID: 0.6.0 :END: *** Changed - Devil key sequence =, m= now translates to =M-= instead of =C-M-=. - Devil key sequence =, m z= now translates to =M-= instead of =C-M-=. - Devil key sequence =, m ,= now translates to =M-,= instead of =C-M-,=. - Devil key sequence =, m m= now translates to =C-M-= instead of =M-=. - Repeatable key sequence =, m m f= changed to =, m f=. - Repeatable key sequence =, m m b= changed to =, m b=. - Repeatable key sequence =, m m y= changed to =, m y=. - Repeatable key sequence =, m m ^= changed to =, m ^=. *** Removed - Devil key translation from =m z= to =M-=. - Devil key translation from =m m= to =m=. - Devil key translation from =m= to =M-=. ** Version 0.5.0 (2023-06-15) :PROPERTIES: :CUSTOM_ID: 0.5.0 :END: *** Added - Function =devil-set-key= to set a new Devil key and update the mode's keymap. - Reinstate variable =devil-version= since it is useful in determining the source version conveniently. It helps during troubleshooting the package when installed from MELPA which sets the package version to a version derived from the current date and time. - Command =devil-describe-key= to describe Devil key sequences. - Command =devil-toggle-logging= to toggle logging. - Special key =, h , k= to execute =devil-describe-key=. - Special key =, h , l= to execute =devil-toggle-logging=. *** Changed - Customising =devil-key= also updates the mode's keymap. - When no binding exists for the translated key sequence, convert the key sequence to a fallback key sequence for terminal Emacs according to =local-function-key-map= and execute any command bound to the fallback key sequence. For example, when the Devil key sequence =, x = is converted to =C-x =, since no command is bound to this key sequence, it is further translated to =C-x TAB= and the command =indent-rigidly= bound to it is executed. - Format control sequence to show the Devil key sequence read by Devil has changed from =%k= to =%r=. - The default special key sequences no longer merely insert literal characters into the buffer. That behaviour was problematic in =isearch-mode= because typing special keys like =, ,= and =, SPC= in =isearch-mode= inserted the literal characters in the buffer as opposed to appending these characters to the search pattern. The default special key sequences now invoke =devil-execute-key= instead which carefully look up the current binding for the current special key and executes it. This produces the correct behaviour of special keys even in =isearch-mode=. *** Fixed - Fix special key sequence =, = which was broken by the previous release of version 0.4.0. - Fix special key =, ,= in =isearch-mode=. ** Version 0.4.0 (2023-05-27) :PROPERTIES: :CUSTOM_ID: 0.4.0 :END: *** Added - Customisable variable =devil-all-keys-repeatable= that makes all Devil key sequences repeatable when set to =t=. - Key =, s= to the default list of repeatable keys. - Key =, d= to the default list of repeatable keys. - Key =, m m ^= to the default list of repeatable keys. - Translate =m m= to =m= to support typing key sequences like =C-c m=. - Translate =m z= to =M-= to support typing key sequences like =C-c M-m= and =C-M-m=. *** Changed - When a Devil key sequence translates to an Emacs key sequence with both the control key and an uppercase letter, the uppercase letter is further translated to its shifted form, e.g., =C-M-V= is translated to =C-M-S-v=. *** Fixed - Fix key translation when the Devil key is a key vector, e.g., =(kbd "")= - Fix key translation of key sequences involving function keys, e.g., =, =, =, =, etc. For example, earlier =, = translated to =C-TAB= and caused "undefined" error even if there was a command bound to =C-=. With this fix, =, = is now translated to =C-= and invokes the command bound to it, if any. ** Version 0.3.0 (2023-05-11) :PROPERTIES: :CUSTOM_ID: 0.3.0 :END: *** Added - Add customisation group =devil=. *** Changed - Move tests out to a separate file. *** Fixed - Fix spacing in documentation strings. - Remove =devil-version= and =devil-show-version=. ** Version 0.2.0 (2023-05-09) :PROPERTIES: :CUSTOM_ID: 0.2.0 :END: *** Added - Key =, k= to the default list of repeatable keys. - Key =, /= to the default list of repeatable keys. - Key =, m m y= to the default list of repeatable keys. - Command =devil-show-version= to display Devil version. *** Changed - Automatically detect the activation key and accumulate it in order to support =devil-mode-map= with multiple activation keys. *** Fixed - Remove a stray =message= call. - Make the function =dev--tests= non-interactive. - Translation issue that caused invalid Emacs key sequences on mapping =-=. For example, mapping =-= to =C-x= and typing =- C-f= produced =C-x CC-xf=. This has been fixed so that =- C-f= is now translated to =C-x C-f=. ** Version 0.1.0 (2023-05-07) :PROPERTIES: :CUSTOM_ID: 0.1.0 :END: *** Added - Devil global and local minor modes. - Default Devil key set to the comma (=,=). - Special key =, ,= to type a literal comma. - Special key =, SPC= to type a comma followed by a space. - Special key =, RET= to type a comma followed by return. - Translation rules that translate =,= and =, z= to =C-=. - Translation rules that translate =m= and =, m m= to =M-=. - Translation rule that translates =, ,= to =,=. - Repeatable key sequences for =, p=, =, n=, =, f=, =, b=, =, m m f=, =, m m b=, and =, m x o=. - Key binding for =isearch-mode-map= to support Devil key sequences in incremental search. - Key binding for =universal-argument-map= to support repeating the universal argument with =u=. ================================================ FILE: CONTRIBUTING.org ================================================ * Contribution Guidelines While contributing changes, bug fixes, pull requests, etc. please follow the contribution guidelines laid out in the following sections. ** Commit Messages :PROPERTIES: :CUSTOM_ID: commit-messages :END: 1. Begin the commit message with a short title. The commit title must not exceed 50 characters in length. Good: #+begin_example Add configuration option to control logging level #+end_example Bad: #+begin_example Introduce a new configuration option to control logging level #+end_example 2. The commit title must be a single line. Good: #+begin_example Add configuration option to control logging level #+end_example Bad: #+begin_example Add configuration option: logging_level #+end_example 3. The commit title must be written in imperative mood. Begin the commit message with words like "Add", "Fix", "Remove", etc. Do not use words like "Added", "Fixes", "Removal", etc. to begin commit summary lines. Good: #+begin_example Add configuration option to control logging level #+end_example Bad: #+begin_example Added configuration option to control logging level #+end_example 4. Do not end the commit title with a punctuation. Good: #+begin_example Add configuration option to control logging level #+end_example Bad: #+begin_example Add configuration option to control logging level. #+end_example 5. Do not start commit title with prefixes like =fix:=, =feat:=, etc. Good: #+begin_example Add configuration option to control logging level #+end_example Bad: #+begin_example feat: Add configuration option to control logging level #+end_example 6. Optionally, add one or more paragraphs that describe the change in detail. This is known as the commit description. There must be a blank line between the commit title and the description. Good: #+begin_example Add configuration option to control logging level This change introduces a new configuration option named logging_level to control the logging level of this application. The logging levels supported are: DEBUG, INFO, WARN, and ERROR. #+end_example Bad: #+begin_example Add configuration option to control logging level This change introduces a new configuration option named logging_level to control the logging level of this application. The logging levels supported are: DEBUG, INFO, WARN, and ERROR. #+end_example 7. When a commit description is present, ensure that no line exceeds 72 characters in length. A decent editor should let you automatically format your paragraphs such that each line is less than or equal to 72 characters. In Vim the commands =:set textwidth=72= followed by =gqap= formats the current paragraph in this manner. In Emacs, the key sequence =M-q= automatically formats the current paragraph so that no line exceeds a certain number of characters (the default is 70 which is fine). Good: #+begin_example Add configuration option to control logging level This change introduces a new configuration option named logging_level to control the logging level of this application. The logging levels supported are: DEBUG, INFO, WARN, and ERROR. #+end_example Bad: #+begin_example Add configuration option to control logging level This change introduces a new configuration option named logging_level to control the logging level of this application. The logging levels supported are: DEBUG, INFO, WARN, and ERROR. #+end_example 8. When a commit description is present and it has multiple sentences, the sentences must be separated by two spaces, i.e., there must be two spaces after each sentence-terminating punctuation. Good: #+begin_example Add configuration option to control logging level This change introduces a new configuration option named logging_level to control the logging level of this application. The logging levels supported are: DEBUG, INFO, WARN, and ERROR. #+end_example Bad: #+begin_example Add configuration option to control logging level This change introduces a new configuration option named logging_level to control the logging level of this application. The logging levels supported are: DEBUG, INFO, WARN, and ERROR. #+end_example ** Content :PROPERTIES: :CUSTOM_ID: content :END: 1. A proposed change should not add major features or increase the scope of the project without prior discussion. Bug fixes and minor improvements are okay. However adding a new feature that significantly increases the scope of this project requires prior discussion. 2. While updating =Makefile=, shell scripts, etc., use syntax, commands, and options that are specified in [[https://pubs.opengroup.org/onlinepubs/9699919799/][POSIX]] as much as possible. Avoid Bash-specific and GNU-specific features. See documentation on [[https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html][POSIX Shell Command Language]], [[https://pubs.opengroup.org/onlinepubs/9699919799/idx/utilities.html][POSIX Utilities]], and [[https://pubs.opengroup.org/onlinepubs/9699919799/utilities/make.html][POSIX Make]] for reference. ================================================ FILE: LICENSE.org ================================================ * The MIT License (MIT) :PROPERTIES: :CUSTOM_ID: the-mit-license :END: Copyright (c) 2022-2023 Susam Pal Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: MANUAL.org ================================================ #+title: Devil Mode #+author: Susam Pal #+email: susam@susam.net #+language: en #+options: ':t toc:nil author:t email:t num:t #+texinfo_dir_category: Emacs misc features #+texinfo_dir_title: Devil: (devil) #+texinfo_dir_desc: Minor mode for Devil-like command entering #+export_file_name: devil #+texinfo: @insertcopying Devil mode trades your comma key in exchange for a modifier-free editing experience in Emacs. Yes, the comma key! The key you would normally wield for punctuation in nearly every corner of text. Yes, this is twisted! It would not be called the Devil otherwise, would it? If it were any more rational, we might call it something divine, like, uh, the God mode? But alas, there is nothing divine to be found here. Welcome, instead, to the realm of the Devil! You will be granted the occasional use of the comma key for punctuation, but only if you can charm the Devil. But beware, for in this sinister domain, you must relinquish your comma key and embrace an editing experience that whispers wicked secrets into your fingertips! * Introduction :PROPERTIES: :CUSTOM_ID: introduction :END: Devil mode intercepts our keystrokes and translates them to Emacs key sequences according to a configurable set of translation rules. For example, with the default translation rules, when we type =, x , f=, Devil translates it to =C-x C-f=. The choice of the comma key (=,=) to mean the control modifier key (=C-=) may seem outrageous. After all, the comma is a very important punctuation both in prose as well as in code. Can we really get away with using =,= to mean the =C-= modifier? It turns out, this terrible idea can be made to work without too much of a hassle. At least it works for me. It might work for you too. If it does not, Devil can be configured to use another key instead of =,= to mean the =C-= modifier. See the section [[*Custom Devil Key]] and the subsequent sections for a few examples. A sceptical reader may rightfully ask: If =,= is translated to =C-=, how on earth are we going to insert a literal =,= into the text when we need to? The section [[*Typing Commas]] answers this. But before we get there, we have some fundamentals to cover. Take the plunge and see what unfolds. Maybe you will like this. Maybe you will not. If you do not like this, you can always retreat to God mode, Evil mode, the vanilla key bindings, or whatever piques your fancy. * Notation :PROPERTIES: :CUSTOM_ID: notation :END: A quick note about the notation used in the document: The previous example shows that =, x , f= is translated to =C-x C-f=. What this really means is that the keystrokes =,x,f= is translated to =ctrl+x ctrl+f=. We do not really type any space after the commas. The key =,= is directly followed by the key =x=. However, the key sequence notation used in this document contains spaces between each keystroke. This is consistent with how key sequences are represented in Emacs in general and how Emacs functions like =key-description=, =describe-key=, etc. represent key sequences. When we really need to type a space, it is represented as =SPC=. * Install :PROPERTIES: :CUSTOM_ID: install :END: Devil is available via [[https://elpa.nongnu.org/nongnu/devil.html][NonGNU ELPA]] and [[https://melpa.org/#/devil][MELPA]]. You may already have a preferred way of installing packages from ELPA/MELPA. If so, install the package named =devil= to get Devil. If you have Emacs 28.1 or a more recent version, it has NonGNU ELPA enabled by default, so you can install Devil quite easily with =M-x package-install RET devil RET= without having to perform any further steps. However, for the sake of completeness, a few very different and basic ways of installing Devil are presented in the next few subsections. ** Install Interactively from MELPA :PROPERTIES: :CUSTOM_ID: install-interactively-from-melpa :END: To install the latest version of Devil from MELPA, perform the following steps: 1. Add the following to the Emacs initialization file (i.e., =~/.emacs= or =~/.emacs.d/init.el= or =~/.config/emacs/init.el=): #+begin_src elisp (require 'package) (add-to-list 'package-archives '("melpa" . "https://melpa.org/packages/") t) (package-initialize) #+end_src 2. Start Emacs with the updated initialization file. Then type these commands: #+begin_example M-x package-refresh-contents RET M-x package-install RET devil RET #+end_example 3. Confirm that Devil is installed successfully with this command: #+begin_example C-h f devil RET #+end_example 4. Enable Devil mode with this command: #+begin_example M-x global-devil-mode RET #+end_example 5. Type =, x , f= and watch Devil translate it to =C-x C-f= and invoke the corresponding command. ** Install Automatically from MELPA :PROPERTIES: :CUSTOM_ID: install-automatically-from-melpa :END: Here is yet another basic way to install and enable Devil using Elisp: #+begin_src elisp (require 'package) (add-to-list 'package-archives '("melpa" . "https://melpa.org/packages/") t) (package-initialize) (unless package-archive-contents (package-refresh-contents)) (unless (package-installed-p 'devil) (package-install 'devil)) (global-devil-mode) (global-set-key (kbd "C-,") 'global-devil-mode) #+end_src Now type =, x , f= and watch Devil translate it to =C-x C-f= and invoke the corresponding command. Type =C-,= to disable Devil mode. Type =C-,= again to enable it. ** Install from Git Source :PROPERTIES: :CUSTOM_ID: install-from-git-source :END: If you prefer obtaining Devil from its Git repository, follow these steps: 1. Clone Devil to your system: #+begin_src shell git clone https://github.com/susam/devil.git #+end_src 2. Add the following to your Emacs initialization: #+begin_src elisp (add-to-list 'load-path "/path/to/devil/") (require 'devil) (global-devil-mode) (global-set-key (kbd "C-,") 'global-devil-mode) #+end_src 3. Start the Emacs editor. Devil mode should now be enabled in all buffers. The modeline of each buffer should show the =Devil= lighter. 4. Type =, x , f= and watch Devil translate it to =C-x C-f= and invoke the corresponding command. Type =C-,= to disable Devil mode. Type =C-,= again to enable it. * Use Devil :PROPERTIES: :CUSTOM_ID: use-devil :END: Assuming vanilla Emacs key bindings have not been changed and Devil has not been customised, here are some examples that demonstrate how Devil may be used: 1. Type =, x , f= and watch Devil translate it to =C-x C-f= and invoke the =find-file= command. 2. Type =, p= to move up one line. 3. To move up multiple lines, type =, p p p= and so on. Some Devil key sequences are repeatable keys by default. The repeatable Devil key sequences can be repeated by typing the last key of the Devil key sequence over and over again. 4. Each repeatable key sequence belongs to a repeatable key sequence groups. Like before, type =, p p p= to move the cursor up by a few lines. But then immediately type =n n= to move the cursor down by a couple of lines. Then immediately type =p n b f= to move the cursor up, down, left, and right. The key sequences =, p= and =, n= and =, f= and =, b= form a single repeatable key sequence group. Therefore after we type any one of them, we can repeat that key sequence or any other key sequence in the same group over and over again merely by typing the last character of that key sequence. Typing any other key stops the repetition and the default behaviour of that other key is then observed. Type =C-h v devil-repeatable-keys RET= to see the complete list of all repeatable key sequence groups. 5. Sometimes a repeatable key sequence may be the only key sequence in a repeatable key sequence group. An example of such a key sequence is =, m ^= which translates to =M-^= and joins the current line to the previous line. In a text buffer with multiple lines type =, m ^= to join the current line to the previous line. Then type =^= repeatedly to continue joining lines. Typing any other key stops the repetition. 6. Type =, s= and watch Devil translate it to =C-s= and invoke incremental search. 7. Type =, m x= and watch Devil translate it to =M-x= and invoke the corresponding command. Yes, =, m= is translated to =M-=. 8. Type =, m m s= and watch Devil translate it to =C-M-s= and invoke regular-expression-based incremental search. The key sequence =, m m= is translated to =C-M-=. 9. Type =, u , f= and watch Devil translate it to =C-u C-f= and move the cursor forward by 4 characters. 10. Type =, u u , f= and the cursor moves forward by 16 characters. Devil uses its translation rules and an additional keymap to make this input key sequence behave like =C-u C-u C-f= which moves the cursor forward by 16 characters. 11. Type =, SPC= to type a comma followed by space. This is a special key sequence to make it convenient to type a comma in the text. Note that this sacrifices the use of =, SPC= to mean =C-SPC= which could have been a convenient way to set a mark. See the section [[*Reclaim , SPC to Set Mark]] if you do not want to make this sacrifice. 12. Type =, z SPC= and watch Devil translate it to =C-SPC= and set a mark. Yes, =, z= is translated to =C-= too. 13. Similarly, type =, RET= to type a comma followed by the =enter= key. This is another special key. 14. Type =, ,= to type a single comma. This special key is useful for cases when you really need to type a single literal comma. 15. Type =, h , k= to invoke =devil-describe-key=. This is a special key that invokes the Devil variant of =describe-key= included in vanilla Emacs. When the key input prompt appears, type the Devil key sequence =, x , f= and Devil will display the documentation of the function invoked by this Devil key sequence. Note: The key sequence =, h k= translates to =C-h k= and invokes the vanilla =describe-key=. It is the Devil key sequence =, h , k= that invokes =devil-describe-key=. * Typing Commas :PROPERTIES: :CUSTOM_ID: typing-commas :END: Devil makes the questionable choice of using the comma as its activation key. As illustrated in the previous section, typing =, x , f= produces the same effect as typing =C-x C-f=. One might naturally wonder how then we are supposed to type literal commas. Most often when we edit text, we do not really type a comma in isolation. Often we immediately follow the comma with a space or a newline. This assumption usually holds good while editing regular text. However, this assumption may not hold in some situations, like while working with code when we need to add a single comma at the end of an existing line. In scenarios where the above assumption holds good, typing =, SPC= inserts a comma and a space. Similarly, typing =, RET= inserts a comma and a newline. In scenarios where we do need to type a single comma, type =, ,= instead. Note that you could also type a single comma with =, q ,= which translates to =C-q ,= and inserts a literal comma. The Emacs key sequence =C-q= invokes the command =quoted-insert= which inserts the next input character. The =, ,= special key sequence is probably easier to type than this. Also, it is worth mentioning here that if all this fiddling with the comma key feels clumsy, we could always customise the Devil key to something else that feels better. We could also disable Devil mode temporarily and enable it again later with =C-,= as explained in section [[*Install]]. * Devil Reader :PROPERTIES: :CUSTOM_ID: devil-reader :END: The following points briefly describe how Devil reads Devil key sequences, translates them to Emacs key sequences, and runs commands bound to the key sequences: 1. As soon as the Devil key is typed (which is =,= by default), Devil wakes up and starts reading Devil key sequences. Type =C-h v devil-key RET= to see the current Devil key. 2. After each keystroke is read, Devil checks if the key sequence accumulated is a special key. If it is, then the special command bound to the special key is executed immediately. Note that this step is performed before any translation rules are applied to the input key sequence. This is how the Devil special key sequence =, SPC= inserts a comma and a space. Type =C-h v devil-special-keys RET= to see the list of special keys and the commands bound to them. 3. If the key sequence accumulated so far is not a special key, then Devil translates the Devil key sequence to a regular Emacs key sequence. If the regular Emacs key sequence turns out to be a complete key sequence and some command is found to be bound to it, then that command is executed immediately. This is how the Devil key sequence =, x , f= is translated to =C-x C-f= and the corresponding binding is executed. If the translated key sequence is a complete key sequence but no command is bound to it, then Devil displays a message that the key sequence is undefined. Type =C-h v devil-translations RET= to see the list of translation rules. 4. After successfully translating a Devil key sequence to an Emacs key sequence and executing the command bound to it, Devil checks if the key sequence is a repeatable key sequence. If it is found to be a repeatable key sequence, then Devil sets a transient map so that the repeatable key sequences that belong to the same group as the typed Devil key sequence can be invoked merely by typing the last character of the input key sequence. This is how =, p p p f f= moves the cursor up by three lines and then by two characters forward. Type =C-h v devil-repeatable-keys RET= to see the list of repeatable Devil key sequences. The variables =devil-special-keys=, =devil-translations=, and =devil-repeatable-keys= may contain keys or values with the string =%k= in them. This is a placeholder for =devil-key=. While applying the special keys, translation rules, or repeat rules, each =%k= is replaced with the actual value of =devil-key= before applying the rules. * Translation Mechanism :PROPERTIES: :CUSTOM_ID: translation-mechanism :END: The following points provide an account of the translation mechanism that Devil uses in order to convert a Devil key sequence entered by the user to an Emacs key sequence: 1. The input key vector read from the user is converted to a key description (like the string produced by functions like =describe-key= and =key-description=). For example, if the user types =,x,f= it is converted to =, x , f=. 2. Now the resulting key description is translated with simple string replacements. If any part of the string matches a key in =devil-translations=, then it is replaced with the corresponding value. For example, =, x , f= is translated to =C- x C- f=. Then Devil normalises the result to =C-x C-f= by removing the stray spaces after the modifier keys. 3. If the simple string based replacement discussed in the previous point leads to an invalid Emacs key sequence, it skips the replacement that causes the resulting Emacs key sequence to become invalid. For example =, m m ,= results in =C-M-C-= after the simple string replacement because the default translation rules replace the leading =, m m= with =C-M-= and the trailing =,= with =C-=. However, =C-M-C-= is an invalid key sequence, so the replacement of the trailing =,= to =C-= is skipped. Therefore, the input =, m m ,= is translated to =C-M-,= instead. 4. Finally, Devil looks for key chords in the key sequence that contain both the =C-= modifier and an uppercase letter. If such a key chord occurs, then it replaces the uppercase letter with its shifted form, e.g., =, m m V= first translates to =C-M-V= according to the previous points and then the result is translated to =C-M-S-v= according to this point. * Default Translation Rules :PROPERTIES: :CUSTOM_ID: default-translation-rules :END: By default, Devil supports a small but peculiar set of translation rules that can be used to avoid modifier keys while typing various types of key sequences. See =C-h v devil-translations RET= for the translation rules. Here are some examples that demonstrate the default translation rules. The obvious ones are shown first. The more peculiar translations come later in the table. The concluding paragraph of this subsection offers a guide on how to gradually and gently adopt these key sequences into your daily routine. | Input | Translated | Remarks | |-----------+------------+-------------------------------------------| | =, s= | =C-s= | Rule 1: =,= is replaced with =C-= | | =, m x= | =M-x= | Rule 2: =, m= is replaced with =M-= | | =, [ x= | =C-[ x= | equivalent to =M-x= | | =, m m s= | =C-M-s= | Rule 3: =, m m= is replaced with =C-M-= | | =, m ,= | =M-,= | Rule 4: =, m ,= is replaced with =M-,= | | =, m z m= | =M-m= | Rule 5: =, m z= is replaced with =M-= too | | =, c , ,= | =C-c ,= | Rule 6: =, ,= is replaced with =,= | | =, z SPC= | =C-SPC= | Rule 7: =, z= is replaced with =C-= too | | =, z z= | =C-z= | ditto | | =, z ,= | =C-,= | ditto | Note how we cannot use =, SPC= to set a mark because that key sequence is already reserved as a special key sequence in =devil-special-keys=. In order to conveniently set a mark, Devil translates =, z= to =C-= too, so that we can type =, z SPC= and have Devil translate it to =C-SPC=. Also, note that while =, m= may be used to type =M-= we have =, [= as yet another way to type a key sequence that contains =M-= because =, [= translates to =C-[= and =C-[ = is equivalent to =ESC = which in turn is equivalent to =M-=. The default translation examples presented in the table above look weirder and weirder as we go down the table. But they are not as arbitrary as they might initially appear to be. They are arranged in such a way that overall, we get the following effect: - Devil translates the input =,= to =C-=. Similarly it translates =, m= to =M-= and =, m m= to =C-M-=. - When we really want to type the Devil key =,= we need to double type it in the Devil key sequence. Doubling the special character serves as an escape mechanism to avoid the special meaning of the Devil key and get its literal form instead. - Now since =, ,= translates to =,= we need another escape mechanism to type =C-,=. Typing =z= in between serves as this escape mechanism, i.e., within a Devil key sequence =, z ,= translates to =C-,=. - Similarly since =, m m= translates to =C-M-= we need an escape mechanism to type =M-m=. Again, typing =z= in between serves as this escape mechanism, i.e., =, m z m= translates to =M-m=. Here is a gentle guide to adopting these key sequences: For beginners using Devil, it is not necessary to memorise all of them right away. Understanding that =,= translates to =C-= and =, m= translates to =M-= is sufficient to begin. Subsequently, learning that =, m m= translates to =C-M-= unlocks several more key sequences like =, m m s= (=C-M-s=), =, m m f= (=C-M-f=), etc. As you encounter more key sequences that are not covered by these initial rules, revisit the above table to pick up new translation rules and adopt them in your day-to-day usage of Devil. * Describe Devil Key :PROPERTIES: :CUSTOM_ID: devil-describe-key :END: Devil offers a command named =devil-describe-key= that can be used to describe a Devil key sequence. It works similarly to the =describe-key= command of vanilla Emacs that can be invoked with =C-h k=. The =devil-describe-key= command can be invoked with the special key sequence =, h , k=. Type =, h , k= and a prompt appears to read a key sequence. Type any Devil key sequence, say, =, x , f= and Devil immediately shows the documentation for the function invoked by this key sequence. Note that =, x , f= (=devil-describe-key=) can also be used to look up documentation for vanilla Emacs key sequences like =C-x C-f=. Also note that the Devil key sequence is =, h k= is still free to invoke =C-h k= (=describe-key= of vanilla Emacs). * Bonus Key Bindings :PROPERTIES: :CUSTOM_ID: bonus-key-bindings :END: Devil adds the following additional key bindings only when Devil is enabled globally with =global-devil-mode=: - Adds the Devil key to =isearch-mode-map=, so that Devil key sequences work in incremental search too. - Adds =u= to =universal-argument-more= to allow repeating the universal argument command =C-u= simply by repeating =u=. As mentioned before these features are available only when Devil is enabled globally with =global-devil-mode=. If Devil is enabled locally with =devil-mode=, then these features are not available. * Custom Configuration Examples :PROPERTIES: :CUSTOM_ID: custom-configuration-examples :END: In the examples presented below, the =(require 'devil)= calls may be omitted if Devil has been installed from a package archive like ELPA or MELPA. There are appropriate autoloads in place in the Devil package that would ensure that it is loaded automatically on enabling Devil mode. However, the =require= calls have been included in the examples below for the sake of completeness. ** Local Mode :PROPERTIES: :CUSTOM_ID: local-mode :END: While the section [[*Install]] shows how we enable Devil mode globally, this section shows how we can enable it locally. Here is an example initialization code that enables Devil locally only in text buffers. #+begin_src elisp (require 'devil) (add-hook 'text-mode-hook 'devil-mode) (global-set-key (kbd "C-,") 'devil-mode) #+end_src This is not recommended though because this does not provide a seamless Devil experience. For example, with Devil enabled locally in a text buffer like this, although we can type =, x , f= to launch the =find-file= minibuffer, we cannot use Devil key sequences in the minibuffer. Further the special keymaps described in the previous section work only when Devil is enabled globally. ** Mode as a buffer default :PROPERTIES: :CUSTOM_ID: buffer-default :END: While enabling =global-devil-mode= is typically enough for using Devil in every buffer the user encounters, buffer creation which bypasses the traditional setup hooks will not have the mode enabled by default. The most likely place to encounter this problem is with the default Emacs startup screen, which is created after the user's init file has been processed but does not run any hooks which will enable Devil. To solve this particular problem it is recommended to either customise the startup screen to one which does run the required hooks, or to advise the =display-startup-screen= function to enable Devil in the buffer once created. Here is an example of enabling =global-devil-mode= and ensuring it is activated in the default Emacs startup screen. #+begin_src elisp (require 'devil) (global-devil-mode) (advice-add 'display-startup-screen :after (lambda (&optional _) (devil-mode 1))) #+end_src This solves the problem most likely to be encountered. But what if you do genuinely need Devil active in *every* buffer? When =devil-global-sets-buffer-default= is set to =t= and =global-minor-mode= is called, Devil will be enabled in all new buffers by default. Enabling this functionality may seem appealing, but consider that not all buffers are intended to be interacted with, and the decision to opt-out of hooks which could apply a minor-mode is likely to have been intentional. Even though it is not recommended, the following example demonstrates how to have Devil active in all buffers by default. #+begin_src elisp (require 'devil) (setq devil-global-sets-buffer-default t) (global-devil-mode) #+end_src ** Custom Appearance :PROPERTIES: :CUSTOM_ID: custom-appearance :END: The following initialization code shows how we can customise Devil to show a Devil smiley (😈) in the modeline and in the Devil prompt. #+begin_src elisp (require 'devil) (setq devil-lighter " \U0001F608") (setq devil-prompt "\U0001F608 %t") (global-devil-mode) (global-set-key (kbd "C-,") 'global-devil-mode) #+end_src ** Reclaim , SPC to Set Mark :PROPERTIES: :CUSTOM_ID: reclaim-comma-space-to-set-mark :END: The default configuration for special keys reserves =, SPC= to insert a literal comma followed by space. This default makes it easy to type comma in various contexts. However, this means that =, SPC= does not translate to =C-SPC=. Therefore =, SPC= cannot be used to set mark. Instead, the default translation rules offer =, z SPC= as a way to set mark. If you would rather set mark using =, SPC= and you are happy with typing the special key =, ,= to insert a literal comma, then use the following configuration: #+begin_src elisp (require 'devil) (global-devil-mode) (global-set-key (kbd "C-,") 'global-devil-mode) (assoc-delete-all "%k SPC" devil-special-keys) #+end_src This removes the special key =, SPC= from =devil-special-keys= so that it is now free to be translated to =C-SPC= and invoke =set-mark-command=. ** Custom Devil Key :PROPERTIES: :CUSTOM_ID: custom-devil-key :END: The following initialization code shows how we can customise Devil to use a different Devil key. #+begin_src elisp (require 'devil) (global-devil-mode) (global-set-key (kbd "C-;") 'global-devil-mode) (devil-set-key (kbd ";")) #+end_src The above example sets the Devil key to the semicolon, perhaps another dubious choice for the Devil key. With this configuration, we can use =; x ; f= and have Devil translate it to =C-x C-f=. ** Yet Another Custom Devil Key :PROPERTIES: :CUSTOM_ID: yet-another-custom-devil-key :END: The following initialization code shows how we can customise Devil to use yet another different Devil key. #+begin_src elisp (require 'devil) (global-devil-mode) (global-set-key (kbd "C-") 'global-devil-mode) (devil-set-key (kbd "")) (dolist (key '("%k SPC" "%k RET" "%k ")) (assoc-delete-all key devil-special-keys)) #+end_src The above example sets the Devil key to the left arrow key. With this configuration, we can use = x f= and have Devil translate it to =C-x C-f=. We can type the special key = = to produce the same effect as the original ==. The above example removes some special keys that are no longer useful. In particular, = SPC= is no longer reserved as a special key, so we can use it now to set a mark. ** Multiple Devil Keys :PROPERTIES: :CUSTOM_ID: multiple-devil-keys :END: While this package provides the comma (=,=) as the default and the only Devil key, nothing stops you from extending the mode map to support multiple Devil keys. Say, you decide that in addition to activating Devil with =,= which also plays the role of =C-=, you also want to activate Devil with =.= which must now play the role of =M-=. To achieve such a result, you could use this initialization code as a starting point and then customise it further based on your requirements: #+begin_src elisp (require 'devil) (global-devil-mode) (define-key devil-mode-map (kbd ".") #'devil) (add-to-list 'devil-special-keys `(". ." . ,(devil-key-executor "."))) (setq devil-translations '((", z" . "C-") (". z" . "M-") (", ," . ",") (". ." . ".") ("," . "C-") ("." . "M-"))) #+end_src With this configuration, we can type =, x , f= for =C-x C-f= like before. But now we can also type =. x= for =M-x=. Similarly, we can type =, . s= for =C-M-s= and so on. Also =, ,= inserts a literal comma and =. .= inserts a literal dot. Further we can type =, z ,= to get =C-,= and =. z .= to get =M-.=. Note that by default Devil configures only one activation key (=,=) because the more activation keys we add, the more intrusive Devil becomes during regular editing tasks. Every key that we reserve for activating Devil loses its default function and then we need workarounds to somehow invoke the default function associated with that key (like repeating =.= twice to insert a single =.= in the above example). Therefore, it is a good idea to keep the number of Devil keys as small as possible. ** Make All Keys Repeatable :PROPERTIES: :CUSTOM_ID: make-all-keys-repeatable :END: By default Devil has a small list of key sequences that are considered repeatable. This list is defined in the variable =devil-repeatable-keys=. Type =C-h v devil-repeatable-keys RET= to view this list. For example, consider the repeatable key sequence group =("%k p" "%k n" "%k f" "%k b")= in this list. Assuming that the default Devil and Emacs key bindings have not been changed, this means that after we type =, p= and move the cursor to the previous line, we can repeat this operation by typing =p= over and again. We can also immediately type =f= to move the cursor right by one character. The repetition occurs as long as the last character of any repeatable key sequence in the group is typed again. Typing any other key stops the repetition and the default behaviour of the other key is then observed. It is possible to make all key sequences repeatable by setting the variable =devil-all-keys-repeatable= to =t=. Here is an example configuration: #+begin_src elisp (require 'devil) (setq devil-all-keys-repeatable t) (global-devil-mode) #+end_src With this configuration, the repeatable key sequence groups still function as described above. However, in addition to that now all other Devil key sequences that end up executing Emacs commands also become repeatable, i.e., any Devil key sequence that does not belong to =devil-all-keys-repeatable= but invokes an Emacs command is now repeatable and it can be repeated by merely repeating the last character of the key sequence. Note that only Devil key sequences that get translated to a regular Emacs key sequence and result in the execution of an Emacs command can be repeatable. The special keys defined in =devil-special-keys= are never repeatable. ** Interaction with Repeat Mode :PROPERTIES: :CUSTOM_ID: interaction-with-repeat-mode :END: Repeatable keys in Devil function somewhat like =repeat-mode= introduced in Emacs 28.1. Here is an example configuration that disables repeatable keys in Devil and shows how to use =repeat-mode= instead to define repeatable commands. #+begin_src elisp (require 'devil) (global-devil-mode) (setq devil-repeatable-keys nil) (defvar movement-repeat-map (let ((map (make-sparse-keymap))) (define-key map (kbd "p") #'previous-line) (define-key map (kbd "n") #'next-line) (define-key map (kbd "b") #'backward-char) (define-key map (kbd "f") #'forward-char) map)) (dolist (cmd '(previous-line next-line backward-char forward-char)) (put cmd 'repeat-map 'movement-repeat-map)) (repeat-mode) #+end_src Now if we type =C-p= to move the cursor up by one line, we can repeat it by merely typing =p= again and we can also type or repeat =n=, =b=, or =f=, to move the cursor down, left, or right respectively. Repeat mode works fine with Devil too, so with the above configuration, when we type =, p= to move the cursor to the previous line, we can type or repeat =p=, =n=, =b=, or =f= to move the cursor up, down, left, or right again. We do not really need to disable Devil's repeatable keys while using repeat mode. Both can be enabled together. However, the results can be surprising due to certain differences between the two. For example, consider the following configuration: #+begin_src elisp (require 'devil) (global-devil-mode) (defvar movement-repeat-map (let ((map (make-sparse-keymap))) (define-key map (kbd "p") #'previous-line) (define-key map (kbd "n") #'next-line) map)) (dolist (cmd '(previous-line next-line)) (put cmd 'repeat-map 'movement-repeat-map)) (repeat-mode) #+end_src Now both Devil repeatable keys and repeat mode are active. If we now type =, p= we can repeat =p= and =n= to move the cursor up and down. Repeat mode makes this repetition possible. Additionally, after typing =, p= we can also type or repeat =b= and =f= to move the cursor left and right. Devil makes this repetition possible. We can tell the difference between repeat mode handling repeatable commands and Devil mode handling repeatable keys by looking at the echo area. When we repeat =p= which is handled by repeat mode, we see a message "Repeat with p, n" in the echo area. But when we repeat =b= which is handled by Devil, we see no such message; Devil sets up repeatable keys silently. ** Comparison with Repeat Mode :PROPERTIES: :CUSTOM_ID: comparison-with-repeat-mode :END: The previous section demonstrates how much of what Devil accomplishes with its support for repeatable key sequences can also be accomplished with =repeat-mode= that comes out of the box in Emacs 28.1 and later versions. However, there is a crucial difference between Devil's repeatable keys and =repeat-mode=. Repeat mode provides repeatable /commands/ but Devil supports repeatable /keys/. This different is crucial and arguably makes repeatable key sequences easier to configure in Devil. To demonstrate the difference, let us consider the key sequence =M-e=. The command =forward-sentence= is bound to it by default in the global map. However, in Org mode, the command =org-forward-sentence= is bound to it. The corresponding Devil key sequence is =, m e= and this is a repeatable key sequence in Devil. Therefore, we can type =, m e= followed by =e e e= and so on to move the cursor forward by multiple sentences in text mode as well as in Org mode. To emulate the same behaviour using repeat mode, we need a configuration like this: #+begin_src elisp (require 'devil) (global-devil-mode) (setq devil-repeatable-keys nil) (defvar forward-sentence-repeat-map (let ((map (make-sparse-keymap))) (define-key map (kbd "e") #'forward-sentence) map)) (defvar org-forward-sentence-repeat-map (let ((map (make-sparse-keymap))) (define-key map (kbd "e") #'org-forward-sentence) map)) (put #'forward-sentence 'repeat-map 'forward-sentence-repeat-map) (put #'org-forward-sentence 'repeat-map 'org-forward-sentence-repeat-map) (repeat-mode) #+end_src Note how we need to configure repeat mode for both commands that are bound to =M-e=. With the above configuration, we can now type =, m e= followed by =e e e= to move forward by multiple sentences in both text mode as well as Org mode. However, we can never be sure if we missed configuring repeat mode for some other command that might be bound to =M-e= in some mode. For example, in C mode, the command =c-end-of-statement= is bound to =M-e=. The above configuration is no good for repeating this command by typing =e e e=. Devil, however, can repeat the command bound to =M-e= in any mode. Devil does not merely make the command bound to it in a particular mode repeatable. Instead Devil makes the key sequence =, m e= itself repeatable. Therefore, with Devil's own support for repeatable key sequences, we can type =, m e= and then =e e e= to repeat the command bound to =M-e= regardless of which mode is active or which command is bound to this key sequence. * Why? :PROPERTIES: :CUSTOM_ID: why :END: Why go to the trouble of creating and using something like this? Why not just remap =caps lock= to =ctrl= like every other sane person does? Or if it is so important to avoid modifier keys, why not use something like God mode or Evil mode? Well, for one, both God mode and Evil mode are modal editing modes. Devil, on the other hand, retains the non-modal editing experience of Emacs. Devil mode began as a fun little experiment. From the outset, it was clear that using something as crucial as the comma for specifying the modifier key is asking for trouble. However, I still wanted to see how far I could go with it. It turned out that in a matter of days, I was using it full-time for all of my Emacs usage. This experiment was partly motivated by Macbook keyboards which do not have a =ctrl= key on the right side of the keyboard. Being a touch-typist myself, I found it inconvenient to type key combinations like =C-x=, =C-s=, =C-r=, =C-d=, =C-f=, =C-w=, =C-a=, =C-e=, etc. where both the modifier key and the modified key need to be pressed with the left hand fingers. I am not particularly fond of remapping =caps lock= to behave like =ctrl= because that still suffers from the problem that key combinations like =C-x=, =C-a= require pressing both the modifier key and the modified key with the left hand fingers. I know many people remap both their =caps lock= and =enter= to behave like =ctrl=. While I think that is a fine solution, I was not willing to put up with the work required to make that work seamlessly across all the various operating systems I work on. What began as a tiny whimsical experiment a few years ago turned out to be quite effective, at least to me. I like that this solution is implemented purely as Elisp and therefore does not have any external dependency. I am sharing this solution in the form of a minor mode, just in case, there is someone out there who might find this useful too. * Comparison with God Mode :PROPERTIES: :CUSTOM_ID: comparison-with-god-mode :END: God mode provides a modal editing experience but Devil does not. Devil has the same underlying philosophy as that of God mode, i.e., the user should not have to learn new key bindings. However, Devil does not have a hard separation between insert mode and command mode like God mode has. Instead, Devil waits for an activation key (=,= by default) and as soon as it is activated, it intercepts and translates keys, runs the corresponding command, and then gets out of the way. So Devil tries to retain the non-modal editing experience of vanilla Emacs. Now it is worth mentioning that some of this non-modal editing experience can be reproduced in god-mode too using its =god-execute-with-current-bindings= function. Here is an example: #+begin_src elisp (global-set-key (kbd ",") #'god-execute-with-current-bindings) #+end_src With this configuration, God mode translates =, x f= to =C-x C-f=. Similarly =, g x= invokes =M-x= and =, G s= invokes =C-M-x=. This provides a non-modal editing experience in God mode too. However, this experience does not extend seamlessly to minibuffers. Devil does extend its Devil key translation to minibuffers. Further note that in God mode the =ctrl= modifier has sticky behaviour, i.e., the modifier remains active automatically for the entire key sequence. Therefore in the above example, we type =,= only once while typing =, x f= to invoke =C-x C-f=. However, this sticky behaviour implies that we need some way to disambiguate between key sequences like =C-x C-f= (=find-file=) and =C-x f= (=set-fill-column=). God mode solves this by introducing =SPC= to deactivate the modifier, e.g., =, x f= translates to =C-x C-f= but =, x SPC f= translates to =C-x f=. Devil does not treat the modifier key as sticky which leads to simpler key sequences at the cost of a little additional typing, i.e., =, x , f= translates to =C-x C-f= and =, x f= translates to =C-x f=. To summarize, there are primarily four things that Devil does differently: - Provide a non-modal editing experience from the outset. - Seamlessly extend the same editing experience to minibuffer, incremental search, etc. - Translate key sequences using string replacements. This allows for arbitrary and sophisticated key translations for the adventurous. - Choose non-sticky behaviour for the modifier keys. These differences could make Devil easier to use than God mode for some people but clumsy for other people. It depends on one's tastes and preferences. * Frequently Asked Questions :PROPERTIES: :CUSTOM_ID: frequently-asked-questions :END: 01. Why was the comma (=,=) chosen as the default Devil key? Isn't the semicolon (=;=) a better choice since it belongs to the home row? Opinions vary. As the author and maintainer of this minor mode, I made a choice to use the comma as the default Devil key. Although, the semicolon belongs to the home row on most keyboards and the comma does not, I find the vertical movement to reach the comma key with the long finger more convenient than the horizontal movement necessary to reach the semicolon with the little finger. As a touch typist, my fingers rest on the eight home row keys when idle. The horizontal movement necessary to type the semicolon leads to a significant angular movement of the wrist. Curling my long finger to reach the comma key helps me avoid this wrist strain. If you do not like this default, it is quite easy to customise the Devil key to be the semicolon or any other key of your choice. See the section [[*Custom Devil Key]] and the subsequent sections to learn how to do this. 02. I am happy with typing =, ,= every time, I need to type a comma. Can I free up =, SPC= to invoke =set-mark-command=? Yes, this can be done by removing the special key =, SPC= from =devil-special-keys=. See the section [[*Reclaim , SPC to Set Mark]] to find out how to do this. 03. Can I make the Devil key sticky, i.e., can I type =, x f= instead of =, x , f= to invoke =C-x C-f=? Devil does not support sticky keys. Say, Devil were to translate =, x f= to =C-x C-f=, how would we invoke =C-x f= then? We need some way to disambiguate between =C-x C-f= and =C-x f=. Different tools take different approaches to disambiguate the two key sequences. God-mode translates =x f= to =C-x C-f= and =x SPC f= to =C-x f=, i.e., God-mode treats the =C-= modifier as sticky by default but when we want to make it non-sticky, we need to type =SPC= in god-mode. This makes some key sequences like =C-x C-f= shorter to type but some other key sequences like =C-x f= longer to type. Devil treats the Devil key as non-sticky, so that there is no need for additional peculiar rules to switch between sticky and non-sticky behaviour to disambiguate key sequences like =C-x C-f= and =C-x f=. With Devil =, x , f= translates to =C-x C-f= and similarly =, x f= translates to =C-x f=. The translation rules are simpler at the cost of a little additional typing in some cases. In most such cases, Devil requires typing an additional comma that one could have avoided if the comma were sticky. However, in other cases, Devil eliminates the need to type an extra key to make the modifier key non-sticky. 04. Are there some things that are easier to do with Devil than god-mode? Devil is not necessarily easier than god-mode. It is different. Preferences vary, so some may find Devil easier to use while some others may find god-mode easier to use. See the section [[*Comparison with God Mode]] for more details on the differences between the two modes. 05. I've called the function =global-devil-mode= in my config file, but when Emacs opens Devil does not seem to active. Why isn't it working? The most likely issue is that the first buffer shown is the default Emacs startup screen, which is created without running any hooks which would give Devil the opportunity to be applied. See the section [[*Mode as a buffer default]] for further details and possible solutions. * Conclusion :PROPERTIES: :CUSTOM_ID: conclusion :END: Devil is a minor mode to translate key sequences. Devil utilises this translation capability to provide a modifier-free editing experience and it does so without resorting to modal-editing. Devil retains the non-modal editing of vanilla Emacs. This mode was written as a quirky experiment to make it easier to use Emacs without modifier keys. However, the resulting mode turned out to be quite convenient to use, in general. You might find Devil comfortable. Or you might find Devil to be a terrible idea. It is also possible that you might find Devil useful but intrusive. In such cases, there are plenty of customisable options that you can modify to configure Devil according to your preferences. If you need any help or if you find any issues, please create an issue at [[https://github.com/susam/devil/issues]]. ================================================ FILE: Makefile ================================================ checks: tests test-sentence-ends test-sentence-ends: grep -n '[^0-9][.?=)] [A-Z]' *.org *.el; [ $$? = 1 ] tests: emacs --batch -l devil.el -l devil-tests.el -f ert-run-tests-batch-and-exit ================================================ FILE: README.org ================================================ * Devil Mode [[https://melpa.org/#/devil][file:https://melpa.org/packages/devil-badge.svg]] [[https://stable.melpa.org/#/devil][file:https://stable.melpa.org/packages/devil-badge.svg]] [[https://elpa.nongnu.org/nongnu/devil.html][file:https://elpa.nongnu.org/nongnu/devil.svg]] [[https://mastodon.social/@susam][file:https://img.shields.io/badge/mastodon-%40susam-%2355f.svg]] Devil mode trades your comma key in exchange for a modifier-free editing experience in Emacs. Yes, the comma key! The key you would normally wield for punctuation in nearly every corner of text. Yes, this is twisted! It would not be called the Devil otherwise, would it? If it were any more rational, we might call it something divine, like, uh, the God mode? But alas, there is nothing divine to be found here. Welcome, instead, to the realm of the Devil! You will be granted the occasional use of the comma key for punctuation, but only if you can charm the Devil. But beware, for in this sinister domain, you must relinquish your comma key and embrace an editing experience that whispers wicked secrets into your fingertips! ** Introduction :PROPERTIES: :CUSTOM_ID: introduction :END: Devil is available in MELPA as well as NonGNU ELPA. If you are using Emacs 28.1 or a more recent version of Emacs, you can get the latest stable version of Devil by typing =M-x package-install RET devil RET=. Otherwise, you need to add MELPA or NonGNU ELPA to your list of package archives and then install MELPA. More details on the installation procedure is provided in the [[https://susam.github.io/devil/][manual]]. By default, Devil mode rebinds the comma key to activate Devil. Once activated, Devil reads a so-called Devil key sequence from you. As you type your Devil key sequence, Devil translates the key sequence to a regular Emacs key sequence. If any command is bound to the translated Emacs key sequence, Devil runs that command and then deactivates itself. By default, each comma in the Devil key sequence is translated to "C-". For example, if you type ", x , f", Devil translates it to "C-x C-f". Similarly ", m" is translated to "M-". If you type ", m x", Devil translates it to "M-x". Further ", m m" is translated to "C-M-". If you type ", m m f" Devil translates it to "C-M-f". There are several other translations available in the default translation rules that let you enjoy working with Emacs while avoiding modifier keys. Further, the Devil activation key, translation rules, etc. are customisable. Thus if you do not like the default choices made in this package, you can customise it easily to suit your preferences. Read the [[https://susam.github.io/devil/][manual]] to learn how to install, use, and customise Devil. ** Channels :PROPERTIES: :CUSTOM_ID: channels :END: The author of this project hangs out at the following places online: - Website: [[https://susam.net][susam.net]] - Mastodon: [[https://mastodon.social/@susam][@susam@mastodon.social]] - GitHub: [[https://github.com/susam][@susam]] You are welcome to subscribe to, follow, or join one or more of the above channels to receive updates from the author or ask questions about this project. ** Support :PROPERTIES: :CUSTOM_ID: support :END: To report bugs, suggest improvements, or ask questions, [[https://github.com/susam/devil/issues][create issues]]. ** Contributing :PROPERTIES: :CUSTOM_ID: contributing :END: See [[https://github.com/susam/devil/blob/main/CONTRIBUTING.org][CONTRIBUTING.org]] for contribution guidelines. ** Thanks :PROPERTIES: :CUSTOM_ID: thanks :END: Thanks to: - [[https://github.com/riscy][Chris Rayner]] for initial code review. - [[https://github.com/phikal][Philip Kaludercic]] for initial code review and patches. - [[https://github.com/morganwillcock][Morgan Willcock]] for initial feedback and code reviews. ** Reactions :PROPERTIES: :CUSTOM_ID: reactions :END: Some amusing reactions to this project collected from various corners of the world wide web: #+begin_quote Every bit of this horrifies me, and I can't believe you've done it. Outstanding. Well done! -- [[https://news.ycombinator.com/item?id=35953341][@kstrauser]] #+end_quote #+begin_quote This is insane. I am going to try it immediately. -- [[https://news.ycombinator.com/item?id=35855621][@jrockway]] #+end_quote #+begin_quote Will defiantly check this out. -- [[https://old.reddit.com/r/emacs/comments/13aj99j/devil_mode_a_twisted_key_sequence_translator_for/jj94y35/][@strings]] #+end_quote #+begin_quote Defiantly! -- [[https://old.reddit.com/r/emacs/comments/13aj99j/devil_mode_a_twisted_key_sequence_translator_for/jj98owf/][@oantolin]] #+end_quote #+begin_quote 😈 -- [[https://old.reddit.com/r/emacs/comments/13aj99j/devil_mode_a_twisted_key_sequence_translator_for/jj72ive/][@SequentialDesign]] #+end_quote ** More :PROPERTIES: :CUSTOM_ID: more :END: See [[https://github.com/susam/emacs4cl][Emacs4CL]], a DIY quick-starter kit to set up Emacs for Common Lisp programming. See [[https://github.com/susam/emfy][Emfy]], a DIY quick-starter kit to set up Emacs for general purpose editing and programming. ================================================ FILE: devil-tests.el ================================================ ;;; devil-tests.el --- Tests for devil -*- lexical-binding: t; -*- ;;; Commentary: ;; Unit tests for the internal devil logic. Run these with M-x ert ;; RET devil- RET. ;;; Code: (require 'ert) (require 'devil) ;;; Customization ==================================================== (ert-deftest devil-log () "Test if `devil--log' works as expected." ;; When logging is disabled, message is not called. (unwind-protect (let ((devil-logging nil) (count 0)) (advice-add 'message :override (lambda (&rest args) (setq count (1+ count))) '((name . message-override))) (devil--log "foo") (should (= count 0))) (advice-remove 'message 'message-override)) ;; When logging is enabled, message is called. (unwind-protect (let ((devil-logging t) (count 0)) (advice-add 'message :override (lambda (&rest args) (setq count (1+ count))) '((name . message-override))) (devil--log "foo") (should (= count 1))) (advice-remove 'message 'message-override)) ;; When logging is disabled, logging arguments are not evaluated. (unwind-protect (let ((devil-logging nil) (count 0)) (advice-add 'message :override (lambda (&rest args)) '((name . message-override))) (devil--log (progn (setq count (1+ count)) "foo") (progn (setq count (1+ count))) (progn (setq count (1+ count)))) (should (= count 0))) (advice-remove 'message 'message-override)) ;; When logging is enabled, logging arguments are evaluated. (unwind-protect (let ((devil-logging t) (count 0)) (advice-add 'message :override (lambda (&rest args)) '((name . message-override))) (devil--log (progn (setq count (1+ count)) "foo") (progn (setq count (1+ count))) (progn (setq count (1+ count)))) (should (= count 3))) (advice-remove 'message 'message-override))) ;;; Command Lookup =================================================== (ert-deftest devil--incomplete-key-p () "Test if `devil--invalid-key-p' works as expected." (should (devil--incomplete-key-p "C-")) (should (devil--incomplete-key-p "C-x C-")) (should (devil--incomplete-key-p "C-M-S-")) (should (not (devil--incomplete-key-p ""))) (should (not (devil--incomplete-key-p "C-x-C-f"))) (should (not (devil--incomplete-key-p "C-x CC-f"))) (should (not (devil--incomplete-key-p "C-x C-f"))) (should (not (devil--incomplete-key-p "C-M-x")))) ;;; Key Translation ================================================== (ert-deftest devil--translate () "Test if `devil-translate' works as expected." ;; Trivial translations. (should (string= (devil--translate (vconcat "a")) "a")) (should (string= (devil--translate (vconcat "A")) "A")) ;; Translations involving the C- modifier. (should (string= (devil--translate (vconcat ",")) "C-")) (should (string= (devil--translate (vconcat ",x")) "C-x")) (should (string= (devil--translate (vconcat ",x,")) "C-x C-")) (should (string= (devil--translate (vconcat ",x,f")) "C-x C-f")) ;; Escape hatch to type commas. (should (string= (devil--translate (vconcat ",,")) ",")) (should (string= (devil--translate (vconcat ",,,,")) ", ,")) ;; Translations involving M- modifier. (should (string= (devil--translate (vconcat ",mx")) "M-x")) (should (string= (devil--translate (vconcat ",mmx")) "C-M-x")) (should (string= (devil--translate (vconcat ",m,x")) "M-, x")) (should (string= (devil--translate (vconcat ",mmm")) "C-M-m")) ;; Translations involing C- and uppercase letter. (should (string= (devil--translate (vconcat ",a")) "C-a")) (should (string= (devil--translate (vconcat ",A")) "C-S-a")) (should (string= (devil--translate (vconcat ",mA")) "M-A")) (should (string= (devil--translate (vconcat ",mmA")) "C-M-S-a")) (should (string= (devil--translate (vconcat ",A,mmA,a")) "C-S-a C-M-S-a C-a")) (should (string= (devil--translate (vconcat ",A,mA,mA,a")) "C-S-a M-A M-A C-a")) ;; Translations involving C- and RET. (should (string= (devil--translate (vconcat ",\r")) "C-RET")) (should (string= (devil--translate (vconcat ",m\r")) "M-RET")) (should (string= (devil--translate (vconcat ",mm\r")) "C-M-RET")) (should (string= (devil--translate (vconcat ",\r,R,m\r")) "C-RET C-S-r M-RET")) ;; Translations provided in the manual as examples. (should (string= (devil--translate (vconcat ",s")) "C-s")) (should (string= (devil--translate (vconcat ",mx")) "M-x")) (should (string= (devil--translate (vconcat ",mms")) "C-M-s")) (should (string= (devil--translate (vconcat ",m,")) "M-,")) (should (string= (devil--translate (vconcat ",mzm")) "M-m")) (should (string= (devil--translate (vconcat ",[x")) "C-[ x")) (should (string= (devil--translate (vconcat ",c,,")) "C-c ,")) (should (string= (devil--translate (vconcat ",z ")) "C-SPC")) (should (string= (devil--translate (vconcat ",zz")) "C-z")) (should (string= (devil--translate (vconcat ",z,")) "C-,"))) (ert-deftest devil--terminal-key () "Test if `devil--terminal-key' works as expected." (let ((local-function-key-map (make-sparse-keymap))) ;; Define bindings for fallback. (define-key local-function-key-map (kbd "") (kbd "TAB")) (define-key local-function-key-map (kbd "M-") (kbd "M-RET")) ;; Test translation (should (string= (devil--terminal-key "") "")) (should (string= (devil--terminal-key "a") "a")) (should (string= (devil--terminal-key "") "")) (should (string= (devil--terminal-key "C-") "C-")) (should (string= (devil--terminal-key "C-") "C-")) (should (string= (devil--terminal-key "") "TAB")) (should (string= (devil--terminal-key "M-") "M-RET")) (should (string= (devil--terminal-key "C- M-") "C- M-RET")))) (ert-deftest devil--shifted-key () "Test if `devil--shifted-key' works as expected." (should (string= (devil--shifted-key "A") "S-a")) (should (string= (devil--shifted-key "C-A") "C-S-a")) (should (string= (devil--shifted-key "C-M-A") "C-M-S-a")) (should (string= (devil--shifted-key "A ") "S-a ")) (should (string= (devil--shifted-key "C-A ") "C-S-a ")) (should (string= (devil--shifted-key "C-M-A ") "C-M-S-a "))) (ert-deftest devil--invalid-key-p () "Test if `devil--invalid-key-p' works as expected." (should (devil--invalid-key-p "")) (should (devil--invalid-key-p "C-x-C-f")) (should (devil--invalid-key-p "C-x CC-f")) (should (not (devil--invalid-key-p "C-x C-f"))) (should (not (devil--invalid-key-p "C-M-x")))) ;;; Utility Functions ================================================ (ert-deftest devil-format () "Test if `devil-format' works as expected." (let ((devil-key ",")) (should (string= (devil-format "%k") ",")) (should (string= (devil-format "Devil: %k") "Devil: ,")) (should (string= (devil-format "%k %%") ", %")) (should (string= (devil-format "%r => %t" (kbd ",")) ", => C-")) (should (string= (devil-format "%r => %t" (kbd ", x")) ", x => C-x"))) (let ((devil-key (kbd ""))) (should (string= (devil-format "%k") "")) (should (string= (devil-format "Devil: %k") "Devil: ")) (should (string= (devil-format "%k %%") " %")) (should (string= (devil-format "%r => %t" (kbd " x")) " x => C-x")) (should (string= (devil-format "%r => %t" (kbd " x ")) " x => C-x C-")))) (ert-deftest devil-string-replace () "Test if `devil-string-replace' works as expected." (should (string= (devil-string-replace "" "" "") "")) (should (string= (devil-string-replace "" "foo" "") "")) (should (string= (devil-string-replace "foo" "foo" "foo") "foo")) (should (string= (devil-string-replace "foo" "bar" "") "")) (should (string= (devil-string-replace "foo" "bar" "foo") "bar")) (should (string= (devil-string-replace "foo" "bar" "Foo") "Foo")) (should (string= (devil-string-replace "foo" "bar" "FOO") "FOO")) (should (string= (devil-string-replace "f.." "bar" "foo f..") "foo bar")) (should (string= (devil-string-replace "f.." "<\\&>" "foo f..") "foo <\\&>"))) (ert-deftest devil-regexp-replace () "Test if `devil-string-replace' works as expected." (should (string= (devil-regexp-replace "" "" "") "")) (should (string= (devil-regexp-replace "" "foo" "") "")) (should (string= (devil-regexp-replace "foo" "foo" "foo") "foo")) (should (string= (devil-regexp-replace "foo" "bar" "") "")) (should (string= (devil-regexp-replace "foo" "bar" "foo") "bar")) (should (string= (devil-regexp-replace "foo" "bar" "Foo") "Foo")) (should (string= (devil-regexp-replace "foo" "bar" "FOO") "FOO")) (should (string= (devil-regexp-replace "f.." "bar" "foo f..") "bar bar")) (should (string= (devil-regexp-replace "f.." "<\\&>" "foo f..") " "))) (provide 'devil-tests) ;;; devil-tests.el ends here ================================================ FILE: devil.el ================================================ ;;; devil.el --- Minor mode for translating key sequences -*- lexical-binding: t; -*- ;; Copyright (c) 2022-2023 Susam Pal ;; Author: Susam Pal ;; Maintainer: Susam Pal ;; Version: 0.7.0-beta3 ;; Package-Requires: ((emacs "24.4")) ;; Keywords: convenience, abbrev ;; URL: https://github.com/susam/devil ;; This file is not part of GNU Emacs. ;; Permission is hereby granted, free of charge, to any person ;; obtaining a copy of this software and associated documentation ;; files (the "Software"), to deal in the Software without ;; restriction, including without limitation the rights to use, copy, ;; modify, merge, publish, distribute, sublicense, and/or sell copies ;; of the Software, and to permit persons to whom the Software is ;; furnished to do so, subject to the following conditions: ;; The above copyright notice and this permission notice shall be ;; included in all copies or substantial portions of the Software. ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ;; DEALINGS IN THE SOFTWARE. ;;; Commentary: ;; Devil intercepts your devil key (comma by default) to let you type ;; key sequences without using modifier keys. Devil is highly ;; configurable and it can be configured to perform other key sequence ;; translations. ;;; Code: ;;; Customization ==================================================== (defgroup devil '() "Minor mode for translating key sequences." :prefix "devil-" :group 'editing) (defconst devil-version "0.6.0" "Devil version string.") (defvar devil-mode-map (make-sparse-keymap) "Keymap for Devil mode. By default, only `devil-key' is added to this keymap so that Devil can be activated using it. To support multiple activation keys, this keymap may be modified to add multiple keys to activate Devil.") (defcustom devil-logging nil "Non-nil iff Devil should print log messages." :type 'boolean) (defun devil-toggle-logging () "Toggle the value of `devil-logging'." (interactive) (setq devil-logging (not devil-logging)) (message "Devil: Logging %s" (if devil-logging "enabled" "disabled"))) (defmacro devil--log (format-string &rest args) "Write log message with the given FORMAT-STRING and ARGS." `(when devil-logging (message (concat "Devil: " ,format-string) ,@args))) (defun devil--custom-devil-key (symbol value) "Set Devil key variable SYMBOL to the key sequence in given VALUE. After setting SYMBOL to VALUE, clear all key bindings in `devil-mode-map' and add a new key binding such that the key sequence given in VALUE activates Devil." (set-default symbol value) (setcdr devil-mode-map nil) (define-key devil-mode-map value #'devil) (devil--log "Keymap updated to %s" devil-mode-map)) (defun devil-set-key (key) "Set `devil-key' to the given KEY and update `devil-mode-map'. KEY is a string or vector that represents a sequence of keystrokes, e.g., `\",\"', `(kbd \"\")', etc. This function clears existing key bindings in `devil-mode-map' and sets a single key binding in this keymap so that Devil can be activated using the given KEY." (devil--custom-devil-key 'devil-key key)) (defcustom devil-key "," "The key sequence that begins Devil input. Do not set this variable directly. Either use the `devil-set-key' function to set this variable or customize this variable using Emacs customization features/functions. Doing so ensures that the `devil-mode-map' is updated correctly to use the updated value of this variable." :type 'key-sequence :set #'devil--custom-devil-key) (defun devil-key-executor (key) "Create a command to call `devil-execute-key' with KEY when invoked. KEY is a string in the format returned by commands such as `C-h k' (`describe-key'). Format control sequences supported by `devil-format' may be used in KEY. This is a convenience function that returns an interactive lambda that may be used as a binding value for a special key defined in `devil-special-keys'. When the lambda returned by this function is later invoked, it disables Devil keys temporarily and executes the bindings bound to KEY. This allows key sequences involving the configured `devil-key' to be executed to produce their original behaviour thus avoiding invoking Devil recursively." (lambda () (interactive) (devil-execute-key key))) (defcustom devil-special-keys (list (cons "%k %k" (devil-key-executor "%k")) (cons "%k SPC" (devil-key-executor "%k SPC")) (cons "%k RET" (devil-key-executor "%k RET")) (cons "%k " (devil-key-executor "%k ")) (cons "%k h %k k" #'devil-describe-key) (cons "%k h %k l" #'devil-toggle-logging)) "Special Devil keys that are executed as soon as they are typed. The value of this variable is an alist where each key represents a Devil key sequence. If `key-description' of Devil key sequence matches any key in this alist, the function or lambda in the corresponding value is invoked. Format control sequences supported by `devil-format' may be used in the keys." :type '(alist :key-type string :value-type function)) (defcustom devil-translations (list (cons "%k m m" "C-M-") (cons "%k m %k" "M-,") (cons "%k m z" "M-") (cons "%k m" "M-") (cons "%k %k" "%k") (cons "%k z" "C-") (cons "%k" "C-")) "Translation rules to convert Devil input to Emacs key sequence. The value of this variable is an alist where each item represents a translation rule that is applied on the `key-description' of the Devil key sequence read from the user in order to obtain the Emacs key sequence to be executed. The translation rules are applied in the sequence they occur in the alist. For each rule, if the key occurs anywhere in the Devil key sequence, it is replaced with the corresponding value in the translation rule. However, if a replacement leads to an invalid key sequence, then that replacement is skipped. Format control sequences supported by `devil-format' may be used in the keys and values." :type '(alist :key-type string :value-type string)) (defcustom devil-repeatable-keys '(("%k /") ("%k d") ("%k k") ("%k m ^") ("%k m e") ("%k m b" "%k m f" "%k m a" "% k m e") ("%k m @" "%k m h") ("%k m y") ("%k p" "%k n" "%k b" "%k f" "%k a" "%k e") ("%k s") ("%k x [" "%k x ]") ("%k x ^" "%k x {" "%k x }") ("%k x o") ("%k x u")) "Devil mode repeatable key sequences arranged in groups. The value of this variable is a list of lists. Each item (each inner list) of the top-level list represents a group of repeatable key sequences. Each item of each group is a repeatable key sequence. A repeatable key sequence may be repeated merely by typing the last character in the key sequence. After a repeatable key sequence has been typed, typing the last character of any repeatable key sequence that belongs to the same group executes that key sequence. Note that only Devil key sequences that get translated to a regular Emacs key sequence and result in the execution of an Emacs command can be repeatable. The special keys defined in `devil-special-keys' are never repeatable. Format control sequences supported by `devil-format' may be used in the items. Only key sequences that translate to a complete Emacs key sequence according to `devil-translations' and execute an Emacs command are made repeatable." :type '(repeat (repeat string))) (defcustom devil-all-keys-repeatable nil "All successfully translated key sequences become repeatable if non-nil. When this variable is set to non-nil all key sequences that translate to a complete and defined Emacs key sequence become a repeatable key sequence, i.e., every such key sequence can be repeated merely by typing the last character in the key sequence." :type 'boolean) (defcustom devil-lighter " Devil" "String displayed on the mode line when Devil mode is enabled." :type 'string) (defcustom devil-prompt "Devil: %t" "A format control string that determines the `devil' prompt. Format control sequences supported by `devil-format' may be used in the format control string." :type 'string) (defcustom devil-describe-prompt "Describe Devil key: %t" "A format control string that determines the `devil-describe-key' prompt. Format control sequences supported by `devil-format' may be used in the format control string." :type 'string) (defcustom devil-global-sets-buffer-default nil "Non-nil iff `global-devil-mode' modifies new buffer defaults. When non-nil and `global-devil-mode' is enabled, `devil-mode' will be enabled in all new buffers without relying on the standard global minor-mode hooks. While this solves issues with `devil-mode' not being active in buffers which have not called the hooks where a minor-mode could be applied, the decision to bypass these hooks is likely to have been intentional. It is not recommended to enable this option unless you are absolutely sure of the consequences. To work around the most common issue, where `global-devil-mode' is enabled during start-up but `devil-mode' is not enabled in the default Emacs startup screen, a safer solution is to advise the function which creates the startup screen to enable the mode locally." :type 'boolean) ;;; Minor Mode Definition ============================================ ;;;###autoload (define-minor-mode devil-mode "Local minor mode to support Devil key sequences." :lighter devil-lighter (devil--log "Mode is %s in %s" devil-mode (buffer-name))) ;;;###autoload (define-globalized-minor-mode global-devil-mode devil-mode devil--on (if global-devil-mode (devil--add-extra-keys) (devil--remove-extra-keys)) (when devil-global-sets-buffer-default (setq-default devil-mode global-devil-mode))) (defun devil--on () "Turn Devil mode on." (devil-mode 1)) ;;; Bonus Key Bindings =============================================== (defvar devil--saved-keys nil "Original key bindings saved by Devil.") (defun devil--add-extra-keys () "Add key bindings to keymaps for Isearch and universal argument." (devil--log "Adding extra key bindings") (setq devil--saved-keys (devil--original-keys-to-be-saved)) (define-key isearch-mode-map devil-key #'devil) (define-key universal-argument-map (kbd "u") #'universal-argument-more)) (defun devil--remove-extra-keys () "Remove Devil key bindings from Isearch and universal argument." (devil--log "Removing extra key bindings") (define-key isearch-mode-map (kbd ",") (devil--aget 'isearch-comma devil--saved-keys)) (define-key universal-argument-map (kbd "u") (devil--aget 'universal-u devil--saved-keys))) (defun devil--original-keys-to-be-saved () "Return an alist of keys that will be modified by Devil." (list (cons 'isearch-comma (lookup-key isearch-mode-map devil-key)) (cons 'universal-u (lookup-key universal-argument-map (kbd "u"))))) ;;; Activation Commands ============================================== (defun devil () "Read and execute a Devil key sequence." (interactive) (devil--log "Activated with %s" (key-description (this-command-keys))) (let* ((result (devil--read-key devil-prompt (this-command-keys))) (key (devil--aget 'key result)) (translated-key (devil--aget 'translated-key result)) (binding (devil--aget 'binding result))) (devil--log "Read key: %s => %s => %s => %s" key (key-description key) translated-key binding) (if (not binding) (message "Devil: %s is undefined" translated-key) (devil--execute-command key binding) (when translated-key (devil--set-repeatable-keys (key-description key)))))) (defun devil-describe-key () "Describe a Devil key sequence." (interactive) (devil--log "Activated with %s" (key-description (this-command-keys))) (let* ((result (devil--read-key devil-describe-prompt (vector))) (key (devil--aget 'key result)) (translated-key (devil--aget 'translated-key result)) (binding (devil--aget 'binding result))) (devil--log "Read key: %s => %s => %s => %s" key (key-description key) translated-key binding) (if translated-key (describe-key (list (cons (kbd translated-key) key))) ;; Create a transient keymap to describe special key sequence. (let* ((virtual-keymap (make-sparse-keymap)) (exit-function (set-transient-map virtual-keymap))) (define-key virtual-keymap key binding) (describe-key key) (funcall exit-function))))) ;;; Command Lookup =================================================== (defconst devil--fallbacks (list #'devil--terminal-key) "A list of functions that further translate a translated key.") (defun devil--read-key (prompt key) "Read Devil key sequence. Key events are read until it is determined to be a valid special key sequence, a valid complete key sequence after translation to Emacs key sequence, or an undefined key sequence after translation to Emacs key sequence. PROMPT is a format control string that defines the prompt to be displayed while reading the key sequence. Format control sequences supported by `devil-format' may be used in PROMPT. KEY is a vector that represents the key sequence read so far. This function reads a new key from the user, appends it to KEY, and then checks if the result is a valid key sequence or an undefined key sequence. If the result is a valid key sequence for a special key command or an Emacs command, then the command is executed. Otherwise, this function calls itself recursively to read yet another key from the user." (setq key (vconcat key (vector (read-event (devil-format prompt key))))) (or (devil--find-special-command key) (devil--find-regular-command key) (devil--read-key prompt key))) (defun devil--find-special-command (key) "Find special command defined for KEY. If the `key-description' of the given key sequence vector KEY is found to be a special key in `devil-special-keys', the corresponding special command is executed, and a non-nil result is returned. Otherwise nil is returned." (catch 'break (dolist (entry devil-special-keys) (when (string= (key-description key) (devil-format (car entry))) (devil--log "Found special command: %s => %s" (key-description key) (cdr entry)) (throw 'break (devil--binding-result key nil (cdr entry))))))) (defun devil--find-regular-command (key) "Translate KEY and find command bound to it. After translating the given key sequence vector KEY to an Emacs key sequence, if the resulting key sequence turns out to be an incomplete key, then nil is returned. If it turns out to be a complete key sequence, a non-nil result is returned." (devil--find-command key (devil--translate key) devil--fallbacks)) (defun devil--find-command (key translated-key fallbacks) "Find command bound to TRANSLATED-KEY translated from KEY. FALLBACKS is a list of functions. When FALLBACKS is non-nil and no binding is found for the given TRANSLATED-KEY, the given TRANSLATED-KEY is translated further by invoking the `car' of this list. Then this function is called recursively with the `cdr' of this list." (let* ((parsed-key (ignore-errors (kbd translated-key))) (binding (when parsed-key (key-binding parsed-key)))) (cond ((devil--incomplete-key-p translated-key) (devil--log "Ignoring incomplete key: %s" translated-key) nil) ((keymapp binding) (devil--log "Ignoring prefix key: %s" translated-key) nil) ((commandp binding) (devil--log "Found command: %s => %s" translated-key binding) (devil--binding-result key translated-key binding)) (t (devil--log "Undefined key: %s => %s" translated-key binding) (let ((fallback-key (when fallbacks (funcall (car fallbacks) translated-key)))) (if (and fallback-key (not (string= translated-key fallback-key))) (devil--find-command key fallback-key (cdr fallbacks)) (devil--binding-result key translated-key nil))))))) (defun devil--incomplete-key-p (translated-key) "Return t iff TRANSLATED-KEY is an incomplete Emacs key sequence." (string-match "[ACHMSs]-$" translated-key)) (defun devil--binding-result (key translated-key binding) "Create alist for the given KEY, TRANSLATED-KEY, and BINDING." (list (cons 'key key) (cons 'translated-key translated-key) (cons 'binding binding))) ;;; Key Translation ================================================== (defun devil--translate (key) "Translate a given Devil key sequence vector to Emacs key sequence. KEY is a key sequence vector that represents a Devil key sequence. The returned value is an Emacs key sequence string in the format returned by commands such as `C-h k' (`describe-key')." (setq key (key-description key)) (let ((result "") (index 0)) ;; Scan Devil key from left to right. (while (< index (length key)) (catch 'break ;; Try each translation at the current scan position. (dolist (entry devil-translations key) (let* ((from-key (devil-format (car entry))) (to-key (devil-format (cdr entry))) (in-key (substring key index)) (try-key)) (when (string-prefix-p from-key in-key) ;; Apply matching translation at the current scan position. (setq try-key (devil--clean-key (concat result to-key))) (unless (devil--invalid-key-p try-key) ;; Translation succeeded. Do not apply any more ;; translation at the current scan position. Instead ;; move ahead to the next scan position. (setq result try-key) (setq index (+ index (length from-key))) (throw 'break t))))) ;; If no translation succeeded, increment scan position and ;; try applying translations at the new scan position. (let ((char (substring key index (1+ index)))) (setq result (devil--clean-key (concat result char)))) (setq index (1+ index)))) (devil--normalize-ctrl-uppercase-chord result))) (defun devil--terminal-key (translated-key) "Translate TRANSLATED-KEY to an Emacs key sequence for terminal Emacs. The argument TRANSLATED-KEY is a string that represents an Emacs key sequence returned by `devil--translate'. Each keystroke in the key sequence is looked up in `local-function-key-map'. If a match is found, it is replaced with its corresponding binding." (unless (devil--incomplete-key-p translated-key) (let ((result "")) (dolist (chunk (split-string translated-key " " t)) (let* ((separator (if (string= result "") "" " ")) (binding (lookup-key local-function-key-map (kbd chunk)))) (when (and binding (not (keymapp binding))) (setq chunk (key-description binding))) (setq result (concat result separator chunk)))) result))) (defun devil--clean-key (translated-key) "Clean up TRANSLATED-KEY to properly formatted Emacs key sequence." (devil-regexp-replace "\\([ACHMSs]\\)- " "\\1-" translated-key)) (defun devil--normalize-ctrl-uppercase-chord (translated-key) "Normalize chords containing ctrl and uppercase letter in TRANSLATED-KEY." (devil-regexp-replace "C-\\(?:[ACHMs]-\\)*[A-Z]\\(?: \\|$\\)" 'devil--shifted-key translated-key)) (defun devil--shifted-key (translated-key) "Replace the last character in TRANSLATED-KEY with its shifted form." (let* ((hyphen-index (if (string-suffix-p " " translated-key) -2 -1)) (prefix (substring translated-key 0 hyphen-index)) (suffix (substring translated-key hyphen-index))) (concat prefix "S-" (downcase suffix)))) (defun devil--invalid-key-p (translated-key) "Return t iff TRANSLATED-KEY is an invalid Emacs key sequence." (catch 'break (dolist (chunk (split-string translated-key " ")) (when (or (string= chunk "") (not (string-match-p "^\\(?:[ACHMSs]-\\)*\\([^-]*\\|<.*>\\)$" chunk)) (string-match-p "\\([ACHMSs]-\\)[^ ]*\\1" chunk)) (throw 'break t))))) ;;; Command Execution ================================================ (defun devil-execute-key (key) "Suppress Devil keys and execute the given KEY. KEY is a string in the format returned by commands such as `C-h k' (`describe-key'). Format control sequences supported by `devil-format' may be used in KEY." (let ((keymap (cdr devil-mode-map)) (key (devil-format key))) (setcdr devil-mode-map nil) (devil--remove-extra-keys) (devil--log "Disabling keymaps") (unwind-protect (devil--find-bindings-and-execute key) (devil--log "Enabling keymaps") (setcdr devil-mode-map keymap) (devil--add-extra-keys)))) (defun devil--find-bindings-and-execute (key) "Find bindings bound to the given KEY and execute them." (let ((accumulator "")) (dolist (chunk (split-string key " " t)) (let ((separator (if (string= accumulator "") "" " "))) (setq accumulator (concat accumulator separator chunk))) (let* ((result (devil--find-command key accumulator devil--fallbacks)) (binding (devil--aget 'binding result))) (cond ((not binding) (message "Devil: %s is undefined" accumulator) (setq accumulator "")) (t (devil--execute-command (kbd chunk) binding) (setq accumulator ""))))))) (defun devil--execute-command (key binding) "Execute the given BINDING bound to the given KEY." (let ((described-key (key-description key))) (devil--update-command-loop-info key binding) (devil--log-command-loop-info) (devil--log "Executing command: %s => %s" described-key binding) (call-interactively binding))) (defun devil--update-command-loop-info (key binding) "Update variables that maintain command loop information. The given KEY and BINDING is used to update variables that maintain command loop information. This allows the commands that depend on them behave as if they were being invoked directly with the original Emacs key sequence." ;; ;; Set `last-command-event' so that `digit-argument' can determine ;; the correct digit for key sequences like , 5 (C-5). See M-x ;; find-function RET digit-argument RET for details. (setq last-command-event (aref key (- (length key) 1))) ;; ;; Set `this-command' to make several commands like , z SPC , z SPC ;; (C-SPC C-SPC) and , p (C-p) work correctly. Emacs copies ;; `this-command' to `last-command'. Both variables are used by ;; `set-mark-command' to decide whether to activate/deactivate the ;; current mark. The first variable is used by vertical motion ;; commands to keep the cursor at the `temporary-goal-column'. There ;; may be other commands too that depend on this variable. (setq this-command binding) ;; ;; Set `real-this-command' to make , x z (C-x z) work correctly. ;; Emacs copies it to `last-repeatable-command' which is then used ;; by repeat. See the following for more details: ;; ;; - M-x find-function RET repeat RET ;; - C-h v last-repeatable-command RET ;; - grep kset_last_repeatable_command src/keyboard.c (setq real-this-command binding)) (defun devil--log-command-loop-info () "Log command loop information for debugging purpose." (devil--log "Found current-prefix-arg: %s; \ this-command: %s; last-command: %s; last-repeatable-command: %s; \ last-command-event: %s; char-before: %s" current-prefix-arg this-command last-command last-repeatable-command last-command-event (char-before))) (defun devil--set-repeatable-keys (described-key) "Set transient map for repeatable keys in the same group as DESCRIBED-KEY." (let ((group (or (devil--find-repeatable-group described-key) (when devil-all-keys-repeatable (list described-key))))) (when group (devil--log "Setting repeatable keys for %s: %S" described-key group) (devil--set-transient-map group)))) (defun devil--set-transient-map (repeatable-keys-group) "Set transient map for the keys in REPEATABLE-KEYS-GROUP." (let ((map (make-sparse-keymap))) (dolist (repeatable-key repeatable-keys-group) (let* ((key (vconcat (kbd (devil-format repeatable-key)))) (translated-key (devil--translate key)) (transient-key (vector (aref key (1- (length key))))) (result (devil--find-command key translated-key devil--fallbacks)) (binding (devil--aget 'binding result))) (when binding (devil--log "Setting transient repeatable key: %s => %s" (key-description transient-key) binding) (define-key map transient-key binding)))) (set-transient-map map t))) (defun devil--find-repeatable-group (described-key) "Find the repeatable keys group that DESCRIBED-KEY belongs to." (catch 'break (dolist (repeatable-group devil-repeatable-keys) (dolist (repeatable-key repeatable-group) (when (string= described-key (devil-format repeatable-key)) (throw 'break repeatable-group)))))) ;;; Utility Functions ================================================ (defun devil-format (format-string &optional key) "Format a Devil FORMAT-STRING. KEY must be a key sequence vector. The following format control sequences are supported in FORMAT-STRING: %k - Devil key. %r - Devil key sequence read by Devil so far. %t - Emacs key sequence translated from the Devil key sequence. %% - The percent sign." (format-spec format-string (list (cons ?k (key-description devil-key)) (cons ?r (key-description key)) (cons ?t (devil--translate key)) (cons ?% "%")))) (defun devil-string-replace (from-string to-string in-string) "Replace FROM-STRING with TO-STRING in IN-STRING." (let ((case-fold-search nil)) (replace-regexp-in-string (regexp-quote from-string) to-string in-string t t))) (defun devil-regexp-replace (regexp replacement in-string) "Replace REGEXP with REPLACEMENT in IN-STRING." (let ((case-fold-search nil)) (replace-regexp-in-string regexp replacement in-string t))) (defun devil--aget (key alist) "Find KEY in ALIST and return corresponding value." (cdr (assoc key alist))) (provide 'devil) ;;; devil.el ends here