├── .dir-locals.el ├── .gitignore ├── LICENSE.txt ├── README.org ├── deianira-manual-tests.el ├── deianira-tests.el └── deianira.el /.dir-locals.el: -------------------------------------------------------------------------------- 1 | ((emacs-lisp-mode . ((lexical-binding . t) 2 | (nameless-current-name . "dei") 3 | (fill-column . 79) 4 | (indent-tabs-mode . nil)))) 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.elc -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.org: -------------------------------------------------------------------------------- 1 | #+TITLE: Deianira 2 | #+AUTHOR: Martin Edström 3 | #+EMAIL: meedstrom91@gmail.com 4 | #+LANGUAGE: en 5 | # Copying and distribution of this file, with or without modification, 6 | # are permitted in any medium without royalty provided the copyright 7 | # notice and this notice are preserved. This file is offered as-is, 8 | # without any warranty. 9 | 10 | # [[https://img.shields.io/badge/license-GPL3+-blue.png]] 11 | 12 | #+begin_html 13 | Bust of Hercules and Dejanira MET DP812684

14 | #+end_html 15 | 16 | # TODO: More consistent "we", "you", "I" 17 | # TODO: More consistent "hotkey", "key sequence", "key", "key binding" .. try to pick one. 18 | 19 | A [[https://github.com/abo-abo/hydra][hydra]]-based [[https://github.com/justbur/emacs-which-key][which-key]] banisher. In some ways the opposite of [[https://gitlab.com/jjzmajic/hercules.el][hercules.el]] (a "which-key based hydra banisher"). In Greek myth, Hercules slew the beast called Hydra, but was then slain himself by the [[https://en.wikipedia.org/wiki/Deianira][princess Deianira]]. 20 | 21 | * Paradigm 22 | 23 | Imagine that after you press the Control key, Emacs behaves as if Control is still pressed for everything you do next, and then that if you press Meta, Emacs switches to behaving as if Meta is pressed. That's basically what this package supports. 24 | 25 | By itself, that isn't revolutionary, but the details come together into a whole new input paradigm. 26 | 27 | Implementation 28 | 29 | 1. All existing key bindings get copied into hydras. 30 | 2. Control, Meta, Super (and Alt and Hyper if you have them) all become "leader keys" which spawn a hydra specific to each. 31 | - You may know that Spacemacs and Doom Emacs have a thing with the Space key. That's a leader key. You get up to five of them. Why we abuse the modifier keys this way will become apparent, read on. 32 | 3. "Homogenized keymaps": we forbid any difference between keys such as ~C-x C-e~ and ~C-x e~; we bind both to the same command, so it won't matter if you keep holding down Control or not. 33 | - Necessary since I want every keybinding to be typeable by pressing each key in isolation separately, e.g. the sequence ~ x e~ maps to ~C-x e~, but a sequence like ~ x e~ would have 4---count them, 4---isolated key presses and releases in sequence. That's Just Bad, so we rule it out and are left with no obvious key sequence that would map to ~C-x C-e~. Plus, we use the Control key to restart the input sequence, often useful. 34 | 4. Forbid mixing modifiers: we don't allow key sequences with more than a single modifier, like ~C-M-f~, ~M-%~ or ~C-c M-o~. I find these gratuitously painful, and anyway there's no way to bring them over to our hydra system without sacrificing other aspects. 35 | 36 | Consequences 37 | 38 | 1. We can do what I'll coin "transient exits": When the Control hydra is active, we can still type e.g. ~M-f~ to move forward by word, without exiting the Control hydra. This applies to all our hydras, even cases like the hydra for the Control-X-prefix, so instead of a sequence like ~C-x t C-n C-x t C-n C-x t~... you can "stay in the Control-X-prefix" and do ~t C-n t C-n t~... This would not be possible if we allowed more than one modifier in a hotkey. 39 | - In this example, =repeat= wouldn't have helped since you're cycling between two different commands, making it useless. 40 | 2. I find it intuitive, compared to [[https://github.com/emacsorphanage/god-mode][god-mode]] or Spacemacs/Doom. There is no weird new leader key to learn. You press the same modifier keys you always have -- Control and Meta -- and that's all there is to it. 41 | 3. We get many benefits of modal editors and skip some of their drawbacks. 42 | - For example, instead of entering a mode, running a command, exiting it, and returning to whichever mode you were in, as with the hypothetical sequence ~ f ~, it's faster to just type ~M-f~ in whatever hydra you were---and remain in that hydra. These transient exits are one of the most /valid/ uses of modifier chords I've seen, otherwise so maligned for ergonomics. 43 | - In the rest of this document, I avoid the term "mode" but speak of root hydras (the root level of the Control, Meta, Super, Alt or Hyper trees). 44 | 45 | My motivations were: 46 | 47 | - I wanted a modifier-free life, and I decided I don't mind typing more to get that. Longer key sequences beat modifiers. *But* as a happy side effect of implementing the vision, I found we need surprisingly little extra typing this way, and sometimes even /less/. 48 | - I first started to learn Vim, lured in by the promise of "modes instead of Control-chords", but what did I find? An excessive use of capital letters, about as uncomfortable as Control chords. So Vim is not chord-free at all, what a strange oversight. What's the point? It's just a version of Emacs that uses Shift instead of Control, and ships some pretty good hydras (what it calls modes) -- that was Vim's real killer feature all along. Thus began a glimpse of Deianira: I disagree so much with the idea of having "modes" to help you escape chords, and then typing chords within those modes anyway. 49 | - I asked myself as a thought-experiment how one would use Emacs with an [[https://olkb.com/][OLKB Planck]] or other tiny keyboard. This constraint sprouted many ideas. I wondered if you could just bind all commands to sequences of lowercase letters, and with Deianira you can if you want. Please observe that no part of the design was sacrificed to support tiny keyboards -- I actually prefer [[https://geekhack.org/index.php?topic=116622][enormous]] keyboards -- and the good fit is a side effect. 50 | 51 | No "vendor lock-in" 52 | 53 | - We rely on an external Linux utility, [[https://github.com/kmonad/kmonad][kmonad]], to turn Control, Meta and Super into leader keys, even while they continue to work as modifiers. But even should the utility stop working somehow, we won't be left dead in the water. Our mass-remapping is done by the [[https://github.com/meedstrom/massmapper][massmapper]] Emacs-Lisp library, which will always work, so your bindings remain in the location you were expecting. During a kmonad service outage, you'll just have to do one of two things: 54 | 1. Chord at first to start a key sequence, like a normal Emacsian (boo hiss). Even forgetting about the hydra system, the remaps you've made along the way remain accessible, and the bindings are not worse than before you started. 55 | 2. Resort to =xmodmap= or similar basic tool to wholesale remap the keys normally labelled "Ctrl" and "Alt" to send different key events entirely. You can no longer chord, but it's a small loss. In fact, I suggest this trick anyway as a set of [[#training-wheels][training wheels]]. In my experience, it's preferable to have hydras than modifiers. 56 | - If you like the aesthetic of the rules described under Implementation, but decide you don't like the pseudo-modal behavior, you can forgo the hydras entirely. You enable only =massmapper-mode= but not =deianira-mode=. You can leave it at that, or you can nerd out about defining a lot more repeat-maps or hand-made hydras, and perhaps that's better in some ways. Please blog about it! 57 | 58 | * Mandatory setup 59 | (If you have a question, welcome to file a GitHub issue, or find my email in the source code.) 60 | 61 | ** Getting the package 62 | 63 | Minimally tested on Emacs 29 and 30. 64 | 65 | The package is not yet on (M)ELPA. With [[https://github.com/raxod502/straight.el][straight.el]] (and the often-enabled setting =straight-enable-use-package-integration=), you can install the package like so: 66 | 67 | #+begin_src elisp 68 | (use-package massmapper 69 | :straight (massmapper :type git :host github :repo "meedstrom/massmapper")) 70 | (use-package deianira 71 | :straight (deianira :type git :host github :repo "meedstrom/deianira")) 72 | #+end_src 73 | 74 | Alternatively with *Doom Emacs*, this goes in =packages.el=: 75 | 76 | #+begin_src elisp 77 | (package! massmapper :recipe (:host github :repo "meedstrom/massmapper")) 78 | (package! deianira :recipe (:host github :repo "meedstrom/deianira")) 79 | #+end_src 80 | 81 | ** KMonad 82 | 83 | You need [[https://github.com/kmonad/kmonad][kmonad]], install it. Setup instructions follow. 84 | 85 | Possible alternatives to kmonad: 86 | - dual-function-keys ([[#dual-function-keys][partial howto]]) 87 | - Hawck ([[https://github.com/snyball/Hawck/issues/8][partial howto]]) 88 | - QMK firmware -- if you only ever use keyboards with it 89 | - xkeysnail 90 | - ... 91 | 92 | The buggy and unmaintained [[https://github.com/alols/xcape][xcape]] is NOT an alternative. Something so fundamental needs to be reliable; when I tried xcape, it could work for a while and then stop. This leads to giving up on Deianira. 93 | 94 | *** What do I need kmonad for? 95 | Emacs cannot detect the fact that you held down and released Control, Meta or Super, so we need some lower software to tell Emacs about it. Thus, we configure kmonad to send separate key events when you touch the keyboard this way. 96 | 97 | It does not matter which key events will represent this, as the user almost never sees them printed in the echo area. The default choices are a bit unusual, discussed in [[#if-you-wish-to-change-the-keys][the appendix]]. 98 | 99 | *** Training config 100 | Here is a basic KMonad config for a Surface Type Cover keyboard. As you're probably not running that exact keyboard, edit the =device-file= field so it points to the correct keyboard under your =/dev/input/by-id/...=. 101 | 102 | #+begin_src lisp 103 | (defcfg 104 | fallthrough true 105 | input (device-file "/dev/input/by-id/usb-Microsoft_Surface_Type_Cover-event-kbd") 106 | output (uinput-sink "My Deianira-enabling KMonad output")) 107 | 108 | (defsrc 109 | lctl lmeta lalt ralt cmp) 110 | 111 | (deflayer main 112 | KeyKatakana KeyHenkan KeyMuhenkan KeyMuhenkan KeyHenkan) 113 | #+end_src 114 | 115 | Here =cmp= is short for "Compose", i.e. the Menu key, which is all the Surface Type Cover has in that location. If your keyboard has a real Right Win key, replace =cmp= here with =rmeta=. 116 | 117 | (If you want to customize further, you'll want to know that KMonad follows the Linux kernel names for Alt and Meta, what we Emacs folk know respectively as Meta and Super!) 118 | 119 | BEWARE that this kills your ctl, alt and super keys for as long as the process runs, which may leave you unable to recover and need a reboot. *You've been warned.* To be safe, leave the process running as foreground in a terminal and close that terminal with the mouse when you need the effect to end. 120 | 121 | Finally, once you come to agree with [[#super-as-control][Super as Control]] (more on that later) you can just remove =lctl= and =KeyKatakana= here. 122 | 123 | *** Full KMonad config 124 | 125 | Once you've trained yourself out of the habit of chording your hotkeys, you can recover the normal chording behavior of Control/Meta/Super for those times it matters. 126 | 127 | Change the config file above to look more like the below. The =tap-hold-next= magic is why we needed KMonad in the first place. 128 | 129 | #+begin_src lisp 130 | (defcfg 131 | fallthrough true 132 | input (device-file "/dev/input/by-id/usb-Microsoft_Surface_Type_Cover-event-kbd") 133 | output (uinput-sink "My Deianira-enabling KMonad output")) 134 | 135 | (defsrc 136 | lctl lmeta lalt ralt cmp) 137 | 138 | (defalias 139 | lc (tap-hold-next 200 KeyKatakana lctl) 140 | la (tap-hold-next 200 KeyMuhenkan lalt) 141 | ra (tap-hold-next 200 KeyMuhenkan ralt) 142 | lm (tap-hold-next 200 KeyHenkan lmet) 143 | rm (tap-hold-next 200 KeyHenkan rmet)) 144 | 145 | (deflayer main 146 | @lc @lm @la @ra @rm) 147 | #+end_src 148 | 149 | ** Basic initfile snippet 150 | 151 | Put into your initfiles something like the following snippet. 152 | 153 | It may look somewhat involved, but this isn't a place for "sane defaults" or /any/ defaults -- I need to teach you how this stuff works. 154 | 155 | #+begin_src elisp 156 | (require 'massmapper) 157 | (massmapper-mode) 158 | (add-hook 'massmapper-keymap-found-hook #'massmapper-homogenize) 159 | (setq massmapper-debug-level 1) 160 | (setq massmapper-homogenizing-winners 161 | '(("C-c C-c") 162 | (find-file) 163 | ("C-x C-f" . global-map) 164 | ("C-x C-s" . global-map) 165 | ("C-x C-;" . global-map) 166 | ("C-h C-g" . global-map) 167 | ("C-c C-," . org-mode-map))) 168 | 169 | (require 'deianira) 170 | (deianira-mode) 171 | #+end_src 172 | 173 | If you have =(setq hydra-is-helpful nil)= somewhere in your initfiles, you'll want to revert it to =t= for at least a while to see what's going on. 174 | 175 | ** Homogenizing 176 | 177 | Let me introduce you to the most important variable, =massmapper-homogenizing-winners=. Take ownership of it; Deianira refuses to start if it's nil. You'll want to customize it gradually over time. Do you use ~C-x f~ or ~C-x C-f~ more? It's hard to know when thinking about it, only experience will tell you. But this is *absolutely key* to becoming comfortable. 178 | 179 | For more info, check the variable's documentation -- type =C-h v massmapper-homogenizing-winners RET=. 180 | 181 | To see what it has done to your Emacs, type =M-x massmapper-list-remaps RET=. There is no way to revert these bindings except by restarting Emacs, but that buffer works as a lookup table for what you /used/ to have on a key, if you merely want a reminder. 182 | 183 | *** Superfluous entries in which-key 184 | 185 | If you keep which-key, the following snippet will hide the superfluous entries. 186 | 187 | #+begin_src elisp 188 | ;; Hide any key sequence involving more than one chord. We have no reason to 189 | ;; see them after using `massmapper-homogenize'. 190 | (with-eval-after-load 'which-key 191 | (cl-pushnew '((" .-." . nil) . t) which-key-replacement-alist 192 | :test #'equal)) 193 | #+end_src 194 | 195 | ** Desktop-specific configuration 196 | See the appendix sections: 197 | 198 | - [[#out-of-gnome-hell][Out of GNOME hell]] (for users of GNOME or Ubuntu) 199 | - [[#for-exwm-users][For EXWM users]] 200 | - [[#for-users-of-guix-system][For users of Guix System]] 201 | 202 | * Optional setup 203 | ** Non-US keyboard 204 | 205 | If you use Emacs with a non-US keyboard layout, you may want to customize these variables. 206 | 207 | - =dei-hydra-keys= 208 | - =dei-all-shifted-symbols= 209 | 210 | ** Where is repeat? 211 | 212 | Do you use the =repeat= command? Ensure it's always there for you by binding =hydra-repeat= in =hydra-base-map= to the same key where you bound =repeat= in =global-map=. 213 | 214 | Let's say you already bound it to ~~ globally and want to keep it there. Then just add an eval-after-load so the end result looks like: 215 | 216 | #+begin_src elisp 217 | (define-key global-map (kbd "") #'repeat) 218 | (with-eval-after-load 'hydra 219 | (define-key hydra-base-map (kbd "") #'hydra-repeat)) 220 | #+end_src 221 | 222 | ** C-g alternative 223 | 224 | Since ~C-g~ is normally bound to keyboard-quit, pressing ~g~ in the Control hydra will do what you'd expect (the same thing as ~C-g~), but I advise against getting in the habit of using it. It's so prone to muscle-memorization and when you're in the Meta hydra or any other hydra, ~g~ /will do something else/. Some naive recourses could be: 225 | 226 | - 1. Bind ~g~ to keyboard-quit in every hydra, i.e. bind ~M-g~, ~s-g~, ~M-s g~, ~C-x g~ and so on, or: 227 | - 2. Don't get in the habit of pressing ~g~ in the Control hydra; press ~C-g~ always 228 | - 3. Always press Control and ~g~ sequentially. 229 | 230 | All three have issues. #1 still will need ~C-g~ when no hydra is active. With #2, it's a chord, and we wanted to be free of chords (and I'd realistically never keep up that discipline). Perhaps more natural is #3, but I find using it this way invites the question why it was ever on a two-key chord in the first place. If I may recommend a bold alternative: 231 | 232 | - 4. Bind some other key to do what ~C-g~ did. 233 | 234 | Everyone's got a different origin story with Emacs, but when you first learned ~C-g~ in the tutorial, I expect you must have been bemused. Maybe you got used to it and haven't thought about it since, but it's a bizarre binding. Such a fundamental action should only take one keystroke -- on a convenient key such as Return or Escape. 235 | 236 | I picked Escape. I put the following in my init file. After a short period of feeling like I was committing sacrilege, it felt natural like I'd been waiting to do it this way all my life. Try it! 237 | 238 | : (define-key input-decode-map (kbd "") (kbd "C-g")) 239 | 240 | (Wondering how to do =ESC ESC ESC= now? Type =C-[ C-[ C-[=.) 241 | 242 | Note that when Emacs freezes up, you cannot break the freeze with ~~, and all of a sudden ~C-g~ is what you must type to break it, even if you had bound C-g to something else. No other key will do. I suspect it's because Emacs stops looking up the keymaps at all working while it's frozen and the only thing Emacs will react to is a true =^G= character, much like a traditional terminal program can be interrupted with a =^C= character. Try for yourself: eval =(sleep-for 5)= and try to break out of it. Escape won't work, and ~C-g~ will. 243 | 244 | One day, I hope we can set the hardcoded interrupt key as a build option if not a Lisp variable. 245 | 246 | (ASIDE: Another thing disregards Escape: the =M-x save-some-buffers= prompt. This is a bug (https://debbugs.gnu.org/cgi/bugreport.cgi?bug=58808): it calls =map-y-or-n-p= which uses =read-event= rather than the more appropriate =read-key=. But very few things use =map-y-or-n-p=, and most of the time you'd type ~y~ or ~n~, not ~C-g~, so you don't think about it. You may be glad to know it hardcodes ~q~ as an alternative cancel key.) 247 | 248 | So ~C-g~ remains your "unfreeze Emacs" key. You can argue it actually should be on a separate key anyway. However, if that bothers you, the final solution is to use an external program like kmonad to remap the Escape key to send ~C-g~ long before Emacs or even Xkb is involved. This deprives non-Emacs apps of a functioning Escape, but the trick is to then install EXWM and use =exwm-input-simulation-keys= to translate ~C-g~ /back/ into Escape! 249 | 250 | (Feeling vendor-locked-in yet?) 251 | 252 | # Alternatively, interception's =xswitch= plugin should be able to carry out the remap only for Emacs. 253 | 254 | ** Mass remapping 255 | *** Super as Control 256 | 257 | In case I ever sell you on deprecating the Control key, this hook setting copies all Control bindings to Super. 258 | 259 | #+begin_src elisp 260 | (add-hook 'massmapper-keymap-found-hook #'massmapper-define-super-like-ctl) 261 | #+end_src 262 | 263 | If there's any inconsistency, 264 | 265 | - check your initfiles to see if you had directly bound any Super keys 266 | - otherwise, please open a GitHub issue 267 | 268 | **** Benefits 269 | 270 | 1. Luxury for an EXWM user: you can set all your =exwm-input-prefix-keys=, =exwm-input-global-keys= and =exwm-input-simulation-keys= to work only on Super bindings, ceding to other apps full control of Control. 271 | 272 | 2. You can liberate the "nightmare keys" (see docstring of =dei--nightmare-p=): ~C-i~, ~C-[~, ~C-m~, ~C-g~. Because ~s-i~, ~s-[~, ~s-m~, ~s-g~ are not magic aliases to TAB and ilk, you can rebind them at will and buy yourself more real estate. 273 | 274 | *** Super as Control-Meta 275 | 276 | An alternative if you didn't buy my kool-aid above. This hook copies all Control-Meta bindings (i.e. keys starting with =C-M-=...) to Super, giving you a nice starting place for filling out Super. 277 | 278 | #+begin_src elisp 279 | (add-hook 'massmapper-keymap-found-hook #'massmapper-define-super-like-ctlmeta) 280 | #+end_src 281 | 282 | Of course it's only relevant if you hate typing Control-Meta keys, like me. It is possible to make it so that pressing Control and Meta together pops up a special hydra for Control-Meta bindings, but in my opinion that's a nasty complication: with three modifiers to start from already, you shouldn't be lacking for available key sequences anyway. And if you do, upgrading the hardware (get a keyboard with thumb keys) is the way to go, not contrive software to do things like this. [[http://xahlee.info/kbd/banish_key_chords.html][Chords are the enemy]], why would you /start/ a key sequence with one? 283 | 284 | ** Prefix arguments: ~C-u M-d~, Brutus? 285 | 286 | The bindings for =universal-argument=, =digit-argument= and =negative-argument= present a conundrum. 287 | 288 | 1. C-123456890 and M-123456890 are a huge waste of good keys. 289 | - Why are the ten keys M-1234567890 bound to =digit-argument=, but we're too stingy to bind one more key, ~M-u~, to =universal-argument=? 290 | 3. Having =universal-argument= only on ~C-u~ breaks the ideal we were going for, of never mixing modifiers: 291 | - a. Ever had to type ~C-u 0 M-x~? I wanted to jump out the window too. 292 | - b. It's similar to our issue with ~C-g~; the universal argument should be available under every modifier, and for us also every hydra. In other words if we stick to =u= as the final leaf, we want ~C-u~, ~C-x u~, ~M-u~, ~M-s u~, ~s-u~ etc. But we needn't stick to =u=, more on this later. 293 | 294 | Note: This is not a particular consequence of Deianira. The issue just sticks out like a sore thumb under our paradigm. Binding only ~C-u~ but not ~M-u~, so you end up having to switch modifier midway through typing a command, as in =C-u 0 M-x byte-recompile-directory=... It's made tolerable by the fact that all of C-1234567890 and M-1234567890 are =digit-argument= by default, so that particular example can be called thru =M-0 M-x byte-recompile-directory= (on GUI Emacs). 295 | 296 | If we unbind the digit arguments, we can deal with the loss by making it extra convenient to use the universal argument. By default, to do ~M-d~ 9 times you have to type ~C-u 9 M-d~. The solution, if sticking with ~C-u~ for =universal-argument=, we'll make it also possible to type ~M-u 9 M-d~ and, in particular, ~M-u M-9 M-d~ (this last form provides most comfort). And in a hydra you can simply type =u9d=. Then it should be less scary to get rid of M-123456890. 297 | 298 | You notice that in the above example, we needed to bind ~M-u~, implying we bound every possible sequence ending in =u=: ~M-u~, ~s-u~, ~C-x u~ &c. I do not recommend it. If you pick a dedicated key such as ~~ instead, it's an equal waste of keys in theory since you could've used that to start a key sequence, but: 299 | 300 | 1. it's a shame to spend an alphabetic character on this, they're best reserved for semantics. The use of =u= can aid remembering commands like =up-list= and =upcase-word=. 301 | 2. The universal argument isn't important enough for such a good key as ~u~, in my experience 302 | 3. it's nice to exploit Deianira by bringing in all key sequences under the umbrella of the root hydras that double as modifiers, so we wouldn't make a sequence start on ~~ anyway 303 | 304 | ("Really? F12 as universal argument?" But imagine this key is actually physically labelled Universal Argument, with real ink, as if it was a normal feature of keyboards, equally non-negotiable to the Tab key. You'd just hit it where it is and not even consider moving it to C-u...) 305 | 306 | Another clean-feeling alternative could be the leaf ~=~, i.e. the keys ~C-=~, ~M-=~, ~C-x =~ so on, since (on a US QWERTY keyboard) it's right next to ~-~. 307 | 308 | I find the negative argument the most useful of them all, so I keep the leaf ~-~ bound in every hydra (just like having ~C--~, ~M--~, and company) but if you want to really conserve keys, I suggest picking a location for the universal argument such that it is easy to type together with ~-~. On my laptop, ~~ is suitable since it's just above and to the right. Or you could relocate =negative-argument= itself to, let's say, ~~, with =universal-argument= on ~~. 309 | 310 | Here is an example fix including moving universal-argument to ~C-=~, ~M-=~ and company, instead of ~C-u~, ~M-u~ and company. It skips touching ~C-x =~ or any other long sequence ending in ~=~, but I judge they won't be needed (file an issue if you need it) since this fix ensures ~=~ will work inside any hydra as universal-argument anyway. 311 | 312 | #+begin_src elisp 313 | ;;; Fix prefix arguments 314 | 315 | (define-key global-map (kbd "C-u") nil) 316 | (define-key universal-argument-map (kbd "C-u") nil) 317 | (define-key universal-argument-map (kbd "=") #'universal-argument-more) 318 | (define-key universal-argument-map (kbd "-") #'negative-argument) 319 | 320 | (with-eval-after-load 'hydra 321 | (define-key hydra-base-map (kbd "C-u") nil) 322 | ;; in case you use non-Deianira-made hydras 323 | (define-key hydra-base-map (kbd "=") #'hydra--universal-argument)) 324 | 325 | ;; Don't waste good keys (C-123456890) on digit arguments. 326 | ;; But make it more convenient to access them in other ways. 327 | (let ((modifiers '("C-" "M-" "s-" "H-" "A-")) 328 | (digits (split-string "1234567890" "" t))) 329 | (dolist (mod modifiers) 330 | (define-key global-map (kbd (concat mod "-")) #'negative-argument) 331 | (define-key global-map (kbd (concat mod "=")) #'universal-argument) 332 | (define-key universal-argument-map (kbd (concat mod "=")) #'universal-argument-more) 333 | (dolist (d digits) 334 | (define-key global-map (kbd (concat mod d)) nil) ;; unbind 335 | (define-key universal-argument-map (kbd (concat mod d)) #'digit-argument)))) 336 | #+end_src 337 | 338 | If you want to use a dedicated key like == instead, replace all occurrences of ~=~ with ~~ in the code snippets so far, and add another line: 339 | #+begin_src elisp 340 | (define-key global-map (kbd "") #'universal-argument) 341 | #+end_src 342 | 343 | Finally note that the Org setting =org-replace-disputed-keys= overrides ~M--~, so you may want to leave it at nil. 344 | 345 | *** Community packages override my M-1234567890! 346 | 347 | Some packages override M-1234567890. If you want to prevent that, you can use snippets such as the one posted below. Although a cleaner strategy would be to: 348 | 349 | - wrt. global bindings, take back only C-1234567890 and s-1234567890 for personal use (it's rare anything binds them), but don't put any global bindings on M-1234567890 350 | - wrt. mode-specific bindings, take back M-1234567890 for personal use *unless* a package already binds them 351 | 352 | You will not mind the fact that Magit binds ~M-2~ in magit-section-mode-map if you don't have anything at all on ~M-2~ in global-map anyway. You can still make your own binding for ~M-2~ in org-mode-map, another binding for ~M-2~ in emacs-lisp-mode-map, another in eww-mode-map and so on. 353 | 354 | #+begin_src elisp 355 | ;; Don't take my M-1234567890 356 | (with-eval-after-load 'ranger 357 | (let ((digits (split-string "1234567890" "" t))) 358 | (dolist (d digits) 359 | (define-key ranger-normal-mode-map (kbd (concat "M-" d)) nil) 360 | (define-key ranger-emacs-mode-map (kbd (concat "M-" d)) nil)))) 361 | 362 | ;; Don't take my M-1234567890 363 | (with-eval-after-load 'magit 364 | (define-key magit-section-mode-map (kbd "M-1") nil) 365 | (define-key magit-section-mode-map (kbd "M-2") nil) 366 | (define-key magit-section-mode-map (kbd "M-3") nil) 367 | (define-key magit-section-mode-map (kbd "M-4") nil)) 368 | #+end_src 369 | 370 | ** Quitters and quasiquitters 371 | 372 | The following variables let you specify additional keys and commands that should exit the hydra and how it should happen. As with =massmapper-homogenizing-winners=, experience will tell you over time how to customize these. Read their docstrings so you're aware of their existence. 373 | 374 | - =dei-quitter-keys= 375 | - =dei-quitter-commands= 376 | - =dei-quasiquitter-keys= 377 | - =dei-quasiquitter-commands= 378 | - =dei-stemless-quitters= 379 | - =dei-inserting-quitters= 380 | 381 | * Q&A 382 | ** Can I keep which-key? 383 | Yes. 384 | 385 | ** Can I keep ergoemacs? 386 | In theory. I haven't tested it. 387 | 388 | ** Can I keep xah-fly-keys? 389 | Probably not. 390 | 391 | ** Can I keep god-mode? 392 | No. 393 | 394 | ** What if instead of all this crap, you just use sticky keys and thoughtfully-made repeat-maps? 395 | Not the same thing -- for it to be comparable, you'd need something like god-mode, and you'd still need to setup kmonad or similar software so as to make the Control and Meta keys into entry-points for god-mode's simulations of Control and Meta. 396 | 397 | Do that and I'll link your blog post here! Many things will be different, but I'll leave the particulars for then. 398 | 399 | ** Can you use this without the drastic "homogenizing" remaps? 400 | No. Or there will be a lot of keys you can't reach from hydra, and the paradigm is broken. Worse, if we have /bastard sequences/ (see [[#terminology][terminology]]) or different bindings for chord-once and perma-chord sequences (see [[#terminology][terminology]]), it introduces a layer of doubt that interferes with you memorizing the sequence -- as your muscle memory can't "cross-train" between what happens inside the hydra and what happens outside it. 401 | 402 | Note that we remap only in a structural way, according to a few fixed rules. Sometimes these rules poke us in the eye, but aside from them, we're carefully non-opinionated. In another package, ergoemacs-mode, they move ~M-x~ to ~M-a~, a wonderful improvement but the kind of decision Deianira doesn't involve itself in. 403 | 404 | ** Why do you hate Shift? Shift is great! 405 | Shift has some surprising utilities. But to understand what makes it unique, here's a thought experiment. 406 | 407 | Imagine you make another key replace all the use cases of Shift. Let's say you choose the ~s~ key, short for "Shift" because you're sentimental. 408 | 409 | Now instead of binding anything to say, ~ K~, you bind ~ s k~. You'll note it's the same number of key presses (3), and probably more comfortable. 410 | 411 | It's more comfortable than Shift because Shift has flaws: 412 | 413 | - Shift needs to be held down. (You can solve this with the "sticky keys" feature on many OSes.) 414 | - Shift is typically hit with the pinky finger. (You can solve this with a non-standard keyboard that gives it to a thumb.) 415 | 416 | Even after solving both of these issues, the Shift-involved key sequence will only approach the comfort of the Shift-free key sequence, not meaningfully exceed it. 417 | 418 | So why ever involve Shift in a hotkey? Especially considering you may not always have sticky keys, nor a specialty keyboard? Reasons I've found: 419 | 420 | 1. Mnemonics 421 | 2. /Because/ it chords 422 | 423 | I find Reason 1 insufficient (just my subjective sense of aesthetics---I'd rather have more nested sequences if that means they can all be all-lowercase), so let's look at Reason 2. It's subtle. 424 | 425 | (The below is probably easier to understand after you've used Deianira) 426 | 427 | With Deianira, the ~ s ...~ keys get collected into a new hydra. This much you know. 428 | 429 | Now if we want that hydra to faithfully reflect the Shift experience, we have to make a tradeoff. Should it reflect Shift-with-Sticky-Keys, or chord-Shift? The latter case is easy, it's just Deianira's default behavior (well, it doesn't in fact look up any Shifted keys, but in principle). 430 | 431 | For the former, we'd need a new type of "temporary" hydra where once you execute any key in it, you exit, but /you go up only one level/, i.e. you come back to the ~ ...~ hydra rather than exiting fully. 432 | 433 | If instead of the ~s~ key, you use the actual Shift key like a normal person, you get to /choose/ depending on the context. Sticky Shift does not preclude chord-Shift on occasion. So you can hold down Shift and spam something while sitting in the ~ ...~ hydra. 434 | 435 | /That/ is the unique utility of Shift. It's not much, but it's there. We could generalize this benefit with a massive round of [[https://github.com/emacsorphanage/key-chord/][key-chord.el]] mappings inside each and every hydra. I.e. make it so that when you're in ~ ...~ you can hit the chord ~sk~ as if typing ~s k~ but without actually entering the ~ s...~ subhydra. It could be a wishlist feature. 436 | 437 | However there seems a good alternative use of key-chord in the concept of [[https://dreymar.colemak.org/layers-extend.html][Extend]] from the Colemak community, to vastly increase the number of things you can do without exiting a given hydra. 438 | 439 | * Vision 440 | ** Which engine? 441 | 442 | Despite the name, Deianira is not necessarily a Hercules killer, but could be remade to run on top of it. In fact, there's a range of potential "engines" for us: 443 | 444 | 1. Hydra 445 | 2. Hercules (or just bare which-key) 446 | 3. [[https://tildegit.org/acdw/define-repeat-map.el][define-repeat-map]] 447 | 4. Transient 448 | 449 | (I'd like an engine-agnostic term for the concept shared by all these. Please hit me up. For now, the term "hydra" is short and useful: it can become verbs and adjectives like "hydraize", "hydrable", even other nouns like "hydratics". A "head" is meaningfully different from a "key" and it's nice to have that word. In addition, you can speak of "flocks" of hydras, and of "spawning" and "slaying" them.) 450 | 451 | While it looks perfectly possible to rewire the package to use the other engines, I doubt we get any important benefit from options 2 or 3. What about option 4, tarsius' Transient package? It may have a ton of potential, which I dare not imagine because I've spent enough years thinking about hotkeys and if I'm right, that would blaze a new path full of new questions. 452 | 453 | Let me explain. 454 | 455 | The famous collection of Transients known as Magit is, sayeth Internet Truth, a discoverable way to subtly modify any =git= command, beating the command line even for command line masters. 456 | 457 | If we represent all of Emacs' key bindings in Transients, the same way Magit swallowed all of Git's commands, the benefit is unclear compared to doing the same with Hydra, because most of the time, you do not want to modify a command anyway. But that very fact may boil down to us now having separate commands for all of the following: 458 | 459 | - transpose-chars (C-t) 460 | - transpose-words (M-t) 461 | - transpose-sexps (C-M-t) 462 | - transpose-lines (C-x t) 463 | - transpose-sentences 464 | - transpose-paragraphs 465 | - transpose-regions 466 | - avy-transpose-lines-in-region 467 | - crux-transpose-windows 468 | 469 | (Vimmers, you might now be anxiously shifting in your seat, but bear with me) 470 | 471 | These commands speak of one *verb* "transpose", together with a variety of targets or *objects* "char", "word", "sexp", "line" and so on. We see a similar pattern for the verb "kill": 472 | 473 | - kill-word (M-d) 474 | - kill-line (C-k) 475 | - kill-sexp (C-M-k) 476 | - kill-buffer (C-x k) 477 | - kill-comment 478 | - kill-whole-line 479 | - kill-process 480 | - kill-emacs 481 | - .... 482 | 483 | And so on it goes; the pattern is everywhere in Emacs. With such a cornucopia of predefined commands, it's natural that they rarely need modifying. 484 | 485 | Deianira cooperates with this; it just uncreatively brings in existing key bindings under a hydra, so you get precisely the subset of Emacs commands that had key bindings (a few hundred). By contrast, to properly use Transient's potential, you'd find ways to call every one of Emacs' 3,000+ commands, and maybe by accident create whole crops of new commands that don't yet exist. 486 | 487 | It's easy to imagine a Transient that has just one key for the verb "transpose", one key for the verb "kill", one key for the object "char", one key for the object "word" and so on, and then you add adverbs and adjectives. Once you get to this point, you've reinvented Vim. 488 | 489 | But with the masterpiece that is Transient, maybe we could do better than Vim, beating the "Vim paradigm" even for Vim masters, like Magit beats the command line paradigm? 490 | 491 | As heady as that vision sounds, I'm skeptical whether it'd do much better. That's where I suggest Deianira can come in, one of a set of twins that together beats Vim at Vimgolf. Maybe that's just a fever dream. 492 | 493 | ** How easy would it be to change engine? 494 | 495 | I don't know, but Deianira would not become any simpler. If you imagine that using the Emacs 28 repeat-maps would uncomplicate the code -- no, the lines of code would multiply. Hydra provides a satisfactory API. 496 | 497 | 498 | * Notes 499 | ** Extra modifiers fix everything forever! Or? 500 | If your keyboard is blessed with extra thumb keys, you may be able to acquire Hyper and Alt for a total of five leader keys. If so, you could move most of what you use from under the prefixes ~C-h~, ~C-x~, ~M-g~, ~M-s~ etc to just ~H-~ and ~A-~, but I believe the advantage is small if you already curate the ~C-~ and ~M-~ prefixes since: 501 | 502 | 1. We have many discomfort mitigations in place. 503 | 2. It isn't actually good to spread your leaves under many different prefixes. It's something you do to shorten key sequences, but because we have hydras, many keys are now already as short as they can be, and /switching prefix/ becomes an extra action! The more well-filled one prefix, the less likely you'll have to switch prefix while exploiting a hydra. Thus, you'll benefit more from curating the 2-3 modifiers you already have, than from acquiring extra modifiers like Hyper and Alt. 504 | 3. We have Backspace. On a standard keyboard, Control/Alt/Super aren't in comfortable places, so supposing you find Backspace more comfortable, you may want to minimize the switching between root hydras, and instead travel among a single root hydra's children, going in and out of nested key sequences with the help of Backspace. 505 | - very often, Backspace brings a subtle practical benefit, because for a variety of reasons, there will exist at least a few deeply nested key sequences in your keymap -- much of MELPA binds them by default! When you're in a deep sequence, it can be quicker to Backspace to reach a command than it would be to start over from a root hydra. Only if you truly ensured there were no deep sequences anywhere would the comparison become fair. 506 | 507 | Hyper and Alt are not the panacea you think, because you remain *highly vulnerable* to the choice of *where you bind each command*: it could be good or it could be terrible, needing you to switch prefix very often. Commands you're likely to call after each other should live in the same prefix. No amount of extra keys can brute-force this mandate for careful design. See also [[#vision][Vision]]. 508 | 509 | Although extra arms would help a ton---if you had many arms, you'd not need any modifiers! 510 | 511 | ** Terminology 512 | *** Permachord and chord-once 513 | 514 | The rule of homogenized keymaps imply the following: 515 | 516 | 1. ~C-x k e~ is legal 517 | 2. ~C-x C-k e~ is illegal 518 | 3. ~C-x k C-e~ is illegal 519 | 4. ~C-x C-k C-e~ is legal, but must be bound the same as #1. 520 | 521 | I call the variant at #1 a /chord-once sequence/ and the variant at #4 a /permachord sequence/. The act of "homogenizing" a binding is just making sure #1 and #4 are bound to the same command. By default, the command bound at #1 will be copied to #4, overriding what was on #4. There used to be a variable to control which way it would go by default, but experience showed some problems with the opposite default. 522 | 523 | As for the middle variants, #2 and #3, I call them 'bastard sequences', because they result from a copulation no one wanted. 524 | # These among others can optionally be unbound with =(add-hook 'dei-keymap-found-hook #'dei--unbind-illegal-keys)=, but it doesn't change much for the user. 525 | 526 | *** Bastard sequence 527 | - ~C-c p 4 C-d~ (projectile) 528 | - ~C-c C-e l o~ (org) 529 | 530 | I call the above bastard sequences. Basically those that have you hit a modifier, release it halfway and maybe hit it again at different points. I suspect they arise accidentally or from historical reasons -- at least I hope so. 531 | 532 | *** Key sequence 533 | 534 | Standard Emacs term. A sequence of keys of any number of steps, any of which may include chords. Technically, a single key such as ~~, or a chord such as ~C-M-f~, is a key sequence of one step. 535 | 536 | *** Multi-chord 537 | 538 | A chord involving more than one modifier, such as ~C-M-f~. 539 | 540 | *** Single-pair chord 541 | 542 | A chord that only involves one modifier, such as ~C-f~. 543 | 544 | *** Mixed-modifier sequence 545 | 546 | A key sequence that involves more than one modifier, such as ~C-c M-o~ or ~C-M-w~ (which is also a multi-chord). 547 | 548 | *** Key 549 | 550 | In Emacs vocabulary, a "key" can mean a chord such as ~C-M-f~, which in my opinion is best thought of as three keys. Until we come up with a new term for what it is that's happening thrice in ~C-M-f~ ("key presses"?), it can reduce confusion to pay attention to what is actually meant when someone uses this word. 551 | 552 | *** Quitter 553 | *** Quasi-quitter 554 | * Surprising powers 555 | 556 | Power 1. You can use digit arguments on commands *bound to the same digit,* by backspacing out of the prefix-argument-adapted hydra that temporarily appears. Here we assume that is your universal argument key, what most people call C-u: 557 | : x 3 3 ;; calls C-x 3 with argument 3 558 | 559 | Power 2. You can insert prefix arguments anywhere inside a key sequence, rather than only at the start. These are all equivalent: 560 | : x 3 3 561 | : 3 x 3 562 | : 3 x 3 563 | 564 | Power 3. When a desktop environment like GNOME clobbers your ~s-a~ chord, you can still access it by typing ~ a~. Similarly, on many systems Alt+F4 tries to kill your Emacs, but you can type ~ ~ to reach its real binding, if you gave it one. 565 | 566 | * Known issues 567 | ** Hint is misleading until after the first command 568 | Noticed 2023-11-13. Will work on it. 569 | 570 | The misleading hint also includes "hydra--digit-argument" on the number keys. They're a lie and not meant to be shown. 571 | 572 | The reason this issue could crop up is that I haven't got back to dogfooding this package. (That's also why the package is not published anywhere, yet somehow it got 15 stars...) 573 | 574 | ** On start, no hydras for a little while 575 | Yeah, it takes time to build the first flock (5-20 seconds, longer if you are interacting with Emacs in the meantime). Look at buffer =*deianira*=. 576 | 577 | It used to take minutes and lock up Emacs, so I'm happy with that improvement :-) Further improvement is possible (see source comments on =dei--try-birth-hydra=) but it's not my itch to scratch. 578 | 579 | ** Hydra does not update instantly 580 | If you run buffer-switching commands such as =next-buffer= while a hydra is active, getting a different major mode and keymaps, the hydra hint will not reflect this, but continue to reflect the last buffer you were in. 581 | 582 | Aside from confusion, it's usually not a problem because: 583 | - In a supermajority of cases, the difference is only visual: it's the hydra /hint/ that reflects the wrong buffer's bindings. The keys still do what they should, since most of them are not bound to specific commands but to =(call-interactively (key-binding KEY))=, which results in the correct action. 584 | - By default, =next-buffer= (=C-x =) and similar commands are under the /Control-X-prefix/, which is static and unchanging, i.e. it has no mode-specific anything, so there is no change to show in the hydra 585 | 586 | If you do this under a prefix that changes a lot between major modes, like =C-c=, the next key can behave unexpectedly because: 587 | - It can happen that you expect a key to lead to a sub-hydra but it doesn't. 588 | - The heads' individual =:exit= flags also do not change, so they can be inappropriate for the current buffer, not reflecting =dei-quitter-keys= or related variables. 589 | 590 | In principle, I can fix this so that Deianira serves up a fresh hydra on buffer change, but I haven't found the matter a big deal. 591 | 592 | ** Hydra hint width is wrong 593 | 594 | Can happen when you resize the frame. 595 | 596 | * Pre-release TODOs 597 | # ** Fix critical bug: data destruction 598 | 599 | # Note that =lv= had (has? I haven't seen it in a while) a horrific bug that cleared the buffer of text without possibility of undo, by way of =delete-region=, because =lv-message= called =(with-current-buffer (lv-window))= which sometimes didn't do the expected thing. I'd like to patch in an extra safety clause before the =delete-region=. TODO: before publishing Deianira, patch in a safety clause. (learn how to submit PR upstream) 600 | 601 | ** Training wheels 602 | 603 | It's REALLY hard to stop chording while the modifiers still work as they always did, because 604 | - Muscle memory 605 | - I'm in the habit of absently pressing the modifiers for no reason, which then unexpectedly pops up hydras, and I might accidentally call commands and get a bit overwhelmed with all the unintentional things happening 606 | 607 | A few training wheels in mind, but the most important: *disable the modifiers* for a while. 608 | 609 | 1. Disable the modifiers 610 | - Alt 1. Just plainly remap the lctrl key to KeyKatakana etc. 611 | - Alt 2. Turn the modifiers into Hyper or Alt when held, to block any combinations. 612 | - Because even when Ctl no longer does Ctl, pressing it together with f will still output f on screen -- frustrating. If it were Hyper, you instead get the message "H-f is unbound". 613 | - As a bonus, if your window manager supports it, you could have H-f send C-f in non-Emacs applications so they still work. 614 | 615 | * Appendix 616 | ** I'm a layman. Why did this program take you years to write? It seems simple, what it does? 617 | 618 | 1. KEYMAPS. Like a lot of software, Emacs binds keyboard keys to commands, but unlike most software, Emacs doesn't just have one static list of key-bindings, but keeps hundreds of separate lists which it calls "keymaps". Each may bind the same keys to different commands! To determine what a given key should /in fact/ do, Emacs consults a composite of all the relevant keymaps for the current context, considering rules of precedence. One problem is that this composite changes rapidly, and we use a technology (hydra) that defines keys in a static way. A technical challenge then becomes to continuously update these hydras to reflect the current composite. 619 | 2. KEY SEQUENCES. Also unusual among software, Emacs has key sequences. Aside from reflecting the keymap composite, we want to make hydras to reflect /in which step/ of any sequence we are sitting. This is half the package's /raison d'etre/. We must now connect the hydras to each other in an intuitive predictable way. 620 | 3. AVOIDING MODIFIERS. Having solved 1 and 2, we've done a lot already to avoid modifiers. However, there may be bound two different sequences like Ctrl+X F and Ctrl+X Ctrl+F to different commands. And not only do we want to avoid holding down Ctrl, we want to tap it no more than once. So we bash together the lists of keys, into chord-free lists, so that we won't need to press Ctrl+F in that example, nor even for that matter ensure that we press Ctrl and X simultaneously. Kind of simple, but there's a horrific amount of edge cases, such as when one keymap binds a single command at a given location, and another keymap binds a whole sub-keymap instead, and it takes some thinking to understand what's appropriate here, and we must plug in the user's preferences along the way. 621 | 4. PERFORMANCE. The package must continuously keep its state in sync with the truth of the context -- not just the hydras (points 1 and 2) but the bashing together of key bindings (point 3). Since it could do so as often as every keystroke, and we don't want any input latency, performance becomes a challenge, and we must devise ways to let the computer skip work without breaking the truthful sync. 622 | 623 | After all of /that/ is done, the program /starts/ to be usable. 624 | 625 | ** Out of GNOME hell 626 | 627 | For users on GNOME or Ubuntu. 628 | 629 | Okay, GNOME's behavior when you press the Super key, addictive right? But Super-S does the same thing! There's no need to clobber Super itself! Win back your Super key with this shell command: 630 | 631 | : gsettings set org.gnome.mutter overlay-key '' 632 | 633 | You probably know that you can install Gnome Tweaks to access many hidden settings. However it's not so helpful in discovering which setting is responsible for a misbehavior, like the above-mentioned. So it's worth keeping a personal cheatsheet. 634 | 635 | ------ 636 | 637 | The KDE equivalent of the above: 638 | 639 | : kwriteconfig5 --file kwinrc --group ModifierOnlyShortcuts --key Meta "" 640 | 641 | ------ 642 | 643 | GNOME overrides anything you do with =setxkbmap= and many other commands, but there will be a =gsettings= command to do the same thing. 644 | 645 | Instead of =setxkbmap -option caps:menu=, run this: 646 | 647 | : gsettings set org.gnome.desktop.input-sources xkb-options 'caps:menu' 648 | 649 | Instead of =xset r rate 200 30=: 650 | 651 | : gsettings set org.gnome.desktop.peripherals.keyboard repeat-interval 30 652 | : gsettings set org.gnome.desktop.peripherals.keyboard delay 200 653 | 654 | ** For EXWM users 655 | 656 | If you want access to the hydras from EXWM buffers, configure either =exwm-input-prefix-keys= or =exwm-input-global-keys= so that they passthrough the keys defined in =dei-ersatz-control=, =dei-ersatz-meta= etc. 657 | ** If you wish to change the keys 658 | 659 | We default to the key events Henkan, Katakana, Hiragana and friends because almost all alternatives I've found needs the user to put in some elbow grease to make them work, especially on Wayland. If you type Japanese, you'll need to bind something else. Here's how. 660 | 661 | The keys we've chosen to represent presses of Control/Meta/Super must be listed doubly -- once in the kmonad config, and once in the following Customizable variables. 662 | 663 | - =dei-ersatz-alt= (default "") 664 | - =dei-ersatz-control= (default "") 665 | - =dei-ersatz-hyper= (default "") 666 | - =dei-ersatz-meta= (default "") 667 | - =dei-ersatz-super= (default "") 668 | 669 | If you wish to change a keysym, change it in both places! 670 | 671 | *** Which keysyms? 672 | 673 | In my testing, these keys are predefined on Xkb's =us= layout on the standard pc105 geometry. In other words, the config you get with =setxkbmap -layout us= . I find it likely these keys are defined under many other configs too, maybe even all configs? 674 | 675 | Additionally... they actually work in my testing under Sway WM (a Wayland compositor), unlike many other predefined keys. If someone could explain why so many /don't/ work, I'd appreciate it. 676 | 677 | | Kernel keysym | Emacs keydesc | Xkb keysym | Kernel code | Xkb code | 678 | |----------------------+---------------------+---------------+-------------+----------| 679 | | KEY_SEARCH | | XF86Search | 217 | 225 | 680 | | KEY_MAIL | | XF86Mail | 155 | 163 | 681 | | KEY_HOMEPAGE | | XF86HomePage | 172 | 180 | 682 | | KEY_NEXTSONG | | XF86AudioNext | 163 | 171 | 683 | | KEY_KATAKANA | | Katakana | 90 | 98 | 684 | | KEY_HIRAGANA | | Hiragana | 91 | 99 | 685 | | KEY_HENKAN | | Henkan | 92 | 100 | 686 | | KEY_KATAKANAHIRAGANA | | | 93 | | 687 | | KEY_MUHENKAN | | Muhenkan | 94 | 102 | 688 | | KEY_HANGEUL | | | 122 | | 689 | | KEY_HANJA | | | 123 | | 690 | | KEY_PAUSE | | | | | 691 | 692 | - More kernel keysyms: https://github.com/torvalds/linux/blob/master/include/uapi/linux/input-event-codes.h 693 | - More Xorg keysyms: run =xmodmap -pke=, or see https://gist.github.com/siarie/61247ee2bb70f1146484f852f845c1b7 694 | 695 | *** A keysym is not being recognized! 696 | 697 | Unfortunately, this is unsolved. While many syms look like they should work, the majority did not for me. Hence the known-good table above. 698 | 699 | I understand if it's just that we cannot rely on xmodmap because xmodmap is obsolete, relying on pre-Xkb ideas of how things work. However, the issue crops up even with keysyms that exist /by default/ in both the kernel and default Xkb table. And that's a mystery to me. 700 | 701 | It seems that interception-tools or dual-function-keys interfere with xmodmap settings and even reset Xkb options, so they look like possible culprits also for why some keysyms aren't recognized. I remember xcape cooperating better in this regard. 702 | 703 | **** Write a custom .xkb file 704 | My next step is to write a custom .xkb file and see if that's respected. 705 | 706 | Custom .xkb files are also the most current and portable way to configure the keyboard (it works not only on Xorg but on wlroots-based Wayland compositors like Sway). 707 | 708 | Start by generating a =custom.xkb= file with xkbcomp and modify it: 709 | 710 | : xkbcomp $DISPLAY custom.xkb 711 | 712 | After editing to your satisfaction, load it back. This does not persist across reboots, so if you mess something up badly you can always reboot. 713 | 714 | In Xorg like this 715 | : xkbcomp custom.xkb $DISPLAY 716 | 717 | In Sway like this 718 | : sway input xkbfile custom.xkb 719 | 720 | **** Alt and Hyper 721 | 722 | I once thought it was just Wayland (and Microsoft and Apple) that lacked the concepts of Alt and Hyper, but even Xkb layouts don't normally come with them! 723 | 724 | The Linux kernel doesn't define any syms for what Emacs calls Alt or Hyper, and I doubt that you can find any kernel keycodes that would be automagically recognized as such by Xkb and thereafter Emacs. We need an edit to the Xkb settings. With xmodmap that would have been a couple of simple commands, but it's long deprecated, so here is the .xkb file method: https://wiki.archlinux.org/title/X_keyboard_extension#Meta,_Super_and_Hyper 725 | 726 | (Addendum: looks like Xkb keycodes 92 and 203 are mapped to Mod3 and Mod5 by default?) 727 | 728 | ** AUR 729 | 730 | Note to self---and whoever hasn't tried AUR. 731 | 732 | In case I want to try AUR packages like interception-k2k, interception-xswitch or hawck-git, how to do it (the Arch wiki page is much too wordy): 733 | 734 | #+begin_src sh 735 | sudo pacman -S --needed base-devel # run once 736 | git clone https://aur.archlinux.org/interception-k2k-git 737 | cd interception-k2k-git 738 | makepkg 739 | # replace this with the filename you produced 740 | sudo pacman -U interception-k2k-git-0.0.0.r30.259a549-1-x86_64.pkg.tar.zst 741 | #+end_src 742 | 743 | ** Install KMonad on NixOS 744 | Here's how I did it on NixOS: 745 | 746 | 1. set up Guix 747 | 2. install kmonad into your user profile with =guix install kmonad= 748 | 3. write this NixOS system service (assuming that your user is named =me= and your kmonad config file is named =/home/kept/sysconf/kmonad/usb-Microsoft_Surface_Type_Cover-event.kbd=) 749 | 750 | #+begin_src nix 751 | systemd.services.kmonad = { 752 | enable = true; 753 | description = "KMonad"; 754 | after = [ "syslog.target" ]; 755 | script = "/var/guix/profiles/per-user/me/guix-profile/bin/kmonad /home/kept/sysconf/kmonad/usb-Microsoft_Surface_Type_Cover-event.kbd"; 756 | serviceConfig = { 757 | Restart = "on-failure"; 758 | RestartSec = 15; 759 | }; 760 | startLimitBurst = 5; 761 | startLimitIntervalSec = 60; 762 | wantedBy = [ "multi-user.target" ]; 763 | }; 764 | #+end_src 765 | 766 | ** dual-function-keys 767 | 768 | On Arch, install like so: 769 | 770 | : sudo pacman -S interception-dual-function-keys 771 | 772 | Let there be two config files, named =~/udevmon.yaml= and =~/dual-fn.yaml= (the filenames and locations don't matter). Fill them with copypasta from the following sections. 773 | 774 | ([[#for-users-of-guix-system][Users of Guix System]] have some alternate instructions) 775 | 776 | *** udevmon.yaml 777 | 778 | #+begin_src yaml 779 | # note -- change the file path in here if necessary! 780 | - JOB: "intercept -g $DEVNODE | dual-function-keys -c /home/me/dual-fn.yaml | uinput -d $DEVNODE" 781 | DEVICE: 782 | EVENTS: 783 | EV_KEY: [ KEY_LEFTCTRL, KEY_LEFTALT, KEY_LEFTMETA, KEY_RIGHTCTRL, KEY_RIGHTALT, KEY_RIGHTMETA ] 784 | #+end_src 785 | 786 | *** dual-fn.yaml 787 | 788 | #+begin_src yaml 789 | 790 | TIMING: 791 | DOUBLE_TAP_MILLISEC: 0 # default 150 792 | # TAP_MILLISEC: 200 # default 200 793 | 794 | MAPPINGS: 795 | # Control 796 | - KEY: KEY_LEFTCTRL 797 | TAP: KEY_KATAKANA 798 | HOLD: KEY_LEFTCTRL 799 | 800 | - KEY: KEY_RIGHTCTRL 801 | TAP: KEY_KATAKANA 802 | HOLD: KEY_RIGHTCTRL 803 | 804 | # Emacs calls this "Meta" 805 | 806 | - KEY: KEY_LEFTALT 807 | TAP: KEY_MUHENKAN 808 | HOLD: KEY_LEFTALT 809 | 810 | - KEY: KEY_RIGHTALT 811 | TAP: KEY_MUHENKAN 812 | HOLD: KEY_RIGHTALT 813 | 814 | # Emacs calls this "Super" 815 | 816 | - KEY: KEY_LEFTMETA 817 | TAP: KEY_HENKAN 818 | HOLD: KEY_LEFTMETA 819 | 820 | - KEY: KEY_RIGHTMETA 821 | TAP: KEY_HENKAN 822 | HOLD: KEY_RIGHTMETA 823 | #+end_src 824 | 825 | *** Test 826 | 827 | *Step 1.* Test it. Execute the following shell command in some terminal. You can end the effect by interrupting the terminal with Ctrl-C. 828 | 829 | : sudo nice -n -20 udevmon -c ~/udevmon.yaml 830 | 831 | *Step 2.* With the above program active, you should expect that tapping Ctrl, Alt or Super in Emacs will yield a message like " is undefined". Make sure you see that sort of message for all three modifier keys, both the left and right variants, so you know they all work. 832 | 833 | *Step 3*. After verifying the above, type =M-x deianira-mode RET= and see what now happens when you press Ctrl, Alt or Super. You get hydras? Great! 834 | 835 | All done, proceed to next chapter. 836 | 837 | Please mind that this is just a test -- later on, I'll recommend some more lisp in your initfiles. 838 | 839 | (ASIDE: If you want Alt and Hyper, see the appendix.) 840 | 841 | (ASIDE: To use other keysyms than Katakana and friends, see the appendix.) 842 | 843 | (ASIDE: Running this program temporarily resets my Xkb settings -- I have no idea why, but don't be surprised if this happens to you. There are no Gitlab issues about it so maybe I missed something. But running it on computer boot before Xorg, you don't face the problem.) 844 | 845 | *** For users of Guix System 846 | 847 | I don't yet know how to write an on-boot service, but here is how to create =udevmon.yaml= inside the system declaration with hardcoded store paths. 848 | 849 | #+begin_src scheme 850 | (packages 851 | (cons* ... 852 | interception-tools 853 | interception-dual-function-keys 854 | ...)) 855 | (services 856 | (cons* ... 857 | (extra-special-file 858 | "/etc/interception/udevmon.yaml" 859 | (mixed-text-file "udevmon.yaml" 860 | "- JOB: \"" 861 | interception-tools "/bin/intercept" 862 | " -g $DEVNODE | " 863 | interception-dual-function-keys "/bin/dual-function-keys" 864 | ;; NOTE: change this filesystem path to wherever you keep the file 865 | " -c /home/me/dual-fn.yaml | " 866 | interception-tools "/bin/uinput" 867 | " -d $DEVNODE\" 868 | DEVICE: 869 | EVENTS: 870 | EV_KEY: [ KEY_LEFTCTRL, KEY_LEFTALT, KEY_LEFTMETA, KEY_RIGHTCTRL, KEY_RIGHTALT, KEY_RIGHTMETA ] 871 | ")) 872 | ...)) 873 | #+end_src 874 | 875 | Execute the following Bash in some TTY and you're ready to go. Re-execute on every boot. 876 | 877 | : sudo nice -n -20 udevmon -c /etc/interception/udevmon.yaml 878 | 879 | (For those just running GNU Guix as a package manager, follow the Arch instructions instead, I think it'll work.) 880 | 881 | * Thanks 882 | 883 | I owe thanks to [[https://github.com/abo-abo][abo-abo]] and the other contributors to Hydra. If I'd had to wrangle =god-mode= or =which-key= to my purposes, I would have needed to know a lot more about the Emacs hotkey internals than I did starting out. With Hydra, I could just hack and experiment, and incrementally arrive to where I am. There's something right about it, it's a friendly API that allows you to iteratively learn as you bend it towards your needs, so it's a fine member of the Emacs ecosystem and representative of its spirit. 884 | -------------------------------------------------------------------------------- /deianira-manual-tests.el: -------------------------------------------------------------------------------- 1 | ;;; deianira-manual-tests.el --- description -*- lexical-binding: t; -*- 2 | 3 | ;; Manual tests 4 | ;; TODO: Figure out a test that doesn't need me to compare with a list thousands of sexps long 5 | (let ((keys-to-hydraize '("C-x a i" "M-o"))) 6 | (setq dei--requested-hydras 7 | (append 8 | (cl-loop for key in keys-to-hydraize 9 | collect 10 | (let ((stem (concat key " "))) 11 | (cons (dei-dub-from-key key) 12 | (append (dei--specify-visible-heads stem) 13 | (dei--specify-invisible-heads stem) 14 | (dei--specify-extra-heads stem))))) 15 | (cl-loop for key in keys-to-hydraize 16 | collect 17 | (let ((stem (concat key " "))) 18 | (cons (concat (dei-dub-from-key key) "-nonum") 19 | (append (dei--specify-visible-heads 20 | stem dei--hydra-keys-list-no-numbers) 21 | (dei--specify-invisible-heads stem) 22 | (dei--specify-extra-heads stem)))))))) 23 | 24 | ;; test 25 | (let ((x (car dei--requested-hydras))) 26 | (dei--define-dire-hydra (car x) (cdr x))) 27 | 28 | ;; test 29 | (cl-loop for x in dei--requested-hydras 30 | collect (dei--define-dire-hydra (car x) (cdr x))) 31 | 32 | 33 | ;; EDUCATION ------------------------------------------- 34 | ;; instructive prior art: which-key--get-keymap-bindings 35 | ;; Also see results of evaluating 36 | ;; (map-keymap 'readkey1 global-map) 37 | ;; (map-keymap 'readkey2 global-map) 38 | 39 | (defun readkey1 (ev def) 40 | (print (key-description (list ev)) (get-buffer-create "*scratch*")) 41 | (print def (get-buffer-create "*scratch*"))) 42 | 43 | (defun readkey2 (ev def) 44 | (when (dei--of-interest-p def) 45 | (print (key-description (list ev))) 46 | (print def))) 47 | 48 | ;; Unfortunately C source, so you can't learn from them: 49 | ;; (substitute-command-keys "\\{org-mode-map}") 50 | ;; (accessible-keymaps global-map) 51 | 52 | ;; Other cool functions 53 | ;; (keyboard-translate) 54 | 55 | ;; map-keymap passes events to a function, and those events look like 56 | ;; 67108918 or f2 57 | ;; and it turns out you can append events instead of concatting strings: 58 | ;; (key-description (append (kbd "C-x") (list 67108918))) 59 | ;; => "C-x C-6" 60 | ;; -------------------------------------------------------- 61 | 62 | 63 | 64 | ;;; deianira-manual-tests.el ends here 65 | -------------------------------------------------------------------------------- /deianira-tests.el: -------------------------------------------------------------------------------- 1 | ;;; deianira-tests.el -*- lexical-binding: t; -*- 2 | 3 | (require 'deianira) 4 | (require 'ert) 5 | 6 | (ert-deftest dei-test-keydesc-handling () 7 | 8 | (should (equal (dei--corresponding-hydra (massmapper--parent-stem "C-x ")) #'dei-C/body)) 9 | (should (equal (dei--corresponding-hydra (massmapper--parent-stem "M-x ")) #'dei-M/body)) 10 | (should (equal (dei--corresponding-hydra (massmapper--parent-stem "s-x ")) #'dei-s/body)) 11 | (should (equal (dei--corresponding-hydra (massmapper--parent-stem "s-x a ")) #'dei-sx/body)) 12 | (should-error (dei--corresponding-hydra (massmapper--parent-stem "s-x a"))) 13 | (should (equal (dei--corresponding-hydra (massmapper--parent-stem "C-")) nil)) 14 | 15 | (should (massmapper--key-contains dei--all-shifted-symbols-list "M-F")) 16 | (should (massmapper--key-contains dei--all-shifted-symbols-list "C-M-F")) 17 | (should (massmapper--key-contains dei--all-shifted-symbols-list "F")) 18 | (should-not (massmapper--key-contains dei--all-shifted-symbols-list "M-f")) 19 | (should-not (massmapper--key-contains dei--all-shifted-symbols-list "C-M-f")) 20 | (should-not (massmapper--key-contains dei--all-shifted-symbols-list "RET")) 21 | 22 | ;; Not a big fan of the angle bracket protectors. Think I might bank on 23 | ;; mandating no capitals (or always rephrasing them to have S- out front), 24 | ;; then upcasing everything that'd normally go between angle brackets. Which 25 | ;; also means I have to mandate that you can't make hydras from both TAB and 26 | ;; , but that's cool bc it implies I can use RET as a shorthand for 27 | ;; . 28 | (should (equal (dei--dub-hydra-from-key-or-stem "C-x 8 RET") "dei-Cx8")) 29 | (should (equal (dei--dub-hydra-from-key-or-stem " 8 RET") "dei-8")) 30 | (should (equal (dei--dub-hydra-from-key-or-stem " f r") "dei-fr")) 31 | (should (equal (dei--dub-hydra-from-key-or-stem " ") "dei-")) 32 | (should (equal (dei--dub-hydra-from-key-or-stem "ESC C-") "dei-")) 33 | (should (equal (dei--dub-hydra-from-key-or-stem "C-x RET C-\\") "dei-Cx\\")) 34 | (should (equal (dei--dub-hydra-from-key-or-stem "C-x RET C-> <") "dei-Cx><")) 35 | (should (equal (dei--dub-hydra-from-key-or-stem "M-") "dei-M")) 36 | (should (equal (dei--dub-hydra-from-key-or-stem "C-- - -") "dei-C---")) 37 | (should (equal (dei--dub-hydra-from-key-or-stem "C--") "dei-C-")) 38 | (should (equal (dei--dub-hydra-from-key-or-stem "C-") "dei-C")) 39 | (should (equal (dei--dub-hydra-from-key-or-stem "-") "dei--")) 40 | (should (equal (dei--dub-hydra-from-key-or-stem "TAB") "dei-")) 41 | (should (equal (dei--dub-hydra-from-key-or-stem "") "dei-")) 42 | 43 | ;; apparent conflicts are nonissue due to homogenizing 44 | (should (equal (dei--dub-hydra-from-key-or-stem "A-T A-B") "dei-ATB")) 45 | (should (equal (dei--dub-hydra-from-key-or-stem "A-T A B") "dei-ATAB")) 46 | (should (equal (dei--dub-hydra-from-key-or-stem "C-x C-f") "dei-Cxf")) 47 | (should (equal (dei--dub-hydra-from-key-or-stem "C-x f") "dei-Cxf")) 48 | 49 | (should (equal (dei--dub-hydra-from-key-or-stem "s x s x") "dei-sxsx")) 50 | ;; a conflict that's likely to never play a role 51 | (should (equal (dei--dub-hydra-from-key-or-stem "s x s-x") "dei-sxx")) 52 | (should (equal (dei--dub-hydra-from-key-or-stem "s-x s-x") "dei-sxx")) 53 | 54 | ;; not sane result, but ok due to filters in 55 | ;; `dei--unnest-and-filter-current-bindings' 56 | (should (equal (dei--dub-hydra-from-key-or-stem "C-M-") "dei-C")) 57 | 58 | ) 59 | 60 | (ert-deftest dei-test-unnest () 61 | (let ((foo (dei--unnest-and-filter-current-bindings))) 62 | (should (-none-p #'not (-map #'key-valid-p (-map #'car foo)))) 63 | (should (-none-p #'keymapp (-map #'cdr foo))) 64 | (should (--all-p (member (car it) '(closure lambda)) 65 | (-filter #'listp (-map #'cdr foo)))) 66 | ;; (should (not (null (seq-find (lambda (x) (dei--subhydra-or-nil (car ()))) foo)))) 67 | )) 68 | 69 | ;; meant to run in emacs -Q 70 | (ert-deftest dei-test-generate-heads () 71 | (let ((dei--colwidth 30) 72 | (dei--filler (dei--filler-recalc 30))) 73 | (should (equal (length (dei--filler-recalc dei--colwidth)) 30)) 74 | (should (equal (dei--head "C-" "f") 75 | `("f" (call-interactively (key-binding ,(key-parse "C-f"))) "forward-char"))) 76 | (should (equal (dei--head "C-x C-" "f") 77 | `("f" (call-interactively (key-binding ,(key-parse "C-x C-f"))) "find-file"))) 78 | (should (equal (dei--head-invisible "C-" "f") 79 | `("f" (call-interactively (key-binding ,(key-parse "C-f")))))) 80 | (should (equal (dei--head-arg-hint "C-" "f") 81 | (symbol-name (key-binding (key-parse "C-f"))))) 82 | (should (equal (dei--head-arg-hint "C-" "") 83 | dei--filler)) 84 | (should (equal (dei--head-arg-hint "C-" "x") 85 | "dei-Cx/body")) 86 | (should (equal (dei--specify-extra-heads "C-x ") 87 | '(("" dei-C/body :exit t)))) 88 | (should (equal (dei--specify-extra-heads "C-") 89 | '(("" nil :exit t) 90 | ("" nil :exit t) 91 | ("C-" nil:exit t)))) 92 | 93 | ;; Tests 94 | ;; (dei--specify-extra-heads "M-s ") 95 | ;; (dei--specify-extra-heads "M-s M-") 96 | ;; (dei--specify-extra-heads "M-") 97 | ;; (dei--specify-extra-heads "M-" t) 98 | ;; (setq foo (dei--specify-dire-hydra "M-s ")) 99 | ;; (dei--specify-invisible-heads "C-") 100 | ;; (append nil (-map #'car (dei--specify-extra-heads "C-"))) 101 | 102 | )) 103 | 104 | (provide 'deianira-tests) 105 | ;;; deianira-tests.el ends here 106 | -------------------------------------------------------------------------------- /deianira.el: -------------------------------------------------------------------------------- 1 | ;;; deianira.el --- Hydra-ize every key sequence -*- lexical-binding: t; -*- 2 | 3 | ;; (read-symbol-shorthands . '("dei-" . "deianira-")) 4 | 5 | ;; Copyright (C) 2018-2023 Martin Edström 6 | 7 | ;; This program is free software: you can redistribute it and/or modify 8 | ;; it under the terms of the GNU General Public License as published by 9 | ;; the Free Software Foundation, either version 3 of the License, or 10 | ;; (at your option) any later version. 11 | 12 | ;; This program is distributed in the hope that it will be useful, 13 | ;; but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ;; GNU General Public License for more details. 16 | 17 | ;; You should have received a copy of the GNU General Public License 18 | ;; along with this program. If not, see . 19 | 20 | ;; This file is not part of GNU Emacs. 21 | 22 | ;; Author: 23 | ;; Created: 2018-08-03 24 | ;; Version: 0.2.9-pre 25 | ;; Keywords: abbrev convenience 26 | ;; Homepage: https://github.com/meedstrom/deianira 27 | ;; Package-Requires: ((emacs "28") (asyncloop "0.5.1") (massmapper "0.1.4") (compat "29.1.4.4") (hydra "0.15.0") (named-timer "0.1") (dash "2.19.1")) 28 | 29 | ;;; Commentary: 30 | 31 | ;; See the README.org. You may find it by visiting: 32 | ;; https://github.com/meedstrom/deianira 33 | ;; 34 | ;; or by evalling (but your package manager probably left out the README): 35 | ;; (find-file (file-name-directory (find-library-name "deianira"))) 36 | ;; 37 | ;; or with Straight: 38 | ;; M-x straight-visit-package RET deianira RET 39 | 40 | ;;; Code: 41 | 42 | (defgroup deianira nil 43 | "Hydra everywhere." 44 | ;; :link '(info-link "(deianira)") 45 | :group 'keyboard) 46 | 47 | ;; builtin dependencies 48 | (require 'subr-x) 49 | (require 'cl-lib) 50 | 51 | ;; external dependencies 52 | (require 'dash) 53 | (require 'hydra) 54 | (require 'compat) 55 | (require 'asyncloop) ;; was part of this package 56 | (require 'massmapper-lib) ;; was part of this package 57 | 58 | ;; muffle the compiler 59 | (declare-function #'dei-A/body "deianira" nil t) 60 | (declare-function #'dei-C/body "deianira" nil t) 61 | (declare-function #'dei-H/body "deianira" nil t) 62 | (declare-function #'dei-M/body "deianira" nil t) 63 | (declare-function #'dei-s/body "deianira" nil t) 64 | 65 | ;; obsolete 66 | (defun dei-homogenize-all-keymaps () 67 | (display-warning 'massmapper "Deprecated function dei-homogenize-all-keymaps, use massmapper-homogenize")) 68 | 69 | 70 | ;;;; User settings 71 | 72 | (defcustom dei-hydra-keys 73 | "1234567890qwertyuiopasdfghjkl;zxcvbnm,./" 74 | "Keys to show in hydra hint\; default reflects an US QWERTY keyboard. 75 | Length should be divisible by `dei-columns'. In other words, if 76 | you have 10 columns this can be 30 or 40 characters, if you 77 | want 11 columns this can be 33 or 44 characters, and so on. 78 | 79 | The order matters\; it determines the order in which the keys are 80 | displayed. 81 | 82 | Unfortunately I have no advice if you want to show more oddly 83 | located (on QWERTY) keys such as ` or =, but these would waste 84 | columns on an already cramped grid." 85 | :type 'string 86 | :group 'deianira) 87 | 88 | (defcustom dei-all-shifted-symbols 89 | "~!@#$%^&*()_+QWERTYUIOP{}|ASDFGHJKL:\"ZXCVBNM<>?" 90 | "Characters that imply Shift pressed\; default reflects an US keyboard. 91 | You can add or remove any characters, in any order. You can even 92 | merge two or more regional layouts' sets of shift-symbols, 93 | because inclusion in this list mostly means that Deianira will do 94 | less with them. 95 | 96 | Note also that even if you usually use a non-US layout, you do 97 | not need to modify this variable if you never bind non-US keys to 98 | commands anyway." 99 | :type 'string 100 | :group 'deianira) 101 | 102 | (defcustom dei-columns 10 103 | "Amount of columns to display in the hydra hint. 104 | When customizing, please also customize `dei-hydra-keys'." 105 | :type 'number 106 | :group 'deianira) 107 | 108 | (defcustom dei-debug nil 109 | "Whether to enable debugging checks." 110 | :type 'boolean 111 | :group 'deianira) 112 | 113 | (defcustom dei-quasiquitter-keys 114 | '("C-c c" 115 | "C-x l" ;; for testing 116 | ) 117 | "Keys that send you to the root hydra. 118 | Note that if you use Massmapper (see manual), the hydras are 119 | generated afterwards, consulting this list then. So it is safe 120 | to only refer to e.g. \"C-c c\" even if it's going to be a clone 121 | of \"C-c C-c\". In fact, only \"C-c c\" will have an effect, 122 | probably." 123 | :type '(repeat key) 124 | :group 'deianira 125 | :set (lambda (var new) 126 | (set-default var (--map (massmapper--normalize 127 | (key-description (key-parse it))) new)))) 128 | 129 | (defcustom dei-quasiquitter-commands 130 | '(set-mark-command 131 | rectangle-mark-mode) 132 | "Commands that send you to the root hydra." 133 | :type '(repeat symbol) 134 | :group 'deianira) 135 | 136 | (defcustom dei-inserting-quitters 137 | '("SPC" 138 | "RET") 139 | "Keys guaranteed to slay the hydra as well as self-insert. 140 | Note that you do not need to specify shift symbols, as 141 | `dei-all-shifted-symbols' is basically added to this." 142 | :type '(repeat key) 143 | :group 'deianira 144 | :set (lambda (var new) 145 | (set-default var (--map (massmapper--normalize 146 | (key-description (key-parse it))) new)))) 147 | 148 | (defcustom dei-stemless-quitters 149 | '("" 150 | "C-g") 151 | "Keys guaranteed to behave like themselves, instead of the key plus a prefix. 152 | Also guaranteed to slay the hydra. 153 | 154 | This can be used to ensure that when you're in any hydra, let's 155 | say the hydra for the \"C-x a\" keymap, typing C-g will not send 156 | to Emacs \"C-x a C-g\", but simply C-g." 157 | :type '(repeat key) 158 | :group 'deianira 159 | :set (lambda (var new) 160 | (set-default var (--map (massmapper--normalize 161 | (key-description (key-parse it))) new)))) 162 | 163 | (defcustom dei-quitter-keys 164 | '() 165 | "Key sequences guaranteed to slay the hydra. 166 | Note that if you use Massmapper (see manual), the hydras are 167 | generated afterwards, consulting this list then. So it is safe 168 | to only refer to e.g. \"C-c c\" even if it's going to be a clone 169 | of \"C-c C-c\". In fact, only \"C-c c\" will have an effect, 170 | probably." 171 | :type '(repeat key) 172 | :group 'deianira 173 | :set (lambda (var new) 174 | (set-default var (--map (massmapper--normalize 175 | (key-description (key-parse it))) new)))) 176 | 177 | (defcustom dei-quitter-commands 178 | '(keyboard-quit 179 | keyboard-escape-quit 180 | minibuffer-keyboard-quit 181 | abort-recursive-edit 182 | dei--call-and-return-to-root 183 | dei--call-and-return-to-parent 184 | isearch-forward 185 | isearch-forward-regexp 186 | isearch-backward 187 | isearch-backward-regexp 188 | query-replace 189 | query-replace-regexp 190 | doom/escape 191 | doom/restart 192 | doom/restart-and-restore 193 | magit-status 194 | dired 195 | dired-jump 196 | re-builder 197 | ;; ffap-other-frame 198 | ;; make-frame-command 199 | ;; other-frame 200 | kill-emacs 201 | save-buffers-kill-emacs 202 | save-buffers-kill-terminal 203 | +lookup/online 204 | +doom-dashboard/open 205 | org-noter 206 | org-agenda 207 | org-roam-capture 208 | org-capture) 209 | "Commands guaranteed to slay the hydra. 210 | Note that you usually don't need to add commands that focus the 211 | minibuffer, as Deianira tries to slay the hydra automatically 212 | when that happens." 213 | :type '(repeat symbol) 214 | :group 'deianira) 215 | 216 | (defcustom dei-extra-heads 217 | '() 218 | "Heads to add to every hydra. See `defhydra' for the format." 219 | :type '(repeat sexp) 220 | :group 'deianira) 221 | 222 | (defcustom dei-ignore 223 | nil 224 | "Regexp for key sequences to avoid making hydras for. 225 | To ignore all C- sequences, write C-." 226 | :group 'deianira 227 | :type 'string) 228 | 229 | ;; FIXME: broken in the Custom interface 230 | (defcustom dei-invisible-leafs 231 | (append 232 | (split-string 233 | "`-=[]\\'" 234 | "" t) 235 | (split-string 236 | (concat 237 | " SPC" 238 | " " 239 | " TAB "))) 240 | "Keys that should not behave as foreign keys. 241 | By default, typing a key not in `dei-hydra-keys' nor this list 242 | will result in calling that key's normal binding, as if there was 243 | no active hydra (in Hydra jargon, it behaves as a foreign key). 244 | 245 | Inclusion in this list means that key will be prepended with a 246 | prefix, even though you can't see the key in the hint. 247 | 248 | Example: 249 | 250 | If TAB is not a member of this list, typing the three keystrokes 251 | x TAB calls the binding of TAB. 252 | 253 | If TAB is a member of this list, it's taken as a leaf grafted 254 | onto the hydra's corresponding stem. So typing the three 255 | keystrokes x TAB calls the binding of C-x TAB." 256 | :type '(repeat key) 257 | :group 'deianira 258 | :set (lambda (var new) 259 | (set-default var (--map (massmapper--normalize 260 | (key-description (key-parse it))) new)))) 261 | 262 | 263 | ;;;; Background facts 264 | 265 | (defun dei--all-shifted-symbols-list-recalc () 266 | "Make new value for `dei--all-shifted-symbols-list'." 267 | (split-string dei-all-shifted-symbols "" t)) 268 | 269 | (defvar dei--all-shifted-symbols-list (dei--all-shifted-symbols-list-recalc) 270 | "Cache variable, not to be modified directly. 271 | Customize `dei-all-shifted-symbols' instead.") 272 | 273 | (defun dei--hydra-keys-list-recalc () 274 | "Make new value for `dei--hydra-keys-list'." 275 | (split-string dei-hydra-keys "" t)) 276 | 277 | (defvar dei--hydra-keys-list (dei--hydra-keys-list-recalc) 278 | "Cache variable, not to be modified directly. 279 | Customize `dei-hydra-keys' instead.") 280 | 281 | (defun dei--colwidth-recalc (width) 282 | "Recalculate `dei--colwidth' based on frame width WIDTH." 283 | ;; Minus four because of the legend (there's space reserved around a,b,c in 284 | ;; "a: COMMAND b: COMMAND c: COMMAND ...". 285 | (max 1 (- (floor width dei-columns) 4))) 286 | 287 | (defvar dei--colwidth (dei--colwidth-recalc (frame-width)) 288 | "Cache variable, not to be modified directly.") 289 | 290 | (defun dei--filler-recalc (colwidth) 291 | "Recalculate `dei--filler' based on COLWIDTH. 292 | See `dei--colwidth-recalc'." 293 | (make-string colwidth (string-to-char " "))) 294 | 295 | (defvar dei--filler (dei--filler-recalc dei--colwidth) 296 | "Cache variable, not to be modified directly.") 297 | 298 | 299 | ;;;; Library of random stuff 300 | 301 | (defun dei--hydra-active-p () 302 | "Return t if a hydra is active and awaiting input." 303 | (not (null hydra-curr-map))) 304 | 305 | (defun dei--slay (&rest args) 306 | "Slay active hydra and return ARGS." 307 | (when (dei--hydra-active-p) 308 | (setq hydra-deactivate t) 309 | (call-interactively #'hydra-keyboard-quit)) 310 | args) 311 | 312 | (defun dei--dub-hydra-from-key (keydesc) 313 | "Example: if KEYDESC is \"C-x C-a\", return \"dei-Cxa\"." 314 | (declare (pure t) (side-effect-free t)) 315 | (if (string-empty-p keydesc) 316 | nil 317 | (let* ((steps (split-string keydesc " ")) 318 | (first-is-long (> (length (car steps)) 1))) 319 | (and dei-debug 320 | first-is-long 321 | ;; Never try to represent chords beyond the first. This restriction 322 | ;; allows compact notation with dashes and spaces stripped. Else 323 | ;; there would be ambiguity due to confusing chords and keys for 324 | ;; each other (even banning upcase keys leaves s-). 325 | (cl-assert (not (string-match-p massmapper--modifier-safe-re 326 | (substring keydesc 2))))) 327 | (concat "dei-" 328 | ;; root modifier 329 | (and first-is-long 330 | (string-match-p massmapper--modifier-safe-re 331 | (substring keydesc 0 2)) 332 | (substring keydesc 0 1)) 333 | ;; the rest 334 | (string-join 335 | (cl-loop 336 | for step in steps 337 | as leaf = (massmapper--get-leaf step) 338 | collect 339 | ;; TODO: Before transitioning to this, ensure and TAB 340 | ;; don't generate diff hydras 341 | ;; (cond (;; Eliminate ambiguity by downcasing capitals 342 | ;; (and (= 1 (length leaf)) 343 | ;; (seq-contains-p dei-all-shifted-symbols 344 | ;; (string-to-char leaf))) 345 | ;; (concat "S" (downcase leaf))) 346 | ;; ;; Make function keys compact (and stay unambiguous 347 | ;; ;; by upcasing them instead) 348 | ;; ((string-match-p "<.*?>" leaf) 349 | ;; (upcase (string-replace "-" "" (substring 1 -1 leaf)))) 350 | ;; (t 351 | ;; leaf)) 352 | ;; Wrap RET SPC DEL etc in <>, to distinguish from 353 | ;; (extremely unusual) all-caps seqs such as T A B 354 | (if (member leaf '("NUL" "RET" "TAB" "LFD" "ESC" "SPC" "DEL")) 355 | (concat "<" leaf ">") 356 | leaf))))))) 357 | 358 | (defun dei--dub-hydra-from-stem (stem) 359 | "Example: if STEM is \"C-x C-\", return \"dei-Cx\"." 360 | (declare (pure t) (side-effect-free t)) 361 | (if (string-empty-p stem) 362 | nil 363 | (if (= 2 (length stem)) 364 | (concat "dei-" (substring stem 0 1)) ;; stem is just C- or M- etc 365 | (dei--dub-hydra-from-key (string-join (butlast (split-string stem " ")) 366 | " "))))) 367 | 368 | (defun dei--dub-hydra-from-key-or-stem (keydesc-or-stem) 369 | (if (key-valid-p keydesc-or-stem) 370 | (dei--dub-hydra-from-key keydesc-or-stem) 371 | (dei--dub-hydra-from-stem keydesc-or-stem))) 372 | 373 | ;; This is used by `dei--head-arg-cmd' 374 | (defun dei--corresponding-hydra (keydesc-or-stem &optional leaf) 375 | "Return the hydra body that corresponds to a key. 376 | If only one argument is given, KEYDESC-OR-STEM, it should be a 377 | valid key description. If supplying LEAF, then KEYDESC-OR-STEM 378 | should be a dangling stem, as they will be concatenated to make a 379 | valid key description." 380 | (let ((keydesc (concat keydesc-or-stem leaf))) 381 | (if (string-empty-p keydesc) 382 | nil 383 | (intern (concat 384 | (dei--dub-hydra-from-key-or-stem keydesc) 385 | "/body"))))) 386 | 387 | ;; REVIEW: write test for it with a key-simulator 388 | (defun dei-universal-argument (arg) 389 | "Enter a nonum hydra and activate the universal argument." 390 | (interactive "p") 391 | (prefix-command-preserve-state) 392 | (call-interactively 393 | (intern (concat 394 | (substring (symbol-name hydra-curr-body-fn) 0 -5) ;; chop "/body" 395 | "-nonum/body"))) 396 | (hydra--universal-argument arg)) 397 | 398 | (defun dei-negative-argument (arg) 399 | "Enter a nonum hydra and activate the negative argument." 400 | (interactive "p") 401 | (prefix-command-preserve-state) 402 | (call-interactively 403 | (intern (concat 404 | (substring (symbol-name hydra-curr-body-fn) 0 -5) ;; chop "/body" 405 | "-nonum/body"))) 406 | (hydra--negative-argument arg)) 407 | 408 | ;; quasiquit 409 | ;; unused 410 | (defun dei--call-and-return-to-root (keydesc) 411 | "For use in a hydra: call the key binding of KEYDESC. 412 | Then return to the root hydra. 413 | 414 | Nice in some cases, like C-c C-c for which it's often desirable 415 | to end up in the Control root hydra rather than exit altogether. 416 | Say you want to call it for each item in a list of Org headings, 417 | and `next-line' is bound to the standard C-n, then you want to be 418 | able to type nccnccnccncc." 419 | (interactive) 420 | (call-interactively (key-binding (key-parse keydesc))) 421 | (let ((init (substring keydesc 0 2))) 422 | ;; REVIEW: is it better to use call-interactively? 423 | (cond ((string-search "C-" init) (dei-C/body)) 424 | ((string-search "M-" init) (dei-M/body)) 425 | ((string-search "s-" init) (dei-s/body)) 426 | ((string-search "H-" init) (dei-H/body)) 427 | ((string-search "A-" init) (dei-A/body))))) 428 | 429 | ;; unused; another sense of quasiquit 430 | ;; TODO: come up with a good name and implement a defcustom 431 | (defun dei--call-and-return-to-parent (keydesc) 432 | "For use in a hydra: call the key binding of KEYDESC. 433 | Then return to the parent hydra." 434 | (interactive) 435 | (call-interactively (key-binding (key-parse keydesc))) 436 | (if-let ((parent (dei--corresponding-hydra 437 | (massmapper--parent-stem 438 | (massmapper--drop-leaf keydesc))))) 439 | (call-interactively parent) 440 | (hydra-keyboard-quit))) 441 | 442 | 443 | ;;;; Main 444 | 445 | (defvar dei--old-hydra-cell-format nil 446 | "Backup for `hydra-cell-format'.") 447 | 448 | (defvar dei--old-hydra-C-u nil 449 | "Backup for key binding of \"C-u\" in `hydra-base-map'.") 450 | 451 | (declare-function #'ido-read-internal "ido") 452 | (declare-function #'ivy-read "ivy") 453 | (declare-function #'helm "helm-core") 454 | 455 | (defvar dei--interrupts-counter 0 456 | "How many times the hydra maker was interrupted recently.") 457 | 458 | (defun dei--interrupts-decrement () 459 | "Decrement `dei--interrupts-counter' unless already zero." 460 | (unless (zerop dei--interrupts-counter) 461 | (cl-decf dei--interrupts-counter))) 462 | 463 | (defun dei--on-which-keys (command &optional keymap) 464 | "Find to which keys COMMAND is bound. 465 | Optional argument KEYMAP means look only in that keymap." 466 | (->> (where-is-internal command (when keymap (list keymap))) 467 | (-map #'key-description) 468 | (--remove (string-match-p dei--ignore-regexp-merged it)))) 469 | 470 | (defvar dei--give-up nil) 471 | 472 | ;;;###autoload 473 | (define-minor-mode deianira-mode 474 | "Set up hooks to forge hydras, and in the darkness bind them." 475 | :global t 476 | :lighter " dei" 477 | :group 'deianira 478 | :keymap (make-sparse-keymap) 479 | (if deianira-mode 480 | (progn 481 | (setq dei--interrupts-counter 0) 482 | (setq dei--ctr-decay-timer 483 | (run-with-timer 60 60 #'dei--interrupts-decrement)) 484 | (setq dei--old-hydra-cell-format hydra-cell-format) 485 | (setq dei--old-hydra-C-u (keymap-lookup hydra-base-map "C-u")) 486 | (setq hydra-cell-format "% -20s %% -11`%s") 487 | (setq dei--give-up nil) 488 | (keymap-unset hydra-base-map "C-u" t) 489 | ;; REVIEW: I may prefer to just instruct the user to set this stuff 490 | ;; themselves, so they get familiar with the variables 491 | (cl-loop for key in (dei--on-which-keys #'hydra--universal-argument hydra-base-map) 492 | do 493 | (cl-pushnew `( ,key dei-universal-argument nil :exit t) dei-extra-heads) 494 | (setq dei-invisible-leafs (remove key dei-invisible-leafs))) 495 | (cl-loop for key in (dei--on-which-keys #'hydra--negative-argument hydra-base-map) 496 | do 497 | (cl-pushnew `( ,key dei-negative-argument nil :exit t) dei-extra-heads) 498 | (setq dei-invisible-leafs (remove key dei-invisible-leafs))) 499 | ;; REVIEW: Still necessary? 500 | (cl-loop for key in (dei--on-which-keys #'hydra-repeat hydra-base-map) 501 | do (cl-pushnew `( ,key hydra-repeat nil) dei-extra-heads)) 502 | 503 | (add-hook 'before-make-frame-hook #'dei--slay) 504 | (add-hook 'minibuffer-setup-hook #'dei--slay) 505 | (advice-add #'completing-read :before #'dei--slay) 506 | (advice-add #'read-key :before #'dei--slay) 507 | (advice-add #'read-char :before #'dei--slay) 508 | (advice-add #'read-event :before #'dei--slay) 509 | (advice-add #'ido-read-internal :before #'dei--slay) 510 | (advice-add #'ivy-read :before #'dei--slay) 511 | (advice-add #'helm :before #'dei--slay) 512 | (add-hook 'window-buffer-change-functions #'dei-make-hydras-maybe 56) 513 | (add-hook 'window-selection-change-functions #'dei-make-hydras-maybe) 514 | ;; Unfortunately this is triggered every time hydra calls a command. 515 | ;; Maybe upstream would consider it a bug: 516 | ;; (add-hook 'after-change-major-mode-hook #'dei-make-hydras-maybe) 517 | ;; With auto-save-visited-mode, this watcher is triggered every 5 518 | ;; seconds. No big deal but clutters the log buffer: 519 | ;; (add-variable-watcher 'local-minor-modes #'dei-make-hydras-maybe) 520 | (when (and dei-warn-hydra-is-helpful 521 | (not hydra-is-helpful)) 522 | (message "hydra-is-helpful is nil! If intended, disable `%S'" 523 | 'dei-warn-hydra-is-helpful)) 524 | (when (or (bound-and-true-p dei-keymap-found-hook) 525 | (bound-and-true-p dei-homogenizing-winners)) 526 | (deianira-mode 0) 527 | (user-error "%s%s%s" 528 | "Deianira has split into two packages," 529 | " you'll want to add the massmapper package:" 530 | " https://github.com/meedstrom/massmapper")) 531 | (when (null massmapper-homogenizing-winners) 532 | (deianira-mode 0) 533 | (user-error "Disabling Deianira, please customize massmapper-homogenizing-winners"))) 534 | (when dei--loop (asyncloop-cancel dei--loop)) 535 | (when (timerp dei--ctr-decay-timer) (cancel-timer dei--ctr-decay-timer)) 536 | (setq hydra-cell-format (or dei--old-hydra-cell-format "% -20s %% -8`%s")) 537 | (keymap-set hydra-base-map "C-u" dei--old-hydra-C-u) 538 | (remove-hook 'window-buffer-change-functions #'dei-make-hydras-maybe) 539 | (remove-hook 'window-selection-change-functions #'dei-make-hydras-maybe) 540 | (remove-hook 'before-make-frame-hook #'dei--slay) 541 | (remove-hook 'minibuffer-setup-hook #'dei--slay) 542 | (advice-remove #'completing-read #'dei--slay) 543 | (advice-remove #'read-key #'dei--slay) 544 | (advice-remove #'read-event #'dei--slay) 545 | (advice-remove #'read-char #'dei--slay) 546 | (advice-remove #'ido-read-internal #'dei--slay) 547 | (advice-remove #'ivy-read #'dei--slay) 548 | (advice-remove #'helm #'dei--slay))) 549 | 550 | (defcustom dei-warn-hydra-is-helpful t 551 | "Whether to warn that `hydra-is-helpful' is nil.") 552 | 553 | (defvar dei--ctr-decay-timer nil) 554 | (defvar dei--loop nil) 555 | 556 | (defconst dei--ersatz-keys-alist 557 | '((dei-ersatz-alt . dei-A/body) 558 | (dei-ersatz-control . dei-C/body) 559 | (dei-ersatz-hyper . dei-H/body) 560 | (dei-ersatz-meta . dei-M/body) 561 | (dei-ersatz-super . dei-s/body)) 562 | "Table associating the ersatz keys with root hydras. 563 | Never expected to change. Customize `dei-ersatz-alt' & co 564 | instead.") 565 | 566 | (defvar dei--hidden-obarray (obarray-make) 567 | "Place to store the huge variable named \"flocks\". 568 | Reason not to store it in the global obarray as simply just 569 | another variable \"dei--flocks\" is that when the user reads the 570 | source code and happens to place point on \"dei--flocks\", eldoc 571 | chokes Emacs for minutes.") 572 | 573 | (defun dei--set-ersatz-key (sym newkey) 574 | "Bind SYM to NEWKEY, and help other code cope with the change." 575 | ;; Reset all hydras because value gets hardcoded by 576 | ;; `dei--specify-extra-heads' 577 | (obarray-remove dei--hidden-obarray "flocks") 578 | ;; Unbind last key in case it was different 579 | (when (boundp sym) 580 | (keymap-unset deianira-mode-map (symbol-value sym) t)) 581 | ;; Bind new key 582 | (keymap-set deianira-mode-map newkey (alist-get sym dei--ersatz-keys-alist)) 583 | (set-default sym newkey)) 584 | 585 | ;; FIXME: these options are broken in the Custom interface 586 | (defcustom dei-ersatz-alt "" 587 | "Key that represents Alt." 588 | :type 'key 589 | :group 'deianira 590 | :set #'dei--set-ersatz-key) 591 | 592 | (defcustom dei-ersatz-control "" 593 | "Key that represents Control." 594 | :type 'key 595 | :group 'deianira 596 | :set #'dei--set-ersatz-key) 597 | 598 | (defcustom dei-ersatz-hyper "" 599 | "Key that represents Hyper." 600 | :type 'key 601 | :group 'deianira 602 | :set #'dei--set-ersatz-key) 603 | 604 | (defcustom dei-ersatz-meta "" 605 | "Key that represents Meta." 606 | :type 'key 607 | :group 'deianira 608 | :set #'dei--set-ersatz-key) 609 | 610 | (defcustom dei-ersatz-super "" 611 | "Key that represents Super." 612 | :type 'key 613 | :group 'deianira 614 | :set #'dei--set-ersatz-key) 615 | 616 | 617 | ;;;; Hydra blueprinting 618 | 619 | (defvar dei--hydrable-prefixes-with-ancestors nil 620 | "List of keys that may turn into hydras.") 621 | 622 | ;; Head arguments 623 | 624 | (defun dei--head-arg-cmd (stem leaf) 625 | "See `dei--head'." 626 | (let ((key (concat stem leaf))) 627 | (cond 628 | ;; Sub-hydra 629 | ((member key dei--hydrable-prefixes-with-ancestors) 630 | (dei--corresponding-hydra key)) 631 | ;; Quasi-quitter, meaning call key and return to root hydra 632 | ;; Only works if root hydra is a modifier, not if it's or other keys! 633 | ((and (massmapper--key-starts-with-modifier key) 634 | (or (member (key-binding (key-parse key)) dei-quasiquitter-commands) 635 | (member key dei-quasiquitter-keys))) 636 | `(lambda () 637 | (interactive) 638 | (call-interactively (key-binding ,(key-parse key))) 639 | ;; the root hydra /body 640 | (,(dei--corresponding-hydra (substring key 0 2))))) 641 | ;; Regular key 642 | (t 643 | `(call-interactively (key-binding ,(key-parse key))))))) 644 | 645 | (defun dei--head-arg-cmd-leads-to-subhydra-p (stem leaf) 646 | (let ((binding (dei--head-arg-cmd stem leaf))) 647 | (when (symbolp binding) 648 | (string-suffix-p "/body" (symbol-name binding))))) 649 | 650 | (defun dei--head-arg-hint (stem leaf) 651 | "See `dei--head'." 652 | (let* ((sym (if (member (concat stem leaf) 653 | dei--hydrable-prefixes-with-ancestors) 654 | (dei--corresponding-hydra stem leaf) 655 | (key-binding (key-parse (concat stem leaf))))) 656 | ;; REVIEW: when is sym ever not a symbol? 657 | (name (if (symbolp sym) 658 | (symbol-name sym) 659 | (concat stem leaf)))) 660 | (if (null sym) 661 | dei--filler 662 | (if (> (length name) dei--colwidth) 663 | (substring name 0 dei--colwidth) 664 | name)))) 665 | 666 | (defun dei--head-arg-exit (stem leaf) 667 | "See `dei--head'." 668 | (let ((key (concat stem leaf))) 669 | (when (or (member (key-binding (key-parse key)) dei-quasiquitter-commands) 670 | (member (key-binding (key-parse key)) dei-quitter-commands) 671 | (member key dei-quasiquitter-keys) 672 | (member key dei-quitter-keys) 673 | (member key dei--hydrable-prefixes-with-ancestors) 674 | ;; Extra safety measure which could be upstreamed to Hydra 675 | (dei--head-arg-cmd-leads-to-subhydra-p stem leaf)) 676 | '(:exit t)))) 677 | 678 | ;; Different types of full heads 679 | 680 | (defun dei--head (stem leaf) 681 | "Return a hydra head specification (a list), see `defhydra'. 682 | Strings STEM and LEAF concatenate to form a key description 683 | satisfying `key-valid-p' (Emacs 29 function), and string LEAF is 684 | a single unchorded key, typically one character but can also be a 685 | named function key such as ." 686 | `( ,leaf 687 | ,(dei--head-arg-cmd stem leaf) 688 | ,(dei--head-arg-hint stem leaf) 689 | ,@(dei--head-arg-exit stem leaf))) 690 | 691 | (defun dei--head-invisible (stem leaf) 692 | `( ,leaf 693 | ,(dei--head-arg-cmd stem leaf) 694 | ,@(dei--head-arg-exit stem leaf))) 695 | 696 | (defun dei--head-invisible-self-inserting-stemless (_stem leaf) 697 | `( ,leaf 698 | self-insert-command 699 | :exit t)) 700 | 701 | (defun dei--head-invisible-exiting-stemless (_stem leaf) 702 | `( ,leaf 703 | ,(dei--head-arg-cmd "" leaf) 704 | :exit t)) 705 | 706 | (defun dei--head-invisible-stemless (_stem leaf) 707 | `( ,leaf 708 | ,(dei--head-arg-cmd "" leaf))) 709 | 710 | ;; Lists of full heads 711 | 712 | (defun dei--specify-visible-heads (stem &optional verboten-leafs) 713 | "Return a list of heads that will be shown in the hydra hint. 714 | These are for the hydra imaged by STEM, which is combined with 715 | various leafs, see function body. 716 | 717 | Optional argument VERBOTEN-LEAFS, a list of strings such as 718 | '(\"1\" \"z\"), prevents including heads for these leafs." 719 | (let ((leaf-list (-difference dei--hydra-keys-list verboten-leafs))) 720 | (cl-loop for leaf in leaf-list 721 | collect `(,leaf 722 | ,(dei--head-arg-cmd stem leaf) 723 | ,(dei--head-arg-hint stem leaf) 724 | ,@(dei--head-arg-exit stem leaf))))) 725 | 726 | (defun dei--specify-invisible-heads (stem &optional verboten-leafs) 727 | "Return a list of heads not to be shown in the hydra hint. 728 | These are for the hydra imaged by STEM, which is combined with 729 | various leafs, see function body. 730 | 731 | Optional argument VERBOTEN-LEAFS, a list of strings such as 732 | '(\"1\" \"z\"), prevents including heads for these leafs." 733 | (let ((x (append 734 | (cl-loop for leaf in dei-invisible-leafs 735 | collect (dei--head-invisible stem leaf)) 736 | ;; For these keys, we want the hydra to exit, so we need to add 737 | ;; heads so that we can set :exit t. (We design hydras with default 738 | ;; :exit nil for foreign keys, because otherwise we'd need a lot 739 | ;; more heads in order to set :exit nil for them.) As for the 740 | ;; command within these heads, the naive approach is bind to nil, 741 | ;; but we prefer to self-insert at the same time otherwise user has 742 | ;; to press twice. So we bind directly to self-insert-command. An 743 | ;; alternative, our usual head-arg-cmd, is not necessary if we've 744 | ;; anyway decided to self-insert --- although if all shiftsyms were 745 | ;; unbound in all keymaps, it'd work the same. 746 | (cl-loop for leaf in (append dei--all-shifted-symbols-list 747 | dei-inserting-quitters) 748 | collect (dei--head-invisible-self-inserting-stemless stem leaf)) 749 | ;; NOTE: This doesn't overlap with dei-quitter-keys; have to be stemless 750 | (cl-loop for leaf in dei-stemless-quitters 751 | collect (dei--head-invisible-exiting-stemless stem leaf))))) 752 | (-remove (lambda (head) 753 | (member (car head) verboten-leafs)) 754 | x))) 755 | 756 | (defun dei--convert-head-for-nonum (head) 757 | "Ensure that hydra head HEAD suits a nonum hydra. 758 | Basically, if HEAD binds `dei-universal-argument', return a 759 | different head that instead binds `hydra--universal-argument' and 760 | drops any :exit keyword. Same for `dei-negative-argument'. 761 | 762 | This is necessary for the nonum hydras to stay active, as the 763 | wrapper `dei-universal-argument' exists to spawn the nonum hydra to 764 | start with, and should only be called once." 765 | (cond ((eq (cadr head) 'dei-universal-argument) 766 | (list (car head) 'hydra--universal-argument)) 767 | ((eq (cadr head) 'dei-negative-argument) 768 | (list (car head) 'hydra--negative-argument)) 769 | (t 770 | head))) 771 | 772 | (defun dei--specify-extra-heads (stem &optional nonum-p) 773 | "For a hydra imaged by STEM, return some bonus heads for it. 774 | These are mostly the kinds of heads shared by all of Deianira's 775 | hydras. With NONUM-P non-nil, return a different set of extra 776 | heads suited for a nonum hydra, see `dei--convert-head-for-nonum'." 777 | (let ((self-poppers 778 | (cond ((equal "C-" stem) (list dei-ersatz-control 779 | (concat "C-" dei-ersatz-control))) 780 | ((equal "M-" stem) (list dei-ersatz-meta 781 | (concat "M-" dei-ersatz-meta))) 782 | ((equal "s-" stem) (list dei-ersatz-super 783 | (concat "s-" dei-ersatz-super))) 784 | ((equal "H-" stem) (list dei-ersatz-hyper 785 | (concat "H-" dei-ersatz-hyper))) 786 | ((equal "A-" stem) (list dei-ersatz-alt 787 | (concat "A-" dei-ersatz-alt))))) 788 | (extras (if nonum-p 789 | (mapcar #'dei--convert-head-for-nonum dei-extra-heads) 790 | dei-extra-heads))) 791 | (-non-nil 792 | `(,(if nonum-p 793 | `("" ,(dei--corresponding-hydra stem) :exit t) 794 | `("" ,(dei--corresponding-hydra 795 | (massmapper--parent-stem stem)) :exit t)) 796 | ,@(when self-poppers 797 | (cl-loop for key in self-poppers 798 | collect `(,key nil :exit t))) 799 | ,@extras)))) 800 | 801 | ;; Grand merged list of heads 802 | 803 | (defun dei--specify-hydra (stem name &optional nonum-p) 804 | "Return a list of hydra heads, with NAME as first element. 805 | You can pass the output to `dei--try-birth-hydra'. 806 | 807 | String STEM is a stem on which the resulting list of heads will 808 | be based. 809 | 810 | Boolean NONUM-P determines if this should be a numberless hydra, 811 | i.e. one where the numeric keys do numeric prefix arguments 812 | instead of anything else they may have been bound to." 813 | (let* ((extra-heads (dei--specify-extra-heads stem nonum-p)) 814 | (verboten-leafs (append (mapcar #'car extra-heads) 815 | (when nonum-p 816 | (split-string "1234567890" "" t)))) 817 | (heads (append 818 | extra-heads 819 | (dei--specify-visible-heads stem verboten-leafs) 820 | (dei--specify-invisible-heads stem verboten-leafs)))) 821 | (cons name heads))) 822 | 823 | ;; NOTE: Further improving performance is not a priority, but here's where the 824 | ;; package spends over 50% of CPU time, sometimes 90%. I guess defhydra was 825 | ;; not meant to be used in a performance-intensive way, especially when quoted. 826 | ;; Approaches: 827 | ;; 828 | ;; 1. Dodge the need to `eval' a quoted macro, so the byte-compiler can help. 829 | ;; I don't really see a way without rewriting defhydra as a defun that suits 830 | ;; our purposes (even if it would be limited for other purposes). I doubt 831 | ;; I'm capable of doing so without abo-abo's advice since the perf is not an 832 | ;; itch for me anymore. 833 | ;; 834 | ;; 2. Reduce workload by giving up on the self-inserting quitters (principally 835 | ;; capital keys) since there are many of those heads, or giving up on nonum 836 | ;; hydras. 837 | ;; 838 | ;; 3. C-s cream on top RET 839 | ;; 840 | ;; 4. It seems that every time this function runs, it gets slower, in a way 841 | ;; that doesn't have to do with point #3. On emacs start, it takes 0.01s, 842 | ;; but after many flocks, it takes 0.30s per invocation! (And because of 843 | ;; this, the stopgap measure described in point #2 would compound to a huge 844 | ;; difference) 845 | (defun dei--try-birth-hydra (recipe) 846 | "Birth a hydra out of RECIPE formed by `dei--specify-hydra'. 847 | You can view that function as a dry-run and this one as the step 848 | that finally wets it, altering Emacs state in a way the user can 849 | see." 850 | (let ((name (car recipe)) 851 | (list-of-heads (cdr recipe))) 852 | (if (eq hydra-curr-body-fn (intern name)) 853 | ;; REVIEW: An old safety measure, not sure it's needed 854 | (error "This hydra active, skipped redefining: %s" name) 855 | (eval `(defhydra ,(intern name) 856 | (:columns ,dei-columns 857 | :exit nil 858 | :hint nil 859 | :foreign-keys run) 860 | ,name 861 | ,@list-of-heads) 862 | t)))) 863 | 864 | 865 | ;;;; Keymap scanner 866 | 867 | ;; Since (rx (or ...)) calls the slow `regexp-opt', cache the regexp. 868 | (defconst dei--shift-chord-regexp (rx (or bol "-" " ") "S-") 869 | "Match explicit \"S-\" chords in key descriptions. 870 | Do not match capital letters.") 871 | 872 | ;; (will probably export to massmapper.el) 873 | (defun dei--key-is-illegal (keydesc) 874 | "Non-nil if KEYDESC would be unbound in a purist scheme. 875 | This means a scheme of homogenizing, no shift, no multi-chords, 876 | and no mixed modifiers." 877 | (let ((case-fold-search nil)) 878 | (or 879 | (string-match-p dei--shift-chord-regexp keydesc) 880 | (massmapper--key-contains dei--all-shifted-symbols-list keydesc) 881 | (massmapper--key-contains-multi-chord keydesc) 882 | (massmapper--key-mixes-modifiers keydesc) 883 | ;; Drop bastard sequences. 884 | (and (massmapper--key-has-more-than-one-chord keydesc) 885 | (not (massmapper--permachord-p keydesc))) 886 | ;; Drop e.g. C-f. 887 | (and (not (massmapper--key-starts-with-modifier keydesc)) 888 | (string-match-p massmapper--modifier-safe-re keydesc))))) 889 | 890 | (defconst dei--ignore-regexp-merged 891 | (regexp-opt 892 | (append '("DEL" "backspace") 893 | ;; declutter a bit (unlikely someone wants) 894 | '("help" "kp-" "iso-" "wheel" "menu" "redo" "undo" "again" "XF86") 895 | massmapper--ignore-keys-irrelevant 896 | massmapper--ignore-keys-control-chars))) 897 | 898 | ;; REVIEW: Test x 8 with Deianira active. 899 | (defvar dei--avoid-prefixes 900 | (cons "C-x 8" 901 | (mapcar #'key-description 902 | (where-is-internal #'iso-transl-ctl-x-8-map))) 903 | "List of prefixes to avoid looking up.") 904 | 905 | (defvar dei--cache (make-hash-table :size 2000 :test #'equal)) 906 | (defun dei--seq-to-key-if-legal (seq) 907 | (let ((cached-value (gethash seq dei--cache 'not-found))) 908 | (if (eq 'not-found cached-value) 909 | (puthash seq 910 | (let* ((key (key-description seq)) 911 | (normkey (and 912 | ;; Ignore menu-bar/tool-bar/tab-bar 913 | (not (string-search "-bar>" key)) 914 | ;; Sometimes (key-description seq) evalutes 915 | ;; to a key called "C-x (..*", a key called 916 | ;; "ESC 3..9", etc. Even stranger, `seq' for 917 | ;; every one of them is just [switch-frame]. 918 | ;; And all are bound to self-insert-command. 919 | ;; I don't get it. But it's ok to filter out 920 | ;; self-insert-command. 921 | (not (string-search ".." key)) 922 | ;; Finally the input can be assumed valid. 923 | (massmapper--normalize key)))) 924 | (and 925 | normkey 926 | ;; (not (-any-p #'dei--not-on-keyboard (split-string normkey " "))) 927 | (not (string-match-p dei--ignore-regexp-merged normkey)) 928 | (not (massmapper--key-has-more-than-one-chord normkey)) 929 | (not (dei--key-is-illegal normkey)) 930 | (cl-loop for prefix in dei--avoid-prefixes 931 | never (string-prefix-p prefix normkey)) 932 | normkey)) 933 | dei--cache) 934 | cached-value))) 935 | 936 | ;;(dei--relevant-buffer-bindings) 937 | (defun dei--relevant-buffer-bindings () 938 | "List the current bindings appropriate for hydra-making. 939 | The result is an alist of \(KEYDESC . COMMAND\), where each 940 | KEYDESC is normalized to satisfy `key-valid-p'. COMMAND is 941 | expected to be either a command, a lambda or a closure. 942 | 943 | Perhaps obvious but: this is not the bindings from any single 944 | keymap such as `global-map', but from the composite of currently 945 | active keymaps, many of which occlude parts of `global-map'." 946 | ;; You know that the same key can be found several times in multiple 947 | ;; keymaps. Fortunately we can know which binding is correct for the 948 | ;; current buffer, as `current-active-maps' seems to return maps in the 949 | ;; order in which Emacs selects them. So what comes earlier in the list 950 | ;; is what would in fact be used. The rest is history. 951 | (cl-loop 952 | with case-fold-search = nil 953 | for keymap in (current-active-maps) 954 | append (cl-loop 955 | for seq being the key-seqs of keymap 956 | using (key-bindings cmd) 957 | as key = (dei--seq-to-key-if-legal seq) 958 | when key 959 | when cmd 960 | ;; Rule out menu-items and other "weird" bindings 961 | when (if (listp cmd) 962 | (member (car cmd) '(closure lambda)) 963 | t) 964 | ;; Only consider the first instance of a given key (a keymap can 965 | ;; list the same key twice, and it can be in several keymaps) 966 | unless (assoc key bindings) 967 | unless (assoc key merged) 968 | ;; Check if we already found an ancestor to or descendant of this 969 | ;; key sequence... (the things I put up with...) The reason why is 970 | ;; that every key that's already gotten into `merged' at this point 971 | ;; has prio over the key now looked at, so if for example there 972 | ;; exists a bound key C-x s d, it would be wrong to assume that 973 | ;; either C-x s OR C-x s d f are now bound to a command in practice, 974 | ;; just because we found it in this late keymap (C-x s would 975 | ;; technically still be bound, but to a keymap value, not a command, 976 | ;; which still overshadows the C-x s we now find, and the earlier 977 | ;; `assoc' won't catch it because `cl-loop' skips keys bound to 978 | ;; keymap values). 979 | when (cl-loop for (priokey . _) in merged 980 | never (string-prefix-p key priokey) 981 | never (string-prefix-p priokey key)) 982 | ;; May look like amateur `cl-loop' code, but necessary 983 | collect (cons key cmd) into bindings 984 | finally return bindings) 985 | ;; Separating `bindings' and `merged', instead of collecting each key into 986 | ;; `merged' from the start, halves the total execution time 987 | into merged 988 | finally return merged)) 989 | 990 | (defun dei--connection-exists (parent-stem child-stem) 991 | (when (and parent-stem 992 | child-stem) 993 | (let* ((parent-hydra-name (dei--dub-hydra-from-stem parent-stem)) 994 | (child-hydra-name (dei--dub-hydra-from-stem child-stem))) 995 | (and (fboundp (intern (concat parent-hydra-name "/body"))) 996 | (cl-find-if 997 | (lambda (head) 998 | (eq (nth 1 head) 999 | (intern (concat child-hydra-name "/body")))) 1000 | (symbol-value (intern (concat parent-hydra-name "/heads")))))))) 1001 | ;; (dei--connection-exists "C-c " "C-c p ") 1002 | 1003 | 1004 | ;;;; Async worker 1005 | ;; Because it would cause noticable lag to do everything at once, we slice up 1006 | ;; the work into pieces and run them only while the user is not operating 1007 | ;; Emacs. That's not true async, but it makes no difference to the user and 1008 | ;; it's easier to debug than true async (especially when every invocation 1009 | ;; mutates Emacs state). Library I made for this need: 1010 | ;; https://github.com/meedstrom/asyncloop 1011 | 1012 | (defvar dei--hydra-recipes nil "List of arglists to pass to defhydra.") 1013 | (defvar dei--buffer-under-analysis nil "The buffer to make hydras for.") 1014 | (defvar dei--current-hash 0 "The keymap composite in buffer under analysis.") 1015 | (defvar dei--current-width (frame-width) "Width of frame under analysis.") 1016 | (defvar dei--current-bindings nil "The bindings in buffer under analysis.") 1017 | (defvar dei--last-bindings nil "Bindings in last fully analyzed buffer.") 1018 | (defvar dei--changed-stems nil "Stems needing new hydra since last analysis.") 1019 | 1020 | ;; REVIEW: Maybe just presuppose that the user sets things with Emacs 29's 1021 | ;; `setopt'? Lots of users won't, but we could detect a non-default value and 1022 | ;; warn that `setopt' wasn't used. Ehh, I already wrote this. 1023 | (defvar dei--last-settings-alist 1024 | '((dei-hydra-keys) 1025 | (dei-extra-heads) 1026 | (dei-invisible-leafs) 1027 | (dei-stemless-quitters) 1028 | (dei-all-shifted-symbols) 1029 | (dei-inserting-quitters)) 1030 | "User settings to record and watch for changes. 1031 | When they change, we want to carry out some re-calculations, but 1032 | we don't want to do them super-often so we skip doing them as 1033 | long as they don't change.") 1034 | 1035 | (cl-defstruct (dei--flock 1036 | (:constructor dei--flock-define) 1037 | (:copier nil)) 1038 | hash 1039 | width 1040 | funs 1041 | vars 1042 | bindings) 1043 | 1044 | (defun dei--first-flock-by-hash (hash flocks) 1045 | "Return a flock with :hash HASH, among FLOCKS." 1046 | (cl-loop for flock in flocks 1047 | when (eq hash (dei--flock-hash flock)) 1048 | return flock)) 1049 | 1050 | (defun dei--flock-by-hash-and-width (hash width flocks) 1051 | "Return flock with HASH and WIDTH from FLOCKS." 1052 | (cl-loop for flock in flocks 1053 | when (and (eq hash (dei--flock-hash flock)) 1054 | (eq width (dei--flock-width flock))) 1055 | return flock)) 1056 | 1057 | ;; TODO: figure out if it's necessary to respecify heads due to changed 1058 | ;; dei--filler and if so how to get the effect here (theory: we don't need 1059 | ;; filler to be more than one char, I think it was for gracefully degrading 1060 | ;; from a weird issue) (theory: we see no effect when starting with a narrow 1061 | ;; frame and rehint for a big frame, but the other way around could get messy) 1062 | (defun dei--rehint-flock (flock width) 1063 | "Copy FLOCK and update hints to match frame width WIDTH." 1064 | (cl-letf* ((dei--colwidth (dei--colwidth-recalc width)) 1065 | (dei--filler (dei--filler-recalc dei--colwidth)) 1066 | (new (copy-sequence flock))) 1067 | (setf (dei--flock-width new) width) 1068 | (setf (dei--flock-vars new) 1069 | (cl-loop 1070 | for pair in (dei--flock-vars flock) 1071 | when (string-suffix-p "/hint" (symbol-name (car pair))) 1072 | collect 1073 | (let ((basename (substring (symbol-name (car pair)) 0 -5))) 1074 | (cons (car pair) 1075 | (hydra--format 1076 | ;; These arguments are identical to what `defhydra' 1077 | ;; passes to `hydra--format'. The different result 1078 | ;; is due to let-binding `dei--colwidth'. 1079 | basename 1080 | (eval (intern-soft (concat basename "/params"))) 1081 | (eval (intern-soft (concat basename "/docstring"))) 1082 | (eval (intern-soft (concat basename "/heads")))))) 1083 | else collect pair)) 1084 | new)) 1085 | 1086 | ;; Test 1087 | ;; (--filter (string-suffix-p "/hint" (symbol-name (car it))) 1088 | ;; (caddar dei--flocks)) 1089 | ;; (setq bar (dei--rehint-flock (car dei--flocks))) 1090 | ;; (--filter (string-suffix-p "/hint" (symbol-name (car it))) 1091 | ;; (caddr bar)) 1092 | ;; 1093 | 1094 | (defun dei--abort-if-buffer-killed (loop buf) 1095 | "Cancel hydre-building LOOP if buffer killed. 1096 | Otherwise, return nil." 1097 | (unless (buffer-live-p buf) 1098 | (asyncloop-log loop 1099 | "Cancelling because buffer killed: %s" buf) 1100 | (asyncloop-cancel loop) 1101 | t)) 1102 | 1103 | (defun dei--step-1-find-premade (loop) 1104 | (let* ((buffer (current-buffer)) 1105 | (flocks (symbol-value (obarray-get dei--hidden-obarray "flocks"))) 1106 | (hash (abs (sxhash (current-active-maps)))) 1107 | (width (frame-width)) 1108 | ;; If we already made hydras for this keymap composite, retrieve them 1109 | (some-flock (dei--first-flock-by-hash hash flocks))) 1110 | (setq dei--buffer-under-analysis buffer) 1111 | (setq dei--current-hash hash) 1112 | (setq dei--current-width width) 1113 | (if some-flock 1114 | (let* ((past (dei--flock-by-hash-and-width hash width flocks)) 1115 | (width-also-correct 1116 | (if past 1117 | t 1118 | (setq past (dei--rehint-flock some-flock width)) 1119 | nil)) 1120 | (bindings (dei--flock-bindings past)) 1121 | (funs (dei--flock-funs past)) 1122 | (vars (dei--flock-vars past))) 1123 | ;; Reuse cached values. This code came from an eureka, so beautiful. 1124 | (cl-loop for (sym . val) in funs do (fset sym val)) 1125 | (cl-loop for (sym . val) in vars do (set sym val)) 1126 | (setq dei--last-bindings bindings) 1127 | (if width-also-correct 1128 | (progn 1129 | ;; Do not proceed to next steps 1130 | (asyncloop-cancel loop 'quietly) 1131 | (format "Summoned flock %d" hash)) 1132 | ;; After conversion, skip to step 7 to register them 1133 | (setf (asyncloop-remainder loop) (list t #'dei--step-7-register)) 1134 | (format "Converted to %d chars wide: %d" width hash))) 1135 | (format "Requisition new flock for buffer %s" buffer)))) 1136 | 1137 | ;; REVIEW: Maybe write it more readable somehow 1138 | (defun dei--step-2-validate-user-settings (loop) 1139 | "Signal an error if any two user settings overlap. 1140 | That is, if a given key description is found more than once. 1141 | 1142 | This prevents a situation where a hydra defines two heads on 1143 | the same key." 1144 | (unless (dei--abort-if-buffer-killed loop dei--buffer-under-analysis) 1145 | (unless (--all-p (equal (symbol-value (car it)) (cdr it)) 1146 | dei--last-settings-alist) 1147 | (unless (= 0 (mod (length dei-hydra-keys) dei-columns)) 1148 | (user-error "`dei-hydra-keys' not divisible by `dei-columns'")) 1149 | ;; Record the newest setting values, so we can skip the relatively 1150 | ;; expensive calculations next time if nothing changed. 1151 | (setq dei--last-settings-alist 1152 | (cl-loop for cell in dei--last-settings-alist 1153 | collect (cons (car cell) (symbol-value (car cell))))) 1154 | (let ((vars 1155 | (list (cons 'dei-hydra-keys dei--hydra-keys-list) 1156 | (cons 'dei-all-shifted-symbols dei--all-shifted-symbols-list) 1157 | (cons 'dei-invisible-leafs dei-invisible-leafs) 1158 | (cons 'dei-stemless-quitters dei-stemless-quitters) 1159 | (cons 'dei-inserting-quitters dei-inserting-quitters) 1160 | (cons 'dei-extra-heads (mapcar #'car dei-extra-heads))))) 1161 | (while vars 1162 | (let ((var (pop vars))) 1163 | (cl-loop 1164 | for remaining-var in vars 1165 | do (let ((overlap (-intersection (cdr var) 1166 | (cdr remaining-var)))) 1167 | (when overlap 1168 | (error (asyncloop-log loop 1169 | "Found %s in both %s and %s" 1170 | overlap (car var) (car remaining-var)))))))))) 1171 | "OK")) 1172 | 1173 | ;; v2 1174 | (defun dei--connection-exists (parent child) 1175 | "Check if PARENT hydra exists and binds CHILD hydra." 1176 | (when (and parent child) 1177 | (let* ((parent-hydra-name (dei--dub-hydra-from-key parent)) 1178 | (child-hydra-name (dei--dub-hydra-from-key child))) 1179 | (and (fboundp (intern (concat parent-hydra-name "/body"))) 1180 | (cl-find-if 1181 | (lambda (head) 1182 | (eq (nth 1 head) 1183 | (intern (concat child-hydra-name "/body")))) 1184 | (symbol-value (intern (concat parent-hydra-name "/heads")))))))) 1185 | 1186 | ;; what to do if child hydra stops existing?, we still need to redefine the ancestor then 1187 | ;; 1188 | ;; the trick is that if child hydra stops existing, that should be visible as a 1189 | ;; difference in new-bindings. (not necessarily if it's just deeply nested 1190 | ;; keymap that disappeared...) 1191 | ;; 1192 | ;; but then what we want to check is not that a connection exists, but that it 1193 | ;; unexists. 1194 | ;; 1195 | ;; may once again have to split the defunct bindings from the new. 1196 | (defun dei--ancestors-to-connect (key) 1197 | (let (ancestors 1198 | (run t)) 1199 | (while run 1200 | (let ((parent (massmapper--parent-key key))) 1201 | (if (dei--connection-exists parent key) 1202 | ;; also push the parent of the parent in case 1203 | (setq run nil) 1204 | (push parent ancestors) 1205 | )) 1206 | 1207 | ) 1208 | ancestors) 1209 | ) 1210 | 1211 | (defun dei--new-bindings () 1212 | (let* ((new-bindings (append (-difference dei--current-bindings 1213 | dei--last-bindings) 1214 | (-difference dei--last-bindings 1215 | dei--current-bindings))) 1216 | (new-with-ancestors 1217 | (cl-loop 1218 | for (key . _) in new-bindings 1219 | as n = (length (split-string key " ")) 1220 | append (-iterate #'massmapper--parent-key key n))) 1221 | ) 1222 | 1223 | (-union dei--hydrable-prefixes 1224 | (cl-loop 1225 | for prefix in new-with-ancestors 1226 | unless (dei--connection-exists parent-stem stem) 1227 | collect parent-stem)) 1228 | )) 1229 | 1230 | (defun dei--step-3-model-the-world (loop) 1231 | "Calculate facts." 1232 | (unless (dei--abort-if-buffer-killed loop dei--buffer-under-analysis) 1233 | (with-current-buffer dei--buffer-under-analysis 1234 | ;; Cache settings 1235 | (setq dei--all-shifted-symbols-list (dei--all-shifted-symbols-list-recalc) 1236 | dei--hydra-keys-list (dei--hydra-keys-list-recalc) 1237 | dei--colwidth (dei--colwidth-recalc dei--current-width) 1238 | dei--filler (dei--filler-recalc dei--colwidth)) 1239 | 1240 | (condition-case err 1241 | (setq dei--current-bindings (dei--relevant-buffer-bindings)) 1242 | ((error debug) 1243 | (asyncloop-log loop "Problem filtering bindings: %s" (cdr err)) 1244 | (signal (car err) (cdr err)))) 1245 | 1246 | ;; Check for a known problem 1247 | (when (null dei--current-bindings) 1248 | (error (asyncloop-log loop 1249 | "%s %s" "No bindings found, probably an intermittent bug in compiled cl-loop expression in `dei--relevant-buffer-bindings'." 1250 | "Try deleting deianira.elc, or live-evalling that specific defun so it runs uncompiled."))) 1251 | 1252 | ;; Since `dei--relevant-buffer-bindings' returns full keydescs 1253 | ;; only, infer prefixes by cutting the last key off each sequence. 1254 | (setq dei--hydrable-prefixes 1255 | (-uniq (-keep #'massmapper--parent-key 1256 | (-map #'car dei--current-bindings)))) 1257 | 1258 | ;; Add every possible ancestor (count C-c and C-c c as well as C-c c p). 1259 | ;; This variable will be looked up by the hydra-head makers, which I'm 1260 | ;; 80% sure don't need this much info, but it doesn't hurt. It will also 1261 | ;; be used shortly below. 1262 | (setq dei--hydrable-prefixes-with-ancestors 1263 | (-uniq 1264 | (cl-loop 1265 | for key in dei--hydrable-prefixes 1266 | as n = (length (split-string key " ")) 1267 | append (-iterate #'massmapper--parent-key key n)))) 1268 | 1269 | ;; Note that this algo typically gives identical or near-identical 1270 | ;; results to just collecting all parent stems of 1271 | ;; `dei--hydrable-prefixes-with-ancestors'. However, this code better 1272 | ;; expresses what we actually need, so I prefer to keep it like this. 1273 | ;; It does let us skip making a hydra or two sometimes. 1274 | (setq dei--hydrable-stems 1275 | (-uniq 1276 | (-union 1277 | (-keep #'massmapper--prefix-to-stem dei--hydrable-prefixes) 1278 | ;; Check ancestors in case we have to create those hydras too 1279 | (cl-loop 1280 | for prefix in dei--hydrable-prefixes-with-ancestors 1281 | as stem = (massmapper--prefix-to-stem prefix) 1282 | as parent-stem = (massmapper--parent-stem stem) 1283 | unless (dei--connection-exists parent-stem stem) 1284 | collect parent-stem)))) 1285 | 1286 | ;; Figure out which stems have changed, so we can exploit the previous 1287 | ;; flock's work and skip running defhydra for results we know will be 1288 | ;; identical. This has a TREMENDOUS performance boost each time we 1289 | ;; encounter a new keymap combo, cutting 30 seconds of computation down 1290 | ;; to 0-2 seconds. 1291 | 1292 | ;; TODO: have "bindings" include subkeymaps too just to be sure we really 1293 | ;; update. In emacs-lisp-mode, I was getting a Cxn stem that comes from 1294 | ;; org-mode, because I had no equivalent prefix in emacs-lisp-mode. 1295 | ;; Although that issue should not happen if C-x n is bound to a command 1296 | ;; -- the issue there was it was bound to an empty keymap, now fixed. 1297 | ;; Still, it casts light on how this algo really works, and I think I 1298 | ;; need a flowchart before I remove this comment, just to ensure that all 1299 | ;; edge cases will be taken care of. 1300 | 1301 | (setq dei--changed-stems 1302 | (cl-loop 1303 | with case-fold-search = nil 1304 | ;; Visualize a Venn diagram, with two circles for the LAST and 1305 | ;; CURRENT bindings. The defunct bindings are somewhere in LAST, 1306 | ;; the new bindings somewhere in CURRENT, but neither are in the 1307 | ;; circles' intersection, which should never be relevant to update 1308 | ;; as they represent cases where the key's definition is the same 1309 | ;; as in the last keymap combo. 1310 | with new-bindings = (append (-difference dei--current-bindings 1311 | dei--last-bindings) 1312 | (-difference dei--last-bindings 1313 | dei--current-bindings)) 1314 | with new-stems = '() 1315 | ;; TODO: I have a feeling that the whole -connection-exists stuff 1316 | ;; earlier becomes moot here--ancestors don't get rebuilt? 1317 | ;; Reimplement -connection-exists to use keydescs, and use it in 1318 | ;; calculating new-bindings. That may also take care of the other 1319 | ;; todo regarding subkeymaps. 1320 | ;; REVIEW: if ancestors don't get rebuilt, that could be why we 1321 | ;; seem to get wrong hydras for buffer -- just leafs are correct 1322 | for stem in dei--hydrable-stems 1323 | as it = (cl-loop 1324 | for (key . _) in new-bindings 1325 | when (equal stem (massmapper--drop-leaf key)) 1326 | unless (and dei-ignore (string-match-p dei-ignore key)) 1327 | return stem) 1328 | when it collect it)) 1329 | 1330 | ;; Clear the workbench in case of a previous half-done iteration. 1331 | (setq dei--hydra-recipes nil) 1332 | 1333 | (if dei--changed-stems 1334 | (format "%d changed stems: %S" 1335 | (length dei--changed-stems) 1336 | dei--changed-stems) 1337 | (setf (asyncloop-remainder loop) (list t #'dei--step-7-register)) 1338 | "No practical keymap diffs")))) 1339 | 1340 | (defun dei--step-4-write-recipe (loop) 1341 | "Write recipe for the first item of `dei--changed-stems'. 1342 | Specifically, pop a stem off the list `dei--changed-stems', 1343 | transmute it into a recipe, and push that onto the list 1344 | `dei--hydra-recipes'. 1345 | 1346 | What is meant by \"recipe\" is a list of arguments that we 1347 | precompute as much as possible, that we'll later pass to 1348 | `defhydra' in `dei--step-6-birth-hydra'. 1349 | 1350 | Repeatedly add another invocation of this function to the front 1351 | of asyncloop LOOP, so it will run again until 1352 | `dei--changed-stems' empty." 1353 | (unless (dei--abort-if-buffer-killed loop dei--buffer-under-analysis) 1354 | (with-current-buffer dei--buffer-under-analysis 1355 | (if (null dei--changed-stems) 1356 | "All recipes written" 1357 | (let* ((stem (car dei--changed-stems)) 1358 | (name (dei--dub-hydra-from-stem stem)) 1359 | (r1 (dei--specify-hydra stem (concat name "-nonum") t)) 1360 | (r2 (dei--specify-hydra stem name))) 1361 | ;; Side-effects start here 1362 | (push r1 dei--hydra-recipes) 1363 | (push r2 dei--hydra-recipes) 1364 | (push t (asyncloop-remainder loop)) 1365 | (pop dei--changed-stems)))))) 1366 | 1367 | (defun dei--step-5-sort-recipes (loop) 1368 | "Sort to avail most relevant hydras soonest, so the important 1369 | hydras like C- and C-x are among the first to come into 1370 | existence." 1371 | (setq dei--hydra-recipes 1372 | (cl-sort dei--hydra-recipes #'< 1373 | :key (lambda (recipe) 1374 | (length (car recipe))))) 1375 | "Sorted by shortest first") 1376 | 1377 | (defun dei--step-6-birth-hydra (loop) 1378 | "Pass a recipe to `defhydra', wetting what has been a dry-run. 1379 | Each invocation pops one off `dei--hydra-recipes'. 1380 | 1381 | Repeatedly add another invocation of this function to the front 1382 | of asyncloop LOOP, so it will run again until 1383 | `dei--hydra-recipes' empty." 1384 | (unless (dei--abort-if-buffer-killed loop dei--buffer-under-analysis) 1385 | (if (null dei--hydra-recipes) 1386 | "All hydras born" 1387 | ;; Side-effects start here 1388 | (dei--try-birth-hydra (car dei--hydra-recipes)) 1389 | (push t (asyncloop-remainder loop)) 1390 | (car (pop dei--hydra-recipes))))) 1391 | 1392 | (defun dei--step-7-register (loop) 1393 | "Record the hydras made under this keymap combination." 1394 | (let ((flocks (symbol-value (obarray-get dei--hidden-obarray "flocks"))) 1395 | funs 1396 | vars) 1397 | (when (dei--flock-by-hash-and-width 1398 | dei--current-hash dei--current-width flocks) 1399 | (error "Hash already recorded: %s" dei--current-hash)) 1400 | ;; All symbols generated by `defhydra' contain a slash in the name, so just 1401 | ;; collect all such names from the global obarray and call that the current 1402 | ;; flock. 1403 | ;; 1404 | ;; Note that this will also catch syms not used by the current flock, which 1405 | ;; is slightly inefficient as this extra "cream on top" per flock builds up 1406 | ;; the more flocks we make. I expect it won't add up to even one doubling 1407 | ;; of work, so it's fine. The ideal alternative is patching `defhydra' to 1408 | ;; list for us what symbols it set. 1409 | (mapatoms 1410 | (lambda (sym) 1411 | (when (string-match-p "dei-.*?/" (symbol-name sym)) 1412 | (when (fboundp sym) 1413 | (push (cons sym (symbol-function sym)) funs)) 1414 | (when (boundp sym) 1415 | (push (cons sym (symbol-value sym)) vars))))) 1416 | (push (dei--flock-define 1417 | :hash dei--current-hash 1418 | :width dei--current-width 1419 | :funs funs 1420 | :vars vars 1421 | :bindings dei--current-bindings) 1422 | flocks) 1423 | ;; Side-effects start here 1424 | (set (obarray-put dei--hidden-obarray "flocks") flocks) 1425 | (setq dei--last-bindings dei--current-bindings) 1426 | (format "Flock #%d born: %d" (length flocks) dei--current-hash))) 1427 | 1428 | (defun dei--actions-on-interrupt (loop) 1429 | "Stop trying to make hydras if excessive interrupts recently." 1430 | (if (<= dei--interrupts-counter 4) 1431 | (cl-incf dei--interrupts-counter) 1432 | (setq dei--give-up t) 1433 | (asyncloop-cancel loop) 1434 | (display-warning 1435 | 'deianira 1436 | (asyncloop-log loop 1437 | "5 interrupts last 3 min, stopped trying to make hydras! %s" 1438 | "To resume, turn `deianira-mode' off and on.")))) 1439 | 1440 | (defun dei-make-hydras-maybe (&rest _) 1441 | "Maybe make hydras for the current keymap combo." 1442 | (unless (or dei--give-up 1443 | ;; REVIEW: works fine with commenting these out? 1444 | ;;(and (equal dei--buffer-under-analysis (current-buffer)) 1445 | ;; (equal dei--current-width (frame-width))) 1446 | (equal dei--current-hash (abs (sxhash (current-active-maps))))) 1447 | (setq dei--loop 1448 | (asyncloop-run 1449 | (list #'dei--step-1-find-premade 1450 | #'dei--step-2-validate-user-settings 1451 | #'dei--step-3-model-the-world 1452 | #'dei--step-4-write-recipe 1453 | #'dei--step-5-sort-recipes 1454 | #'dei--step-6-birth-hydra 1455 | #'dei--step-7-register) 1456 | :log-buffer-name "*deianira*" 1457 | :immediate-break-on-user-activity t 1458 | :on-interrupt-discovered #'dei--actions-on-interrupt)))) 1459 | 1460 | 1461 | ;;;; Debug toolkit 1462 | 1463 | (defun dei-reset () 1464 | (interactive) 1465 | (asyncloop-reset-all) 1466 | (setq dei--last-bindings nil) 1467 | (obarray-remove dei--hidden-obarray "flocks") 1468 | (message "Note there's a known bug that slows down the hydra maker each reset")) 1469 | 1470 | (provide 'deianira) 1471 | ;;; deianira.el ends here 1472 | --------------------------------------------------------------------------------