├── .dir-locals.el
├── .gitignore
├── LICENSE
├── README.md
├── voicemacs-avy.el
├── voicemacs-base.el
├── voicemacs-command.el
├── voicemacs-correct.el
├── voicemacs-extend-company.el
├── voicemacs-extend-dired.el
├── voicemacs-extend-helm.el
├── voicemacs-it.el
├── voicemacs-lib.el
├── voicemacs-server.el
└── voicemacs.el
/.dir-locals.el:
--------------------------------------------------------------------------------
1 | ((nil . ())
2 | (emacs-lisp-mode . ((eval . (aggressive-indent-mode 1))))
3 | )
4 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.elc
2 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
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.md:
--------------------------------------------------------------------------------
1 | # Voicemacs
2 |
3 | Voicemacs is a set of utilities for controlling Emacs by voice. Voicemacs doesn't add any voice recognition functionality itself - it's a tool that makes Emacs easier to use with an external voice control system, such as [Dragonfly](https://github.com/dictation-toolbox/dragonfly) or [Talon Voice](https://talonvoice.com/).
4 |
5 | Voicemacs allows the voice rec system to call functions & commands remotely, and Voicemacs will send periodic updates with contextual information such as buffer contents, active modes, etc. Voicemacs also extends the functionality of some Emacs packages. For example, candidates in `dired`, `helm` & `company` are numbered and functions are exposed to manipulate them by their numbers, making them easier to navigate by voice. You can autocomplete or select a candidate by speaking its number.
6 |
7 | Many of these features are personal hacks, polished for publishing. I find them robust but they are tailored for my workflow (for example, I only support `helm`, not `ido` or `ivy`). They may not work with your setup.
8 |
9 | ## How Does it Work?
10 |
11 | Voicemacs is very much a work-in-progress. It's not stable or documented. The best way to understand it is probably to look at the client in my [Talon config](https://github.com/jcaw/talon_config/tree/master/emacs/utils), and the source code. Start with `voicemacs-base.el`.
12 |
13 | With that said, here's an overview. The voice recognition software opens a persistent connection to Voicemacs over a TCP socket. Voicemacs uses this connection to send the client information on the state of Emacs as it changes, and the client can use it to send RPC requests. Additional state updates can be easily hooked, if you would like to send more information to your client.
14 |
15 | ## Installation
16 |
17 | Right now, clone the repo directly. You'll have to wire it up yourself, perhaps using the modules from my [Talon config](https://github.com/jcaw/talon_config/tree/master/emacs/utils). This will probably become easier down the line.
18 |
--------------------------------------------------------------------------------
/voicemacs-avy.el:
--------------------------------------------------------------------------------
1 | ;; Commands & infrastructure for doing things with `avy'.
2 |
3 |
4 | (require 'avy)
5 |
6 | (require 'voicemacs-lib)
7 |
8 |
9 | (defvar voicemacs-default-avy-jump-command 'avy-goto-subword-1
10 | "Default jump command to use with `voicemacs-avy-jump'.")
11 |
12 |
13 | ;; FIXME: This prefers {} for the narrowing char. Use something more
14 | ;; comprehensible at the end of the list?
15 | (defvar voicemacs-avy-keys "abcdefghijklmnopqrstuvwxyz'/#:\\-+_!£$*()[]{}"
16 | "Chars to use for Voicemacs avy jumps.
17 |
18 | Note these will not override the default avy jump chars - only
19 | jumps instigated with `voicemacs-avy-jump' will use these
20 | characters.")
21 |
22 |
23 | (defun voicemacs-avy-jump (avy-jump-command &rest avy-command-args)
24 | "Run an avy command, raising an error if the jump fails."
25 | ;; TODO: Maybe expand available symbols?
26 | (let* (
27 | ;; TODO: Is this the right place to ensure we're using old windows?
28 | (avy-all-windows t)
29 | ;; We're using voice, so there is no advantage to restricting to the
30 | ;; home row.
31 | (avy-keys (string-to-list voicemacs-avy-keys))
32 | (result (apply avy-jump-command avy-command-args)))
33 | ;; This means kill commands won't append, they'll create a fresh kill. We
34 | ;; need this because we're doing a non-local kill action, so it shouldn't be
35 | ;; appended. It's also important if we're trying to e.g. duplicate something
36 | ;; with `voicemacs-save-avy-excursion'. We don't restrict this to just
37 | ;; `(eq last-command 'kill-region)' because commands relying on
38 | ;; `last-command' probably assume local behaviour - so disrupt that in all
39 | ;; cases.
40 | (setq last-command nil)
41 | (cond ((eq t result) (error "No candidates found"))
42 | ((not result) (error "Jump cancelled"))
43 | (t result))))
44 |
45 |
46 | (defmacro voicemacs-save-avy-excursion (avy-command &rest body)
47 | "Select location with `avy-command', perform `body', then restore point."
48 | ;; We use save excursion because `avy-pop-mark' doesn't tolerate buffer
49 | ;; changes before point.
50 | `(save-excursion
51 | ,avy-command
52 | ;; FIXME: Max sized ring will lose one element
53 | (voicemacs--first-result (progn ,@body)
54 | (avy-pop-mark))))
55 |
56 |
57 | ;; TODO: Overhaul this + uses, use my new macro
58 | (defmacro voicemacs-avy-pos (avy-command)
59 | "Get the position of a character with Avy.
60 |
61 | Returns a cons cell with the window & position of the match.
62 |
63 | `(window . pos)'"
64 | `(voicemacs-save-avy-excursion
65 | ,avy-command
66 | `((point . ,(point))
67 | (window . ,(selected-window)))))
68 |
69 |
70 | (defmacro voicemacs-defavy (name revert-point-after docstring &rest after-jump-body)
71 | "Define a command that jumps, then iff successful, fires `AFTER-JUMP-BODY'.
72 |
73 | You must provide a docstring for commands defined with this
74 | macro."
75 | (declare (doc-string 3) (indent defun))
76 |
77 | ;; TODO: Optional docstring, intelligently check if one was provided.
78 | `(defun ,name (char)
79 | ,docstring
80 | (interactive (list (read-char "Char: ")))
81 | (,(if revert-point-after 'voicemacs-save-avy-excursion 'progn)
82 | (voicemacs-avy-jump voicemacs-default-avy-jump-command char)
83 | ,@after-jump-body)))
84 |
85 |
86 | (voicemacs-defavy voicemacs-avy-copy nil
87 | "Jump, then copy the `it-thing' at point."
88 | (it-copy-dwim :flash t))
89 |
90 |
91 |
92 |
93 | ;; TODO: Jump back after this? Pad?
94 | (voicemacs-defavy voicemacs-avy-kill nil
95 | "Jump, then kill the `it-thing' at point."
96 | (it-kill-dwim :flash t))
97 |
98 |
99 | (voicemacs-defavy voicemacs-avy-mark nil
100 | "Jump, then mark the `it-thing' at point."
101 | (it-mark-dwim))
102 |
103 |
104 | ;; TODO: Switch to `it' for all flashing?
105 | (voicemacs-defavy voicemacs-avy-yank nil
106 | "Jump, then yank the `it-thing' at point."
107 | (voicemacs-visual-yank :flash t))
108 |
109 |
110 | (defun voicemacs-avy-teleport (char)
111 | (interactive (list (read-char "Char: ")))
112 | ;; TODO: Possible to combine both of these in one undo stage?
113 | (voicemacs-save-avy-excursion
114 | (voicemacs-avy-jump voicemacs-default-avy-jump-command char)
115 | (it-kill-dwim :flash t))
116 | (voicemacs-visual-insert (car kill-ring)))
117 |
118 |
119 | (defun voicemacs-avy-duplicate (char)
120 | (interactive (list (read-char "Char: ")))
121 | ;; TODO: Possible to combine both of these in one undo stage?
122 | (voicemacs-save-avy-excursion
123 | (voicemacs-avy-jump voicemacs-default-avy-jump-command char)
124 | (it-copy-dwim :flash t))
125 | (voicemacs-visual-insert (car kill-ring)))
126 |
127 |
128 |
129 | (defun voicemacs-avy-pad (char)
130 | "Apply `just-one-space' at `CHAR'."
131 | (interactive (list (read-char "Char: ")))
132 | (voicemacs-save-avy-excursion
133 | (voicemacs-avy-jump 'avy-goto-char char)
134 | (just-one-space)))
135 |
136 |
137 | (defun voicemacs--jump-to-string (&optional string)
138 | "Jump to a multiple-char string. Signals an error if the jump fails."
139 | ;; TODO: If only one candidate, jump immediately.
140 | (voicemacs-avy-jump 'avy--generic-jump
141 | (or string (regexp-quote (read-string "String: ")))
142 | nil))
143 |
144 |
145 | (defun voicemacs-avy-kill-word ()
146 | (interactive)
147 | ;; NOTE: The client needs to type fast for this to work.
148 | (voicemacs--jump-to-string)
149 | (it-kill-word))
150 |
151 |
152 | (voicemacs-defavy voicemacs-avy-end-of-word-or-thing (char)
153 | "Jump to the end of the word at `char', or the `it-thing' if not a word."
154 | (goto-char (or (cdr (bounds-of-thing-at-point 'word))
155 | (cdr (it-bounds (it-object-at 'sexp (point))))
156 | (point))))
157 |
158 |
159 | ;; TODO: `voicemacs-avy-join'
160 |
161 |
162 | (provide 'voicemacs-avy)
163 | ;;; voicemacs-avy.el ends here
164 |
--------------------------------------------------------------------------------
/voicemacs-base.el:
--------------------------------------------------------------------------------
1 | (require 'json)
2 | (require 'f)
3 | (require 'voicemacs-server)
4 |
5 |
6 | (defgroup voicemacs nil
7 | "Utilities to make Emacs easier to control by voice."
8 | :prefix "voicemacs-")
9 |
10 |
11 | ;; TODO: Use a set, not a list - more efficient
12 | (defvar voicemacs--exposed-functions '()
13 | "Functions that should be exposed by voicemacs.")
14 |
15 |
16 | (defvar voicemacs--data (make-hash-table :test 'equal)
17 | "Data that should be mirrored to clients.")
18 |
19 |
20 | (defun voicemacs-expose-function (func)
21 | "Expose `FUNC' over the RPC server (when in `voicemacs-mode')."
22 | (unless (member func voicemacs--exposed-functions)
23 | (push func voicemacs--exposed-functions)))
24 |
25 |
26 | (defun voicemacs-remove-function (func)
27 | "Remove a function exposed with `voicemacs-expose-function'."
28 | (setq voicemacs--exposed-functions
29 | (remove func voicemacs--exposed-functions)))
30 |
31 |
32 | (cl-defun voicemacs--queue-once (func &key (args '()) (time 0))
33 | "Queue a function to run once, when Emacs is next idle.
34 |
35 | If the function is already queued, it will be replaced (and the
36 | replacement will use the new timing). Note it will also remove
37 | the function from ordinary timers."
38 | (cancel-function-timers func)
39 | (apply #'run-with-idle-timer (append (list time nil func) args)))
40 |
41 |
42 | (defun voicemacs--equal (item-1 item-2)
43 | "Check equality of two objects - tolerates equivalent hash maps.
44 |
45 | Will raise an error if the items can't be serialized."
46 | (or (equal item-1 item-2)
47 | ;; Check JSON forms so we can tolerate hash maps.
48 | ;;
49 | ;; HACK: JSON comparison as a standin for in-depth compare function.
50 | ;; Replace this at some point.
51 | (string= (json-rpc-server--emulate-legacy-encode item-1)
52 | (json-rpc-server--emulate-legacy-encode item-2))))
53 |
54 |
55 | (defun voicemacs-update-data (key value)
56 | "Update data `key' to be `value', and send the new value to the client."
57 | (puthash key value voicemacs--data)
58 | ;; TODO: Fix circular imports
59 | (voicemacs--broadcast-update key value))
60 |
61 |
62 | (defun voicemacs--update-if-changed (key value)
63 | "Update data under `key', iff `value' is different."
64 | (unless (condition-case nil
65 | (voicemacs--equal value (voicemacs--get-data key))
66 | (wrong-type-argument
67 | ;; HACK: Some strings can't be serialized - if that happens, return
68 | ;; `t' to suppress updates.
69 | t))
70 | (voicemacs-update-data key value)))
71 |
72 |
73 | (defun voicemacs--hash-subset (hash-table keys)
74 | "Get a subset of a hash table with only the keys in `keys'."
75 | (let ((subset (make-hash-table)))
76 | (mapc (lambda (key)
77 | (puthash key (gethash key hash-table) subset))
78 | keys)
79 | subset))
80 |
81 |
82 | (defun voicemacs--get-data (key)
83 | "Get the current value of `key' in `voicemacs--data'."
84 | (gethash key voicemacs--data))
85 |
86 |
87 | (defvar voicemacs--sync-setup-hook '()
88 | "Hook run when voicemacs enables synchronization.
89 |
90 | Don't hook functions to this hook directly - use
91 | `voicemacs--add-sync'.")
92 |
93 |
94 | (defvar voicemacs--sync-teardown-hook '()
95 | "Hook run when voicemacs disables synchronization.
96 |
97 | Don't hook functions to this hook directly - use
98 | `voicemacs--add-sync'.")
99 |
100 |
101 | ;; TODO: Improve documentation
102 | (defun voicemacs--sync-add (setup teardown)
103 | "Add a new data synchronizer to `voicemacs-mode'.
104 |
105 | `SETUP' is the function to run when synchronization is enabled.
106 | `TEARDOWN' is the function to run when synchornization is
107 | disabled.
108 |
109 | Note that if `voicemacs-mode' is active, any previous versions of
110 | `SETUP' will not be torn down. That needs to be done manually
111 | before calling `voicemacs--sync-add'."
112 | ;; Need to fire it manually if `voicemacs-mode' is already active.
113 | (when voicemacs-mode
114 | (funcall setup))
115 | (add-hook 'voicemacs--sync-setup-hook setup)
116 | (add-hook 'voicemacs--sync-teardown-hook teardown))
117 |
118 |
119 | (defun voicemacs--mode-disable ()
120 | "Post-enable hook for `voicemacs-mode'."
121 | (cancel-function-timers 'voicemacs--maybe-restart-server)
122 |
123 | ;; Disable syncing
124 | (run-hooks 'voicemacs--sync-teardown-hook)
125 | ;; Defensive, also free the memory
126 | (clrhash voicemacs--data)
127 |
128 | ;; Now stop the server.
129 | (voicemacs--stop-server)
130 | )
131 |
132 |
133 | (defun voicemacs--maybe-restart-server ()
134 | "If the server is dead (and it shouldn't be), restart it."
135 | (when (and voicemacs-mode
136 | (not voicemacs--server-process))
137 | (message "Voicemacs server has been killed erroneously. Restarting it.")
138 | (voicemacs--start-server)))
139 |
140 |
141 | (defun voicemacs--running-under-wsl ()
142 | "Is this Emacs instance running under Windows Subsystem for Linux?"
143 | (let ((uname (shell-command-to-string "uname -a")))
144 | (and (string-match-p "Linux" uname)
145 | (string-match-p "Microsoft" uname))))
146 |
147 |
148 | (defun voicemacs--mode-enable ()
149 | "Post-disable hook for `voicemacs-mode'."
150 | ;; Start server
151 | (voicemacs--start-server)
152 | (message "Voicemacs server started")
153 | ;; HACK: Some packages kill the server erroneously, e.g. `persp-mode' when it
154 | ;; restores the previous perspective. Don't try and play whack-a-mole with
155 | ;; them, just poll & restart.
156 | (run-with-idle-timer 0.01 0 'voicemacs--maybe-restart-server)
157 |
158 | ;; Setup sync
159 | (clrhash voicemacs--data)
160 | (run-hooks 'voicemacs--sync-setup-hook)
161 |
162 | ;; TODO: Maybe put a signifier that voicemacs is active in the title?
163 | )
164 |
165 |
166 | (defun voicemacs--format-symbol (string-spec &rest args)
167 | "Intern a symbol from a format string."
168 | (intern (apply 'format string-spec args)))
169 |
170 |
171 | (defun voicemacs--define-sync-docstring (string-spec &rest args)
172 | "Create a docstring for a function generated by `voicemacs--define-sync'."
173 | (concat (apply 'format string-spec args)
174 | "\n\n"
175 | "This is an auto-generated function created by `voicemacs-define-sync'."))
176 |
177 |
178 | (cl-defmacro voicemacs-define-sync (key &key
179 | (update 'NOT-PROVIDED)
180 | (enable 'NOT-PROVIDED)
181 | (disable 'NOT-PROVIDED)
182 | (defer t)
183 | (delay nil))
184 | "Register a new `KEY' to synchronize.
185 |
186 | `KEY' should be an unquoted symbol, the key to synchronize.
187 |
188 | This method automatically generates a number of functions that
189 | handle synchronization (and hooks them):
190 |
191 | `voicemacs--sync-' - immediately evaluate a new value for
192 | `KEY', and synchronize it. `:UPDATE' should be a form that will
193 | be evaluated to get the new value.
194 |
195 | `voicemacs--queue-sync-' - queue `voicemacs--sync-' to
196 | fire a single time, once Emacs is idle. This can be used to
197 | defer expensive synchronizations so they only happen once (when
198 | activity has finished).
199 |
200 | `:DEFER' determines which of these is used as the default
201 | synchronization function within the enable & disable
202 | functions (described below). When `:DEFER' is t,
203 | `voicemacs--queue-sync-' will be used. When `:DEFER' is nil,
204 | it's `voicemacs--sync-'.
205 |
206 | `voicemacs--enable-sync-' - enable synchronization of this
207 | key. The `:ENABLE' form will be evaluated in this function to
208 | set up synchronization (e.g. when `voicemacs-mode' is enabled).
209 | For example, you may wish to attach the sync function to a
210 | hook, or add it as advice. Use the variable `sync-func' within
211 | this form to reference the default sync function.
212 |
213 | `voicemacs--disable-sync-' - disable synchronization. The
214 | `:DISABLE' form will be evaluated in this function to disable
215 | synchronization (e.g. when `voicemacs-mode' is disabled). It
216 | should reverse the effects of `voicemacs--enable-sync-'.
217 | Use the variable `sync-func' within this form to reference the
218 | default sync function.
219 |
220 | Pass `:DELAY' (in seconds) to increase the time before a queued
221 | sync fires. `:DELAY' can only be passed when `:DEFER' is t.
222 |
223 | If `voicemacs-mode' is already active, synchronization of this
224 | key will be enabled immediately.
225 |
226 | ---
227 |
228 | Usage examples:
229 |
230 | (voicemacs-define-sync in-comment
231 | :update (if (voicemacs-in-comment-p) t :json-false)
232 | :enable (run-with-idle-timer 0 0 sync-func)
233 | :disable (cancel-function-timers sync-func)
234 | :defer nil)
235 |
236 | (voicemacs-define-sync defined-commands
237 | :update (voicemacs--defined-commands)
238 | :enable (advice-add 'defun :after sync-func)
239 | :disable (advice-remove 'defun sync-func)
240 | :defer t
241 | :delay 1)
242 |
243 | For more examples, see native uses within the `voicemacs'
244 | source."
245 | (declare (indent 1))
246 | ;; Cache expansions
247 | `(let* ((-key (quote ,key))
248 | (-update-form (quote ,update))
249 | (-defer ,defer)
250 | (-enable-form (quote ,enable))
251 | (-disable-form (quote ,disable))
252 | (-delay ,delay))
253 | ;; Validate inputs
254 | (when (member 'NOT-PROVIDED
255 | (list -key -update-form -enable-form -disable-form))
256 | (error "Must provide each of `KEY', `UPDATE', `ENABLE' & `DISABLE'"))
257 | (when (and -delay (not -defer))
258 | (error "`DEFER' must be `t' if a `DELAY' is provided."))
259 | (unless (and (or (symbolp -key) (stringp -key))
260 | (string-match-p "[-a-zA-Z0-9]+" (format "%s" -key)))
261 | ;; Restrict the key format so the client can deal with it easily.
262 | (error "`KEY' may only contain letters, numbers and dashes"))
263 |
264 | ;; Generate function names
265 | (let* ((immediate-sync-func (voicemacs--format-symbol
266 | "voicemacs--sync-%s" -key))
267 | (deferred-sync-func (voicemacs--format-symbol
268 | "voicemacs--queue-sync-%s" -key))
269 | (enable-sync-func (voicemacs--format-symbol
270 | "voicemacs--enable-sync-%s" -key))
271 | (disable-sync-func (voicemacs--format-symbol
272 | "voicemacs--disable-sync-%s" -key))
273 | (sync-action (if -defer deferred-sync-func immediate-sync-func)))
274 | ;; Tear down the previous version of the sync, if necessary
275 | (when (and voicemacs-mode (fboundp disable-sync-func))
276 | (with-demoted-errors "Error reversing previous Voicemacs sync:\n%s"
277 | (funcall disable-sync-func)))
278 |
279 | ;; Define function to sync immediately
280 | (eval `(defun ,immediate-sync-func (&rest _)
281 | ,(voicemacs--define-sync-docstring
282 | (concat "Evaluate & synchronize the state of sync key `%s'."
283 | "\n\nState will only be updated if it has changed.")
284 | -key)
285 | (voicemacs--update-if-changed (quote ,-key) ,-update-form)))
286 | ;; Define function to sync only when idle
287 | (eval `(defun ,deferred-sync-func (&rest _)
288 | ,(voicemacs--define-sync-docstring
289 | "Queue sync of key `%s' once idle." -key)
290 | (voicemacs--queue-once (quote ,immediate-sync-func)
291 | :time (or ,-delay 0))))
292 |
293 | ;; Define functions that set up & tear down syncing
294 | (eval `(defun ,enable-sync-func ()
295 | ,(voicemacs--define-sync-docstring
296 | "Enable synchronization of `%s'" -key)
297 | (let ((sync-func (quote ,sync-action)))
298 | ,-enable-form)
299 | ;; Sync current state up-front. Don't delay because if
300 | ;; `ENABLE-FORM' set up e.g. a repeating idle timer, a delay
301 | ;; could interfere.
302 | (,immediate-sync-func)))
303 | (eval `(defun ,disable-sync-func ()
304 | ,(voicemacs--define-sync-docstring
305 | "Disable synchronization of `%s'" -key)
306 | ;; TODO: Reset data here? Is it reset somewhere else?
307 | (let ((sync-func (quote ,sync-action)))
308 | ,-disable-form)))
309 |
310 | ;; Finally, register the generated setup & teardown functions
311 | (voicemacs--sync-add enable-sync-func disable-sync-func))))
312 |
313 |
314 | (cl-defmacro voicemacs-define-sync-change-buffer (key &key
315 | (update 'NOT-PROVIDED)
316 | (defer t)
317 | (delay nil))
318 | "Add a data key that synchronizes on buffer change.
319 |
320 | Like `voicemacs-define-sync', but `:enable' and `:disable' are
321 | handled for you - they will bind `sync-func' to a buffer change.
322 | See `voicemacs-define-sync' for documentation on the remaining
323 | parameters."
324 | (declare (indent 1))
325 | `(voicemacs-define-sync ,key
326 | :update ,update
327 | :enable (voicemacs--hook-change-buffer sync-func)
328 | :disable (voicemacs--unhook-change-buffer sync-func)
329 | :defer ,defer
330 | :delay ,delay))
331 |
332 |
333 | (define-minor-mode voicemacs-mode
334 | "Minor mode to allow voice recognition software to communicate with Emacs."
335 | :group 'voicemacs
336 | :global t
337 | :lighter nil
338 | :after-hook (if voicemacs-mode
339 | (voicemacs--mode-enable)
340 | (voicemacs--mode-disable)))
341 |
342 |
343 | (defun voicemacs--hook-change-buffer (func)
344 | "Hook a function to fire whenever the active buffer changes.
345 |
346 | This includes switching windows.
347 |
348 | There's no built-in hook for this so the current implementation
349 | is a heuristic. It has a huge false-positive rate; `func' will
350 | fire often, even if the buffer hasn't changed. Don't hook slow
351 | functions."
352 | ;; TODO: Observe buffer changes more directly, these are dodgy heuristics.
353 | ;; TODO: Maybe hook buffer change? Have a look at it. Idle might be enough.
354 | (add-hook 'after-change-major-mode-hook func)
355 | ;; This is a reasonable proxy for when we're switching the buffer.
356 | (add-hook 'post-command-hook func)
357 | ;; Run it idly to catch events that fall through the net.
358 | (run-with-idle-timer 1 0 func))
359 |
360 |
361 | (defun voicemacs--unhook-change-buffer (func)
362 | "Unhook a function that was hooked with `voicemacs--hook-change-buffer'."
363 | (remove-hook 'after-change-major-mode-hook func)
364 | (remove-hook 'post-command-hook func)
365 | (cancel-function-timers func))
366 |
367 |
368 | (defvar voicemacs--digits-so-far ""
369 | "The digits that have been pressed so far in the current numeric key sequence.
370 |
371 | This is only used with `TODO: when key accumulation active'.")
372 |
373 |
374 | (defconst voicemacs--process-digit-commands '()
375 | "All the digit processing command symbols.")
376 |
377 |
378 | (defun voicemacs-bind-cumulative-number-commands (mode-prefix move-function keymap)
379 | "Make basic number keypresses select items in a voicemacs number selection context.
380 |
381 | This tracks digit keypresses and creates commands to handle the
382 | overall number entered, which are bound in `keymap'. Each
383 | keypress, `move-function' is called on the raw number."
384 | (cl-assert (symbolp move-function))
385 | (dotimes (n 10) ; 0-9
386 | (eval
387 | `(let* ((n-str (format "%s" ,n))
388 | (command-symbol (intern (s-concat "voicemacs-" mode-prefix "-process-digit-" n-str))))
389 | (eval
390 | `(progn
391 | (defun ,command-symbol ()
392 | ,(format "Process the digit %s as a quickmove command in %s." mode-prefix n-str)
393 | (interactive)
394 | (unless (member last-command voicemacs--process-digit-commands)
395 | (setq voicemacs--digits-so-far ""))
396 | (setq voicemacs--digits-so-far (s-concat voicemacs--digits-so-far ,n-str))
397 | (condition-case err
398 | (apply #',move-function (list (string-to-number voicemacs--digits-so-far)))
399 | (error
400 | ;; If there's no valid target, we restart the sequence. This is a
401 | ;; convenience feature so the user doesn't always need to tap a
402 | ;; different key to restart the sequence.
403 | (message "Error moving to target")
404 | (setq voicemacs--digits-so-far "")
405 |
406 | (apply #',move-function (list ,n))
407 |
408 | ;; Note we only store the digit as part of the list if it succeeded. Otherwise, all subsequent movements will fail.
409 | (setq voicemacs--digits-so-far ,n-str))))
410 |
411 | (add-to-list 'voicemacs--process-digit-commands ',command-symbol)
412 |
413 | (bind-key ,n-str #',command-symbol ',keymap)
414 | ;; TODO: Possibly also bind the prefixed number to act as the ordinary number command.
415 | )
416 | t))
417 | t))
418 | )
419 |
420 |
421 |
422 |
423 |
424 | (provide 'voicemacs-base)
425 | ;;; voicemacs-base.el ends here
426 |
--------------------------------------------------------------------------------
/voicemacs-command.el:
--------------------------------------------------------------------------------
1 | ;; This module allows the user to inject commands into the command loop.
2 | ;;
3 | ;; It should be used to execute named, interactive commands via RPC. Command
4 | ;; invoked this way will be treated very similarly to if they had been invoked
5 | ;; via keyboard input - this means they'll work in macros, etc.
6 |
7 |
8 | (require 'bind-key)
9 | (require 'voicemacs-base)
10 |
11 |
12 | (defun voicemacs-inject-command (command-name &optional prefix-arg)
13 | "Execute a command as though it were executed via keyboard input.
14 |
15 | This function uses emulation techniques to make the command
16 | behave as much like a keyboard command as possible, down to
17 | injection into the event loop. Using this method, the command can
18 | be smoothly included in Macros, executed after existing commands
19 | in the queue, etc. This also causes errors to be reported in a
20 | similar manner to normal commands (rather than in the network
21 | process filter).
22 |
23 | It is important that RPC-based voice commands are
24 | indistinguishable (from the user's perspective) from commands
25 | injected via keyboard input. They may well be mixed by the
26 | client.
27 |
28 | Arguments:
29 |
30 | `COMMAND-NAME' - The name of the command, as a string.
31 |
32 | `PREFIX-ARG' - Optional. Prefix argument to add to the command."
33 | ;; TODO: Does this need to be run on a proxy with an idle timer?
34 | (let ((command-symbol (if (symbolp command-name)
35 | command-name
36 | ;; Assume it's a string, intern it.
37 | (condition-case nil
38 | (intern command-name)
39 | (error "Could not intern \"%s\" as a symbol." command-name)))))
40 | (unless (commandp command-symbol)
41 | (error "`%s' is not a recognized interactive command." command-symbol))
42 |
43 | (unless (or (integerp prefix-arg)
44 | ;; Prefix arguments might look like '(4) or '(16)
45 | (and (listp prefix-arg)
46 | (eq 1 (length prefix-arg))
47 | (integerp (car prefix-arg)))
48 | (equal prefix-arg "-")
49 | ;; Also allow no prefix argument.
50 | (eq prefix-arg nil))
51 | (error (format
52 | "Prefix arguments may only be numbers, a list such as '(16) or a dash. Was: %s, type: %s"
53 | prefix-arg
54 | (type-of prefix-arg))))
55 | (voicemacs--inject-command command-symbol prefix-arg)
56 | ;; The return value doesn't really matter.
57 | "Command injected successfully."))
58 |
59 |
60 | (defun voicemacs--inject-command (command &optional prefix-arg)
61 | "Inject a command into the event loop."
62 | (voicemacs--inject-event
63 | (voicemacs--create-command-event command prefix-arg)))
64 |
65 |
66 | (defun voicemacs--create-command-event (command &optional prefix-arg)
67 | "Create a command emulation event.
68 |
69 | This event can be injected into the event loop to run an
70 | interactive command, as if it was called by a keypress."
71 | (voicemacs--create-event 'voicemacs-command-signal command prefix-arg))
72 |
73 |
74 | (defun voicemacs--inject-event (event)
75 | "Inject an event into the command loop (at the chronological end)."
76 | ;; TODO: Check this definitely adds it to the end
77 | (setq unread-command-events (cons event unread-command-events)))
78 |
79 |
80 | (defun voicemacs--create-event (signal-type &rest data)
81 | "Create a signal with some optional `DATA'.
82 |
83 | Arguments:
84 |
85 | `SIGNAL-TYPE' - a symbol. You can think of it as the type of
86 | event we're injecting. This signal should be bound to some kind
87 | of event handler by binding it as you would a keychord.
88 |
89 | `DATA' - the data to send."
90 | (cons signal-type data))
91 |
92 |
93 | (defun voicemacs--multiple-cursors-manual-injection (emulated-command)
94 | "Hack to trick `multiple-cursors-mode' into running an emulated command.
95 |
96 | Without this `multiple-cursors-mode' will fall over when applying
97 | our command to secondary cursors, because it tries to repeat
98 | `voicemacs--command-event-handler', not the command we're
99 | emulating. This happens because it stores the original command
100 | during the `pre-command-hook', which is run automatically by the
101 | signal handler.
102 |
103 | To get around this we ignore `voicemacs--command-event-handler'
104 | and manually make it store the command we're emulating. The
105 | normal `post-command-hook' will then trigger that instead. Hairy
106 | hack, but it's also precise with any hacks here to avoid
107 | second-order effects."
108 | (when (and (bound-and-true-p multiple-cursors-mode)
109 | (functionp 'mc/make-a-note-of-the-command-being-run))
110 | (let ((this-original-command emulated-command))
111 | (mc/make-a-note-of-the-command-being-run))))
112 |
113 |
114 | ;;;###autoload
115 | (with-eval-after-load 'multiple-cursors-core
116 | ;; HACK: Multiple cursors should never try and repeat the command signal -
117 | ;; instead we manually inject the emulated command. To do this we force it
118 | ;; to ignore our signal.
119 |
120 | ;; Note we demote errors so Voicemacs doesn't fall over completely if the
121 | ;; patch stops working.
122 |
123 | (defun voicemacs--patch-mc-lists (&rest _)
124 | "Remove the command signal from the multiple cursors lists."
125 | (with-demoted-errors "`voicemacs' error patching `multiple-cursors': %s"
126 | (add-to-list 'mc/cmds-to-run-once 'voicemacs--command-event-handler)
127 | ;; In case the user had it stored in the wrong place.
128 | (setq mc/cmds-to-run-for-all (remove 'voicemacs--command-event-handler
129 | mc/cmds-to-run-for-all))))
130 | (with-demoted-errors "`voicemacs' error patching `multiple-cursors': %s"
131 | (voicemacs--patch-mc-lists)
132 | ;; The list file can be lazy-loaded, so re-apply the patch then.
133 | (advice-add 'mc/load-lists :after 'voicemacs--patch-mc-lists)))
134 |
135 |
136 | (defun voicemacs--command-event-handler ()
137 | "Handle a command emulation event.
138 |
139 | This is made interactive so it can be bound to a signal - you
140 | shouldn't call it yourself via `M-x' (or bind it to an actual
141 | key)."
142 | (interactive)
143 | (let* ((command-event-data (cdr (aref (this-command-keys-vector) 0)))
144 | (command-name (nth 0 command-event-data))
145 | (prefix-arg (nth 1 command-event-data))
146 | ;; This is an RPC command. The user doesn't need to know the keyboard
147 | ;; shortcut, it's annoying.
148 | (suggest-key-bindings nil))
149 | ;; HACK: Compatibility with `multiple-cursors-mode'.
150 | (voicemacs--multiple-cursors-manual-injection
151 | command-name)
152 |
153 | ;; Usually this shouldn't be called from Elisp code, but we want Emacs to
154 | ;; treat this as a normal command as much as possible.
155 | (execute-extended-command prefix-arg (format "%s" command-name))))
156 |
157 |
158 | ;; In order to have voice commands act as normal commands, we bind a signal.
159 | ;;
160 | ;; We use `override-global-map' from `bind-key' to ensure this is always bound,
161 | ;; even in modes that unbind other keys. We aren't actually binding a key here -
162 | ;; we're binding a custom signal, which we'll emit manually.
163 | (define-key override-global-map [voicemacs-command-signal] 'voicemacs--command-event-handler)
164 |
165 |
166 | ;; Ensure this command is callable via RPC
167 | (voicemacs-expose-function 'voicemacs-inject-command)
168 |
169 |
170 | (provide 'voicemacs-command)
171 | ;;; voicemacs-command.el ends here
172 |
--------------------------------------------------------------------------------
/voicemacs-correct.el:
--------------------------------------------------------------------------------
1 | (require 'voicemacs-avy)
2 |
3 |
4 | (defun voicemacs--bounds-of-subword-at-pos (pos)
5 | (save-excursion
6 | (goto-char pos)
7 | ;; FIXME: Make this always act on subwords irrespective of subword-mode.
8 | (or (bounds-of-thing-at-point 'word)
9 | (error "No word at pos: %s" pos))))
10 |
11 |
12 | (defun voicemacs--correct-words (word1-pos word2-pos)
13 | "Correct words from `word1-pos' to `word2-pos'."
14 | (let ((word1-start (car (voicemacs--bounds-of-subword-at-pos word1-pos)))
15 | (word2-end (cdr (voicemacs--bounds-of-subword-at-pos word2-pos))))
16 | (voicemacs-flash (cons word1-start word2-end))
17 | (goto-char word1-start)
18 | ;; TODO: Prompt for correction? Maybe with helm prompt?
19 | (kill-region word1-start word2-end)))
20 |
21 |
22 | (defun voicemacs-correct-words-avy (word1-start-char word2-start-char)
23 | "Correct all words between two words, identified by character."
24 | (interactive (list (read-char "First word start char: ")
25 | (read-char "Second word start char: ")))
26 | (let* ((word1-pos (voicemacs-avy-pos (avy-goto-subword-1 word1-start-char)))
27 | (word2-pos (voicemacs-avy-pos (avy-goto-subword-1 word2-start-char)))
28 | (word1-window (alist-get 'window word1-pos)))
29 | ;; Check both matches are in the same window
30 | (unless (eq word1-window (alist-get 'window word2-pos))
31 | (error "Both matches must be in the same window."))
32 | (select-window word1-window)
33 | (voicemacs--correct-words (alist-get 'point word1-pos)
34 | (alist-get 'point word2-pos))))
35 |
36 |
37 | (defun voicemacs-correct-n-words-avy (n-words first-char)
38 | "Correct n words after a character with avy."
39 | (interactive (list (or current-prefix-arg 1)
40 | (read-char "First char: ")))
41 | (voicemacs-avy-jump 'avy-goto-subword-1 first-char)
42 | (voicemacs--correct-words
43 | (point)
44 | (save-excursion
45 | (forward-word n-words)
46 | (point))))
47 |
48 |
49 | (provide 'voicemacs-correct)
50 | ;;; voicemacs-correct.el ends here
51 |
--------------------------------------------------------------------------------
/voicemacs-extend-company.el:
--------------------------------------------------------------------------------
1 | (require 'company)
2 | (require 'company-quickhelp)
3 | (require 'cl)
4 | (require 'el-patch)
5 |
6 | (require 'voicemacs-base)
7 | (require 'voicemacs-lib)
8 |
9 |
10 | ;; TODO: Maybe remove? Might be useful as an exposed method but not using it to
11 | ;; sync.
12 | (defun voicemacs-company-prompt-open? ()
13 | "Is the company prompt open?"
14 | (bound-and-true-p company-candidates))
15 |
16 |
17 | (defconst voicemacs--company-prompt-key 'company-prompt-open
18 | "Voicemacs sync key to indicate whether the company prompt is open.")
19 |
20 |
21 | (defun voicemacs--update-company-prompt-t (&rest _)
22 | (voicemacs--update-if-changed voicemacs--company-prompt-key t))
23 |
24 |
25 | (defun voicemacs--update-company-prompt-false (&rest _)
26 | (voicemacs--update-if-changed voicemacs--company-prompt-key :json-false))
27 |
28 |
29 | (defun voicemacs--enable-sync-company-prompt ()
30 | (add-hook 'company-completion-started-hook 'voicemacs--update-company-prompt-t)
31 | (add-hook 'company-after-completion-hook 'voicemacs--update-company-prompt-false)
32 | ;; Sync current state immediately.
33 | (company-cancel)
34 | (voicemacs--update-company-prompt-false))
35 |
36 |
37 | (defun voicemacs--disable-sync-company-prompt ()
38 | (remove-hook 'company-completion-started-hook 'voicemacs--update-company-prompt-t)
39 | (remove-hook 'company-after-completion-hook 'voicemacs--update-company-prompt-false)
40 | (voicemacs--update-if-changed voicemacs--company-prompt-key :json-null))
41 |
42 |
43 | ;; This doesn't use the `it-define-sync' macro because it doesn't use a single
44 | ;; sync func.
45 | (voicemacs--sync-add 'voicemacs--enable-sync-company-prompt
46 | 'voicemacs--disable-sync-company-prompt)
47 |
48 |
49 | (defun voicemacs-company-highlight (number)
50 | "Move selection to a numbered company candidate."
51 | (interactive "p")
52 | (if (called-interactively-p 'any)
53 | (company-set-selection (+ company-tooltip-offset (- number 1)) t)
54 | ;; HACK: `company-set-selection' has to be called interactively, or the
55 | ;; selection won't show visually.
56 | (let ((current-prefix-arg number))
57 | ;; FIXME: This trick no longer works everywhere.
58 | (call-interactively 'voicemacs-company-highlight))))
59 |
60 |
61 | (defun voicemacs-company-pop-doc (number)
62 | "Show the `company-quickdoc' for a numbered candidate."
63 | (interactive "p")
64 | (voicemacs-company-highlight number)
65 | (company-quickhelp--show))
66 |
67 |
68 | (defun voicemacs-company-complete (number)
69 | "Insert a company candidate by `NUMBER'.
70 |
71 | Like `company-complete-number', but gives visual feedback."
72 | (interactive "p")
73 | (voicemacs-company-highlight number)
74 | ;; Briefly hold with the candidate highlighted for visual feedback
75 | (sit-for 0.1)
76 | (company-complete))
77 |
78 |
79 | (voicemacs-expose-function 'voicemacs-company-highlight)
80 | (voicemacs-expose-function 'voicemacs-company-complete)
81 | (voicemacs-expose-function 'voicemacs-company-pop-doc)
82 |
83 |
84 | (defvar voicemacs--current-company-number 1
85 | "The number of the last listed company candidate.")
86 |
87 |
88 | ;; TODO: PR `company-mode' for this functionality
89 | (defun voicemacs-company-fill-propertize (original-function
90 | &optional value annotation
91 | width selected left right)
92 | "Intercept `company-fill-propertize' to number more candidates."
93 | ;; This is hard-coded to format correctly only with numbers up to double
94 | ;; digits.
95 | (when (and company-show-numbers
96 | ;; It'll crash if we try and put an empty `right' through this process
97 | right
98 | ;; Number display method is different in company mode - we handle it elsewhere
99 | (not (bound-and-true-p company-box-mode)))
100 | (let ((original-number (string-to-number right)))
101 | ;; Get the new number
102 | (if (= 1 original-number)
103 | (setq voicemacs--current-company-number 1)
104 | (cl-incf voicemacs--current-company-number))
105 | ;; Segments that were un-numbered need to be narrowed to stop the prompt
106 | ;; distorting.
107 | (when (and (= original-number 0)
108 | (not (= voicemacs--current-company-number 10)))
109 | (cl-decf width 2))
110 | ;; FIXME: cuts off last char of completion.
111 | (cl-decf width)
112 | ;; Create our own numbering and spacing
113 | (setq right (concat (voicemacs--pad-string (number-to-string
114 | voicemacs--current-company-number)
115 | 3)
116 | (company-space-string company-tooltip-margin)))))
117 | (funcall original-function value annotation width selected left right))
118 |
119 |
120 | (defvar voicemacs--company-original-show-numbers nil
121 | "Stores the original value of `company-show-numbers'.
122 |
123 | Used to store the value before
124 | `voicemacs-company-more-numbers-mode' was activated, so it can be
125 | restored when the mode is deactivated.")
126 |
127 |
128 | (defun voicemacs--company-numbers-setup ()
129 | "Teardown for `voicemacs-company-more-numbers-mode'."
130 | (setq voicemacs--company-original-show-numbers (default-value company-show-quick-access))
131 | (setq-default company-show-quick-access t)
132 | (advice-add 'company-fill-propertize :around 'voicemacs-company-fill-propertize))
133 |
134 |
135 | (defun voicemacs--company-numbers-teardown ()
136 | "Teardown for `voicemacs-company-more-numbers-mode'."
137 | (setq-default company-show-quick-access voicemacs--company-original-show-numbers)
138 | (advice-remove 'company-fill-propertize 'voicemacs-company-fill-propertize))
139 |
140 |
141 | (define-minor-mode voicemacs-company-more-numbers-mode
142 | "Hacks Company to number more than the first 10 candidates."
143 | :group 'voicemacs
144 | :global t
145 | :lighter nil
146 | :after-hook (if voicemacs-company-more-numbers-mode
147 | (voicemacs--company-numbers-setup)
148 | (voicemacs--company-numbers-teardown)))
149 |
150 |
151 | (el-patch-feature company-box)
152 | (with-eval-after-load 'company-box
153 | ;; HACK: Outright redefine how company box shows numbers to allow numbers greater than 0-9
154 | ;; (el-patch-defun company-box--update-numbers (start)
155 | ;; (let ((side (if (eq company-show-quick-access 'left) 'left-margin 'right-margin))
156 |
157 | ;; (inhibit-redisplay t)
158 | ;; (inhibit-modification-hooks t))
159 | ;; (company-box--remove-numbers side)
160 | ;; (dotimes (index company-box-max-candidates)
161 | ;; (-some--> start
162 | ;; (if (get-text-property it 'company-box--number-pos)
163 | ;; it
164 | ;; (next-single-property-change it 'company-box--number-pos))
165 | ;; (progn
166 | ;; (push it company-box--numbers-pos)
167 | ;; (setq start (1+ it)))
168 | ;; (put-text-property (1- it) it 'display `((margin ,side) ,(int-to-string (1+ index))))))))
169 | (el-patch-defun company-box--update-numbers (start)
170 | (let ((side (if (eq company-show-quick-access 'left) 'left-margin 'right-margin))
171 | (el-patch-remove (offset (if (eq company-show-quick-access 'left) 0 10)))
172 | (inhibit-redisplay t)
173 | (inhibit-modification-hooks t))
174 | (company-box--remove-numbers side)
175 | (dotimes (index (el-patch-swap 10 company-box-max-candidates))
176 | (-some--> start
177 | (if (get-text-property it 'company-box--number-pos)
178 | it
179 | (next-single-property-change it 'company-box--number-pos))
180 | (progn
181 | (push it company-box--numbers-pos)
182 | (setq start (1+ it)))
183 | (put-text-property (1- it) it 'display `((margin ,side) ,(el-patch-swap (aref company-box--numbers (+ index offset))
184 | (int-to-string (1+ index)))))))))
185 | )
186 |
187 |
188 | ;; FIXME: This doesn't error when you hit an invalid number, so the numbers don't auto-reset.
189 | (voicemacs-bind-cumulative-number-commands "company" #'voicemacs-company-highlight 'company-active-map)
190 |
191 |
192 | ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
193 |
194 |
195 | (defun voicemacs-company-apply-recommended-defaults ()
196 | "Apply recommended default settings for `company-mode'."
197 | (setq-default company-show-numbers t
198 | company-tooltip-limit 30
199 | company-minimum-prefix-length 1))
200 |
201 |
202 | (provide 'voicemacs-extend-company)
203 | ;;; voicemacs-extend-company ends here
204 |
--------------------------------------------------------------------------------
/voicemacs-extend-dired.el:
--------------------------------------------------------------------------------
1 | (require 'dired)
2 | (require 'cl)
3 |
4 | (require 'voicemacs-lib)
5 | (require 'voicemacs-base)
6 |
7 |
8 | (defvar-local voicemacs--dired-number-overlays '()
9 | "A list of currently active Dired number overlays")
10 |
11 |
12 | (defface voicemacs-dired-numbers-face
13 | ;; '((t :inherit 'font-lock-keyword-face))
14 | ;; '((t :inherit 'font-lock-variable-name-face))
15 | '((t :inherit 'font-lock-type-face))
16 | "Face used for Dired selection numbers.")
17 |
18 |
19 | (defun voicemacs--dired-remove-overlays ()
20 | "Remove all overlays in the current buffer."
21 | (mapc 'delete-overlay voicemacs--dired-number-overlays)
22 | (setq voicemacs--dired-number-overlays '()))
23 |
24 |
25 | (defun voicemacs--dired-insert-number-overlay (number max-width)
26 | "Insert a single number overlay at the current position."
27 | (let ((overlay (make-overlay (point) (point))))
28 | ;; Add this property so we can find the candidate by number later.
29 | (overlay-put overlay 'number-value number)
30 | (overlay-put
31 | overlay
32 | 'after-string
33 | (propertize (concat (voicemacs--pad-string (number-to-string number)
34 | max-width)
35 | " ")
36 | 'face
37 | '(voicemacs-dired-numbers-face default)))
38 | (push overlay voicemacs--dired-number-overlays)))
39 |
40 |
41 | (defun voicemacs--dired-establish-width ()
42 | "Determine the maximum width needed for numbers."
43 | (save-excursion
44 | (goto-char 0)
45 | (let ((num-files 0))
46 | (while (zerop (forward-line))
47 | ;; We only want to label files & directories - not other lines.
48 | (when (dired-move-to-filename)
49 | (cl-incf num-files)))
50 | (length (number-to-string num-files)))))
51 |
52 |
53 | (defun voicemacs--dired-insert-numbers (&rest _)
54 | "Number all candidates in the current buffer.
55 |
56 | Resets numbers if they already exist. Will only work in Dired
57 | buffers."
58 | (voicemacs--dired-remove-overlays)
59 | (let ((max-number-width (voicemacs--dired-establish-width)) ;; TODO: Find this dynamically?
60 | (current-number 1))
61 | (save-excursion
62 | (goto-char 0)
63 | ;; Forward-line returns 1 if it fails, 0 if it succeeds.
64 | (while (zerop (forward-line))
65 | ;; We only want to label files & directories - not the lines before.
66 | ;;
67 | ;; `dired-move-to-filename' will be truthy iff there's a file on the
68 | ;; line. (This also moves the point to the right position to insert
69 | ;; the number.)
70 | (when (dired-move-to-filename)
71 | (voicemacs--dired-insert-number-overlay
72 | current-number max-number-width)
73 | (cl-incf current-number))))))
74 |
75 |
76 | ;; TODO: Could make this more functional
77 | (defun voicemacs--move-to-dired-item (number)
78 | "Move to a numbered dired item.
79 |
80 | `NUMBER' - the number of the item."
81 | (cl-assert (and (integerp number) (>= number 1)) t)
82 | (unless voicemacs--dired-number-overlays
83 | (error "No numbered dired candidates available."))
84 | (catch 'item-found
85 | (mapc (lambda (overlay)
86 | (when (eq (overlay-get overlay 'number-value) number)
87 | (goto-char (overlay-start overlay))
88 | (dired-move-to-filename)
89 | (throw 'item-found t)))
90 | voicemacs--dired-number-overlays)
91 | (error (format "Dired item with number `%s' was not found." number))))
92 |
93 |
94 | (defun voicemacs-dired-handle-return (&optional prefix)
95 | (interactive "P")
96 | ;; Causes weird hangs if we try to find the file in the same action, so it's disabled for now.
97 | (if prefix
98 | (voicemacs--move-to-dired-item prefix)
99 | (call-interactively #'dired-find-file)))
100 |
101 |
102 | (defun voicemacs-dired-handle-tab (&optional prefix)
103 | (if prefix
104 | (voicemacs--move-to-dired-item prefix)
105 | (call-interactively #'indent-for-tab-command)))
106 |
107 |
108 | (defun voicemacs-dired-move-to-item (&optional item-number)
109 | "Move cursor to a numbered item in the dired buffer."
110 | (interactive "P")
111 | (cl-assert (eq major-mode 'dired-mode))
112 | (voicemacs--move-to-dired-item item-number)
113 | ;; Ensure the move is shown to the user immediately.
114 | (redisplay t)
115 | ;; Dired does not respond to subsequent commands if they come too quickly, so
116 | ;; we sleep and redisplay.
117 | ;;
118 | ;; TODO: This might be a Windows-only issue.
119 | (sleep-for 0.1)
120 | (redisplay t))
121 |
122 |
123 | (voicemacs-expose-function #'voicemacs-dired-move-to-item)
124 |
125 |
126 | (defmacro voicemacs--dired-mapc (&rest body)
127 | "Run `BODY' within every dired buffer in turn."
128 | `(mapc (lambda (buffer)
129 | (with-current-buffer buffer
130 | (when (eq major-mode 'dired-mode)
131 | ,@body)))
132 | (buffer-list)))
133 |
134 |
135 | (defun voicemacs--dired-renumber-buffer (buffer)
136 | "Insert numbers into a specific `BUFFER'."
137 | (when (bufferp buffer)
138 | (with-current-buffer buffer
139 | (voicemacs--dired-insert-numbers))))
140 |
141 |
142 | (defun voicemacs--dired-queue-renumber ()
143 | "Queue a renumbering of the current buffer.
144 |
145 | Defer to avoid duplicating work, and for compatibility with
146 | certain dired rendering schemes (e.g. Doom Emacs hides \".\" &
147 | \"..\" after candidates are inserted, but that won't remove their
148 | number overlays)."
149 | (voicemacs--queue-once #'voicemacs--dired-renumber-buffer
150 | :args (list (current-buffer))))
151 |
152 |
153 | (defun voicemacs--dired-numbers-mode-setup ()
154 | (add-hook 'dired-after-readin-hook #'voicemacs--dired-queue-renumber)
155 | (voicemacs--dired-mapc
156 | (voicemacs--dired-insert-numbers))
157 | ;; Make it easier to jump to the numbers with keyboard.
158 | ;; FIXME: This rebind will be permanent. Make it enable/disable predictably.
159 | (define-key dired-mode-map (kbd "RET") #'voicemacs-dired-handle-return)
160 | (define-key dired-mode-map (kbd "TAB") #'voicemacs-dired-handle-tab))
161 |
162 |
163 | (defun voicemacs--dired-numbers-mode-teardown ()
164 | (remove-hook 'dired-after-readin-hook #'voicemacs--dired-queue-renumber)
165 | (voicemacs--dired-mapc
166 | (voicemacs--dired-remove-overlays)))
167 |
168 |
169 | (define-minor-mode voicemacs-dired-numbers-mode
170 | "When active, `dired' candidates will be numbered."
171 | :group 'voicemacs
172 | :global t
173 | :lighter nil
174 | :after-hook (if voicemacs-dired-numbers-mode
175 | (voicemacs--dired-numbers-mode-setup)
176 | (voicemacs--dired-numbers-mode-teardown)))
177 |
178 |
179 | (voicemacs-bind-cumulative-number-commands "dired" #'voicemacs-dired-move-to-item 'dired-mode-map)
180 |
181 |
182 | (provide 'voicemacs-extend-dired)
183 | ;;; voicemacs-extend-dired.el ends here
184 |
--------------------------------------------------------------------------------
/voicemacs-extend-helm.el:
--------------------------------------------------------------------------------
1 | (require 'helm)
2 |
3 | (require 'voicemacs-base)
4 |
5 |
6 | ;; TODO: Maybe check the nature of the current buffer? This seems janky.
7 | ;;
8 | ;; (eq (current-buffer)
9 | ;; (with-helm-buffer (ignore-errors
10 | ;; (current-buffer))))
11 | (voicemacs-define-sync-change-buffer in-helm-prompt
12 | :update (bound-and-true-p helm-alive-p)
13 | :defer nil)
14 |
15 |
16 | ;; The minibuffer prompt for the current helm session
17 | ;; (voicemacs-define-sync-change-buffer helm-prompt-text
18 | ;; :update (and (bound-and-true-p helm-alive-p) helm--prompt)
19 | ;; :defer nil)
20 |
21 |
22 | ;; The name of the current helm buffer
23 | (voicemacs-define-sync-change-buffer helm-buffer-name
24 | :update (and (bound-and-true-p helm-alive-p)
25 | helm-last-buffer)
26 | :defer nil)
27 |
28 |
29 | ;; Hacky. Might not work.
30 | (voicemacs-define-sync-change-buffer helm-title
31 | :update (when (bound-and-true-p helm-alive-p)
32 | (with-helm-buffer
33 | (buffer-substring-no-properties (line-beginning-position 0)
34 | (line-end-position 0))))
35 | :defer nil)
36 |
37 |
38 | (defun voicemacs--helm-line-number ()
39 | "Line number of the current candidate."
40 | (with-helm-buffer (line-number-at-pos)))
41 |
42 |
43 | (defun voicemacs-helm-goto-line (line &optional do-not-restore)
44 | "Go to the candidate on `line'.
45 |
46 | `do-not-restore' is used for internal purposes. It suppresses
47 | infinite loops on a recursive call."
48 | ;; TODO: This structure is gross. Rewrite it.
49 | (let ((start-line (voicemacs--helm-line-number)))
50 | (helm-beginning-of-buffer)
51 | (let ((last-line (voicemacs--helm-line-number)))
52 | (while (< (voicemacs--helm-line-number) line)
53 | (helm-next-line)
54 | (when (= (voicemacs--helm-line-number) last-line)
55 | ;; No more candidates - restore original selection.
56 | (unless do-not-restore
57 | (voicemacs-helm-goto-line start-line t))
58 | (error "Candidate does not exist"))
59 | (setq last-line (voicemacs--helm-line-number)))))
60 | ;; Redisplay & pause so the user can see we moved the selection.
61 | (redisplay t)
62 | (sit-for 0.1))
63 |
64 |
65 | ;; TODO: Only expose this while minor mode active?
66 | (voicemacs-expose-function 'voicemacs-helm-goto-line)
67 |
68 |
69 | (defun voicemacs--local-override-face (face &rest overrides)
70 | "Override a face in the current buffer only."
71 | (setq-local face-remapping-alist
72 | (cons `(,face ,@overrides)
73 | ;; Remove any overrides for this face that already exist.
74 | (-filter (lambda (mapping)
75 | (not (eq (car mapping) face)))
76 | face-remapping-alist))))
77 |
78 |
79 | (defun voicemacs--enable-selection-line-numbers (&rest _)
80 | "Make the current buffer show bold, absolute line numbers.
81 |
82 | These numbers can be used for selection."
83 | ;; Default line numbers are subtle. These are selection numbers, make them
84 | ;; stand out.
85 | ;;
86 | ;; TODO: Extract line numbers face?
87 | ;;
88 | ;; FIXME: `bold' will override the color in some themes, e.g. `leuven'
89 | ;; (voicemacs--local-override-face 'line-number 'bold 'font-lock-keyword-face)
90 | (voicemacs--local-override-face 'line-number 'helm-bookmark-directory)
91 | ;; (voicemacs--local-override-face 'line-number-current-line
92 | ;; 'bold
93 | ;; 'helm-selection
94 | ;; 'font-lock-keyword-face)
95 | (voicemacs--local-override-face 'line-number-current-line
96 | 'helm-selection
97 | 'helm-bookmark-directory)
98 | (setq-local display-line-numbers 'absolute))
99 |
100 |
101 | (defun voicemacs--show-helm-numbers ()
102 | (when helm-alive-p
103 | (with-helm-buffer
104 | (voicemacs--enable-selection-line-numbers))))
105 |
106 |
107 | (defun voicemacs--helm-numbers-mode-setup ()
108 | (cl-assert (boundp 'display-line-numbers) nil
109 | "`display-line-numbers' not available")
110 | (add-hook 'helm-update-hook 'voicemacs--show-helm-numbers))
111 |
112 |
113 | (defun voicemacs--helm-numbers-mode-teardown ()
114 | (remove-hook 'helm-update-hook 'voicemacs--show-helm-numbers)
115 | ;; Also disable any active numbers
116 | (when helm-alive-p
117 | (with-helm-buffer
118 | (setq-local display-line-numbers nil))))
119 |
120 |
121 | (define-minor-mode voicemacs-helm-numbers-mode
122 | "When active, helm will number candidates with absolute line numbers.
123 |
124 | Incompatible with `helm-display-line-numbers-mode'."
125 | :group 'voicemacs
126 | :global t
127 | :lighter nil
128 | :after-hook (if voicemacs-helm-numbers-mode
129 | (voicemacs--helm-numbers-mode-setup)
130 | (voicemacs--helm-numbers-mode-teardown)))
131 |
132 | ;; TODO: System for enabling by default?
133 |
134 |
135 | ;; FIXME: Find the right map for it to only be active in the minibuffer.
136 | (voicemacs-bind-cumulative-number-commands "helm" #'voicemacs-helm-goto-line 'helm-map)
137 |
138 |
139 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
140 |
141 |
142 | ;; TODO: Maybe make a generalised function to invoke nonblocking RPC calls
143 | (defun voicemacs-helm-swoop (query)
144 | "Run `helm-swoop' with a specific `query' on a timer.
145 |
146 | Allows helm-swoop to be invoked via RPC without blocking."
147 | ;; Type check because it's delayed.
148 | (cl-assert (stringp query))
149 | (run-with-timer 0 nil 'helm-swoop :query query))
150 |
151 | (voicemacs-expose-function 'voicemacs-helm-swoop)
152 |
153 |
154 | (defun voicemacs-helm-submit-if-single-match ()
155 | "Submit the match if only one exists."
156 | ;; Ensure matches are updated
157 | (when (helm--updating-p)
158 | (helm-refresh))
159 | ;; TODO: How to get currently matching candidates?
160 | (helm-candidate-number-limit)
161 | (helm-confirm-and-exit-minibuffer)
162 | )
163 |
164 |
165 | (provide 'voicemacs-extend-helm)
166 | ;;; voicemacs-extend-helm.el ends here.
167 |
--------------------------------------------------------------------------------
/voicemacs-it.el:
--------------------------------------------------------------------------------
1 | (require 'voicemacs-base)
2 | (require 'voicemacs-command)
3 |
4 |
5 | (defvar voicemacs-it-type-keys
6 | '(name
7 | modes
8 | available-actions)
9 | "List of keys to synchronize from each object type.
10 |
11 | These keys will be included when the object type is passed to the
12 | client. Other keys will be discarded. This is used to limit the
13 | information leaving Emacs.")
14 |
15 |
16 | (defun voicemacs--it-filter-type (object-type keys)
17 | "Get a filtered variant of `object-type' with just `keys'."
18 | (-filter (lambda (property-pair)
19 | (member (car property-pair) keys))
20 | object-type))
21 |
22 |
23 | (defun voicemacs--it-object-types ()
24 | "Get all available it object types.
25 |
26 | The empty string will be used as the key for global objects,
27 | rather than `nil'."
28 | (voicemacs--maphash
29 | (lambda (mode objects)
30 | (cons
31 | ;; Global objects are stored under the `nil' key, but we can't
32 | ;; encode a `nil' key into JSON. Replace it with `global'.
33 | (or mode 'global)
34 | ;; Simplify the objects, remove redundant information
35 | (voicemacs--maphash (lambda (name type)
36 | ;; Just transfer the info we need
37 | (voicemacs--it-filter-type type voicemacs-it-type-keys))
38 | objects)))
39 | it-object-types))
40 |
41 |
42 | (with-eval-after-load 'it
43 | ;; TODO: Maybe just expose all `it' actions?
44 | (voicemacs-expose-function 'it-wrap)
45 | (voicemacs-expose-function 'it-text-of-thing-at-dwim)
46 |
47 | (voicemacs-define-sync it-object-types
48 | :update (voicemacs--it-object-types)
49 | :enable (add-hook 'it-define-object-hook sync-func)
50 | :disable (remove-hook 'it-define-object-hook sync-func)
51 | :defer t
52 | ;; May be a big sync.
53 | :delay 0.1
54 | ))
55 |
56 |
57 | (provide 'voicemacs-it)
58 | ;;; voicemacs-it.el ends here
59 |
--------------------------------------------------------------------------------
/voicemacs-lib.el:
--------------------------------------------------------------------------------
1 | ;; Utils library for Voicemacs.
2 |
3 | ;;; Code:
4 |
5 |
6 | (require 'nav-flash)
7 |
8 |
9 | (defun voicemacs--pad-string (string desired-length)
10 | "Pad left side of `STRING' to `DESIRED-LENGTH'."
11 | (concat (make-string
12 | ;; Don't want a negative length prefix.
13 | (max (- desired-length (length string))
14 | 0)
15 | ? )
16 | string))
17 |
18 |
19 | ;; TODO: Convert these to question mark syntax
20 | (defun voicemacs--bound-and-true-p (symbol)
21 | "Is `symbol' both bound, and truthy?
22 |
23 | Like `bound-and-true-p', but a function, not a macro."
24 | (and (boundp symbol)
25 | (symbol-value symbol)))
26 |
27 |
28 | (defun voicemacs-in-string-p ()
29 | "Returns t if currently in a string, nil otherwise.
30 |
31 | `in-string-p' is obsolete so use this instead."
32 | (if (nth 3 (syntax-ppss)) t nil))
33 |
34 |
35 | (defun voicemacs-assert-in (value valid-values)
36 | "Ensure a `VALUE' is one of `VALID-VALUES', with meaningful error."
37 | (unless (member value valid-values)
38 | (user-error "%s not one of %s" value valid-values)))
39 |
40 |
41 | (defun voicemacs-flash (region-cons)
42 | "Flash a region in the buffer."
43 | (when region-cons
44 | ;; TODO: Don't use `nav-flash' for this. It doesn't block.
45 | (nav-flash-show (car region-cons) (cdr region-cons) 'isearch)))
46 |
47 |
48 | (defun voicemacs-visual-copy (region-cons)
49 | (voicemacs-flash region-cons)
50 | (kill-ring-save (car region-cons) (cdr region-cons)))
51 |
52 |
53 | (defun voicemacs-visual-kill (region-cons)
54 | (voicemacs-flash region-cons)
55 | (kill-region (car region-cons) (cdr region-cons)))
56 |
57 |
58 | (defun voicemacs-visual-yank ()
59 | (let ((start-pos (point)))
60 | (yank)
61 | (voicemacs-flash (cons start-pos (point)))))
62 |
63 |
64 | ;; TODO: Smart insert, respecting e.g. whitespace.
65 | (defun voicemacs-visual-insert (text)
66 | (let ((start-pos (point)))
67 | (insert text)
68 | (voicemacs-flash (cons start-pos (point)))))1
69 |
70 |
71 | (defmacro voicemacs--first-result (result-form &rest body)
72 | "Perform `RESULT-FORM' then `BODY', but return the result of `RESULT-FORM'."
73 | (declare (indent 1))
74 | `(let ((result ,result-form))
75 | ,@body
76 | result))
77 |
78 |
79 | (defun voicemacs--filter-atoms (func &optional obarray-)
80 | "Filter all atoms in `OBARRAY-' with `FUNC'.
81 |
82 | Like with `mapatoms', `OBARRAY-' defaults to the value of
83 | `obarray'."
84 | (let ((matches '()))
85 | (mapatoms (lambda (atom)
86 | (when (funcall func atom)
87 | (push atom matches)))
88 | (or obarray- obarray))
89 | matches))
90 |
91 |
92 | (defun voicemacs--maphash (func table)
93 | "Like `maphash', but returns the list of results like `mapcar'."
94 | (let ((results))
95 | (maphash (lambda (key value)
96 | (push (funcall func key value) results))
97 | table)
98 | results))
99 |
100 |
101 | (defun voicemacs--set-to-list (set)
102 | "Convert `set' (represented by a hash table) to a list."
103 | (hash-table-keys set))
104 |
105 |
106 | (defun voicemacs--set-add (element set)
107 | "Add `element' to `set' (represented by a hash table)."
108 | (unless (voicemacs--set-contains? element set)
109 | (puthash element t set)))
110 |
111 |
112 | (defun voicemacs--set-contains? (element set)
113 | "Check if `element' is a member of `set' (represented by a hash table)."
114 | (gethash element set nil))
115 |
116 |
117 | (defun voicemacs--set-remove (element set)
118 | "Remove `element' from `set' (represented by a hash table)."
119 | (remhash element set))
120 |
121 |
122 | (provide 'voicemacs-lib)
123 | ;;; voicemacs-lib.el ends here
124 |
--------------------------------------------------------------------------------
/voicemacs-server.el:
--------------------------------------------------------------------------------
1 | (require 'cl-lib)
2 | (require 'json-rpc-server)
3 |
4 |
5 | (defvar voicemacs--update-response-timeout 3
6 | "Time to wait (in seconds) before assuming a key update failed.")
7 |
8 |
9 | (defconst voicemacs--server-name "voicemacs-server"
10 | "Name to use for the Voicemacs server process.")
11 |
12 |
13 | (defconst voicemacs--server-buffer-name "*voicemacs-server*"
14 | "Name to use for the Voicemacs server's buffer.")
15 |
16 |
17 | (defvar voicemacs--server-process nil
18 | "Holds the Voicemacs server process (once it's started).")
19 |
20 |
21 | (defvar voicemacs--connected-clients '()
22 | "List of currently connected clients.")
23 |
24 |
25 | (defvar voicemacs--current-auth-key nil
26 | "Auth key clients must provide when they connect.")
27 |
28 |
29 | (defvar voicemacs--current-port nil
30 | "Port that the server is running on.")
31 |
32 |
33 | (defun voicemacs--broadcast-update (key new-value)
34 | (declare (indent 1))
35 | (mapc (lambda (client)
36 | (voicemacs--send-update client key new-value))
37 | voicemacs--connected-clients))
38 |
39 |
40 | (defun voicemacs--send-update (client key new-value)
41 | (declare (indent 1))
42 | ;; TODO 1: Need to be able to handle the client just failing here.
43 | (when (voicemacs--authenticated? client)
44 | (let ((nonce (process-get client :outgoing-nonce)))
45 | (voicemacs--send
46 | client
47 | (voicemacs--make-request "update"
48 | nonce
49 | (voicemacs--make-hash-table
50 | `(("key" . ,key)
51 | ("value" . ,new-value)))))
52 | (puthash (format "%s" key) nonce
53 | (process-get client :pending-responses))
54 | ;; TODO: What if we're busy when we recieve the response? Will it process
55 | ;; in time? Idle timer this?
56 | (run-with-timer voicemacs--update-response-timeout nil
57 | 'voicemacs--maybe-resend-update
58 | client key nonce)
59 | ;; TODO: Handle overflow?
60 | (process-put client :outgoing-nonce (+ 1 nonce)))))
61 |
62 |
63 | (defun voicemacs--maybe-resend-update (client key sent-nonce)
64 | "Resend `KEY' to the client, iff we have recieved no response."
65 | (when (eq sent-nonce (gethash key (process-get client :pending-responses)))
66 | ;; Use the *current* value, not the value when we first tried to sync. We
67 | ;; only care about transferring the most up-to-date state.
68 | (voicemacs--send-update client key (voicemacs--get-data key))))
69 |
70 |
71 | (defun voicemacs--confirm-update (client key nonce)
72 | "Confirm that update of `KEY' with `NONCE' was successful."
73 | ;; We only care if it was a confirmation of the *latest* update.
74 | (let ((pending (process-get client :pending-responses)))
75 | (when (equal nonce (gethash key pending))
76 | (remhash key pending))))
77 |
78 |
79 | (defun voicemacs--client-sentinel (client message)
80 | (when (member (process-status client) '(closed failed exit signal))
81 | (setq voicemacs--connected-clients
82 | (remove client voicemacs--connected-clients))))
83 |
84 |
85 | (defun voicemacs--server-filter (client message)
86 | ;; TODO: Timeout on half-finished message?
87 | (let ((pos 0)
88 | match-pos)
89 | (while (setq match-pos (string-match "\0" message pos))
90 | (let ((full-message (concat (process-get client :message-so-far)
91 | (substring message pos match-pos))))
92 | (cond
93 | ;; Ignore double "\0" messages
94 | ((string-empty-p full-message) nil)
95 | ;; Ignore pings
96 | ((string= full-message "\1") nil)
97 | ;; Otherwise handle
98 | (t (voicemacs--handle-message client full-message))))
99 | (process-put client :message-so-far "")
100 | (setq pos (+ match-pos (length "\0"))))
101 | (process-put client :message-so-far
102 | (concat (process-get client :message-so-far)
103 | (substring message pos)))))
104 |
105 |
106 | ;; TODO: Option for faster parsing if we know the data is in the right format?
107 | (defun voicemacs--handle-message (client message)
108 | "Handle one message "
109 | ;; TODO: Cover arbitrary internal errors?
110 | (let ((decoded (condition-case nil
111 | ;; TODO: Emacs <27 parsing too. Probably just hack into
112 | ;; json-rpc-server's approach.
113 | (json-parse-string message)
114 | 'INVALID-JSON)))
115 | (cond
116 | ((eq decoded 'INVALID-JSON)
117 | (voicemacs--respond-error
118 | client nil "invalid-message" "A mangled message was received but it could not be decoded."))
119 | ((not (hash-table-p decoded))
120 | (voicemacs--respond-error client nil "invalid-message" "Message was not a dictionary."))
121 | (t
122 | (let ((type (gethash "type" decoded 'NOT-PROVIDED))
123 | (nonce (gethash "nonce" decoded 'NOT-PROVIDED))
124 | (data (gethash "data" decoded 'NOT-PROVIDED))
125 | (direction (gethash "direction" decoded 'NOT-PROVIDED)))
126 | (cond
127 | ;; Validate message structure first
128 | ;;
129 | ;; nonce first, so it can be included it in other errors
130 | ((eq nonce 'NOT-PROVIDED) (voicemacs--respond-error client nil "invalid-message"
131 | "No `nonce' was provided."))
132 | ((eq type 'NOT-PROVIDED) (voicemacs--respond-error client nonce "invalid-message"
133 | "No `type' was provided."))
134 | ((eq data 'NOT-PROVIDED) (voicemacs--respond-error client nonce "invalid-message"
135 | "No `data' was provided."))
136 | ((eq direction 'NOT-PROVIDED)
137 | (voicemacs--respond-error client nonce "invalid-message"
138 | "No `direction' was provided."))
139 | ((not (stringp type)) (voicemacs--respond-error client nonce "invalid-message"
140 | "`type' must be a string."))
141 | ((not (hash-table-p data)) (voicemacs--respond-error client nonce "invalid-message"
142 | "`data' must be a dictionary."))
143 | ((not (member direction '("request" "response")))
144 | (voicemacs--respond-error client nonce "invalid-message"
145 | "`direction' must be either \"request\" or \"response\""))
146 |
147 | ;; Basic message structure is fine, now dispatch to correct handler.
148 | ((and (string= direction "request") (string= type "authenticate"))
149 | (condition-case nil
150 | (voicemacs--authenticate client data nonce)
151 | (error
152 | ;; They aren't authed, so don't give them much information
153 | (voicemacs--respond-error client nonce "internal-error"
154 | "An error occured during authorization."))))
155 |
156 | ((not (ignore-errors (process-get client :authenticated)))
157 | (voicemacs--respond-error client nonce "not-authenticated"
158 | "Client not authorized. Please request authorization."))
159 |
160 | ((string= direction "request")
161 | (cond ((string= type "json-rpc-call") (voicemacs--json-rpc-call
162 | client nonce data))
163 | (t (voicemacs--respond-error client nonce "unrecognized-type"
164 | "Did not recognize this request type."))))
165 | ((string= direction "response")
166 | ;; Right now there's only one type of outgoing message, so we assume
167 | ;; every response is a response to that.
168 | (cond ((string= type "confirm-update")
169 | ;; TODO: Don't need key for this. The nonce should be enough
170 | ;; information to work with.
171 | (let ((key (gethash "key" data)))
172 | (if key
173 | (voicemacs--confirm-update client key nonce)
174 | ;; TODO: Handle erroneous response structure?
175 | (message "Erroneous response structure - no key"))))
176 | ((string= type "error")
177 | ;; TODO: How to handle error response from the client? Give up
178 | ;; or keep retrying?
179 | (message "Error received during update: %s" data))
180 | (t
181 | ;; TODO: Handle unknown response?
182 | nil)
183 | ))
184 | (t nil)))))))
185 |
186 |
187 | (defun voicemacs--authenticate (client data nonce)
188 | "Attempt to authenticate client based on `AUTH-KEY'."
189 | ;; TODO: Version handshake?
190 | (voicemacs--send
191 | client
192 | ;; For now, always authenticate
193 | (if (and voicemacs--current-auth-key ; Protect against an error in the key.
194 | (equal (gethash "key" data)
195 | voicemacs--current-auth-key))
196 | (progn
197 | (process-put client :authenticated t)
198 | (voicemacs--make-response nonce "authentication-successful" nil))
199 | (voicemacs--make-error nonce "invalid-credentials"
200 | "The credentials supplied were invalid.")))
201 | ;; TODO: Better method for initial sync?
202 | (maphash (lambda (key value)
203 | (voicemacs--send-update client key value))
204 | voicemacs--data))
205 |
206 |
207 | (defun voicemacs--authenticated? (client)
208 | "Has `CLIENT' authenticated itself yet?"
209 | (process-get client :authenticated))
210 |
211 |
212 | (cl-defun voicemacs--make-hash-table (alist)
213 | "Make a hash table from an alist."
214 | (let ((table (make-hash-table :size (length alist)
215 | :test 'equal)))
216 | (mapc (lambda (pair)
217 | (puthash (car pair) (cdr pair) table))
218 | alist)
219 | table))
220 |
221 |
222 | (defun voicemacs--respond-error (client nonce error-type message)
223 | "Send an error response to the client."
224 | (voicemacs--send client (voicemacs--make-error
225 | nonce error-type message)))
226 |
227 |
228 | (defun voicemacs--make-request (type nonce data)
229 | "Construct an outgoing message.
230 |
231 | You must manually increment the nonce if you send a message
232 | constructed with this method."
233 | (voicemacs--make-hash-table
234 | ;; TODO: Maybe call this "request"?
235 | `(("direction" . "request")
236 | ("type" . ,type)
237 | ("nonce" . ,nonce)
238 | ("data" . ,data))))
239 |
240 |
241 | (defun voicemacs--make-response (nonce type data)
242 | (voicemacs--make-hash-table
243 | `(("direction" . "response")
244 | ("type" . ,type)
245 | ("nonce" . ,nonce)
246 | ("data" . ,data))))
247 |
248 |
249 | (defun voicemacs--make-error (nonce error-type error-message)
250 | (voicemacs--make-response
251 | nonce "error" (voicemacs--make-hash-table
252 | `(("error-type" . ,error-type)
253 | ("error-message" . ,error-message)))))
254 |
255 |
256 | (defun voicemacs--json-rpc-call (client nonce data)
257 | (when unread-command-events
258 | ;; HACK: Flush the command queue first - don't want RPC calls to be
259 | ;; processed before queued commands.
260 | (message "Unread command events!")
261 | (redisplay))
262 | (voicemacs--send
263 | client
264 | (voicemacs--make-response
265 | nonce "json-rpc-result"
266 | (voicemacs--make-hash-table
267 | `(("json-result" .
268 | ;; TODO: Handle malformed data
269 | ,(json-rpc-server-handle (gethash "call" data)
270 | voicemacs--exposed-functions)))))))
271 |
272 |
273 | (defun voicemacs--send (client message)
274 | ;; TODO: Temporarily raise garbage collection threshold to stop GCs during
275 | ;; this process?
276 | (process-send-string
277 | client
278 | ;; Guard the start too in case of hanging messages in the pipeline.
279 | (concat "\0"
280 | ;; HACK: Leverage private method of `json-rpc-server' because it
281 | ;; emulates the behaviour of `json-encode' while exploiting the
282 | ;; performance increase of Emacs 27's `json-serialize' (when
283 | ;; possible).
284 | (json-rpc-server--emulate-legacy-encode message)
285 | "\0")))
286 |
287 |
288 | (defun voicemacs--server-sentinel (process message)
289 | ;; TODO: Is `process' the server?
290 | ;;
291 | ;; TODO: Gross, do something more robust (check process status?)
292 | (when (string= message "deleted\n")
293 | (setq voicemacs--connected-clients nil)
294 | (setq voicemacs--server-process nil)))
295 |
296 |
297 | (defun voicemacs--server-new-client (server client _message)
298 | "Handle a new connection from `CLIENT'.
299 |
300 | Only one client can be connected at a time. If no clients are
301 | connected, this client's connection will be accepted. If a client
302 | is already connected, the new client will be rejected."
303 | ;; Connected clients must be authenticated before they can make requests.
304 | (process-put client :authenticated nil)
305 | ;; The filter might not be called with a full message. This is used to store
306 | ;; the part of the message that has been transferred between calls to the
307 | ;; filter.
308 | (process-put client :message-so-far "")
309 | (process-put client :outgoing-nonce 1)
310 | (process-put client :pending-responses (make-hash-table :test 'equal))
311 | (set-process-sentinel client 'voicemacs--client-sentinel)
312 | (push client voicemacs--connected-clients))
313 |
314 |
315 | (defun voicemacs--get-linux-temp-dir ()
316 | "Get a user-only temp dir on Linux, to store the server info in."
317 | ;; If the runtime dir isn't available, fall back to the home dir.
318 | (or (getenv "XDG_RUNTIME_DIR")
319 | (and (getenv "HOME")
320 | (f-join (getenv "HOME") "tmp"))
321 | (and (display-warning
322 | "voicemacs"
323 | (concat "Neither $XDG_RUNTIME_DIR nor $HOME could be read from "
324 | "the environment. Cannot create session file - clients "
325 | "will not be able to connect automatically."))
326 | nil)))
327 |
328 |
329 | (defconst voicemacs--base-temp-dir
330 | ;; TODO: Switch this over to use the same server file style as emacs-server?
331 | (pcase system-type
332 | ('gnu/linux (voicemacs--get-linux-temp-dir))
333 | ('windows-nt (getenv "TEMP"))
334 | ('darwin (substitute-in-file-name "$HOME/Library/"))
335 | (_
336 | ;; Use the same method as Linux on unknown systems.
337 | (display-warning
338 | "voicemacs"
339 | (concat "Unrecognised system type. Don't know where to find the "
340 | "temp directory. Using the same method as Linux."))
341 | (porthole--get-linux-temp-dir)))
342 | "The base temp directory to use.
343 |
344 | This will be dependent on the current system.")
345 |
346 |
347 | (defconst voicemacs--session-file-name
348 | (f-join voicemacs--base-temp-dir "voicemacs" "session.json"))
349 |
350 |
351 | (defun voicemacs--publish-session-file (port auth-key)
352 | "Publish the current session's connection information.
353 |
354 | Clients can use this file to automatically connect."
355 | ;; Clean up old session first
356 | (when (f-file? voicemacs--session-file-name)
357 | (f-delete voicemacs--session-file-name))
358 |
359 | (let ((directory (f-dirname voicemacs--session-file-name)))
360 | (unless (f-dir? directory)
361 | (make-directory directory t)))
362 | (with-temp-file voicemacs--session-file-name
363 | (insert (json-rpc-server--emulate-legacy-encode
364 | (voicemacs--make-hash-table
365 | `(("port" . ,port)
366 | ("auth-key" . ,auth-key))))))
367 | voicemacs--session-file-name)
368 |
369 |
370 | (defun voicemacs--erase-session-file ()
371 | "Delete the active session file (and directory).
372 |
373 | Will not raise an error if the file doesn't exist."
374 | (when (f-file? voicemacs--session-file-name)
375 | (f-delete voicemacs--session-file-name))
376 | (let ((directory (f-dirname voicemacs--session-file-name)))
377 | (when (f-dir? directory)
378 | (f-delete directory t))))
379 |
380 |
381 | (defun voicemacs--random-sha256-key ()
382 | "Generate a random sha256 key."
383 | ;; Make 400 random int strings, join them, then hash the result. That should
384 | ;; be suitably unique.
385 | ;;
386 | ;; TODO: Introduce some kind of external entropy? Command history?
387 | (let ((long-random-number
388 | (apply #'concat (mapcar (lambda (_)
389 | (format "%s" (random 9999999999999)))
390 | (number-sequence 0 400)))))
391 | (secure-hash 'sha256 long-random-number)))
392 |
393 |
394 | (cl-defun voicemacs--start-server (&key port plist)
395 | "Start a new Voicemacs server process."
396 | (when voicemacs--server-process
397 | ;; TODO: Ensure server is also running?
398 | (error "The Voicemacs server is already running."))
399 |
400 | ;; TODO: Attach this to the server process?
401 | (setq voicemacs--connected-clients nil)
402 | (setq voicemacs--server-process
403 | ;; TODO: Include port number in server/buffer name?
404 | (make-network-process :name voicemacs--server-name
405 | :buffer voicemacs--server-buffer-name
406 | :family 'ipv4
407 | ;; TODO: Explicit address?
408 | :service (or port t)
409 | :sentinel 'voicemacs--server-sentinel
410 | :filter 'voicemacs--server-filter
411 | :log 'voicemacs--server-new-client
412 | ;; :keepalive t
413 | :server t
414 | :noquery t
415 | :plist plist))
416 |
417 | (setq voicemacs--current-auth-key (voicemacs--random-sha256-key))
418 | (setq voicemacs--current-port
419 | ;; Have to manually extract the actual assigned port from the process.
420 | (process-contact voicemacs--server-process :service))
421 |
422 | (voicemacs--publish-session-file
423 | voicemacs--current-port
424 | voicemacs--current-auth-key))
425 |
426 |
427 | (defun voicemacs--stop-server ()
428 | "Stop the Voicemacs server."
429 | (when voicemacs--server-process
430 | (voicemacs--erase-session-file)
431 | (ignore-errors
432 | (delete-process voicemacs--server-process))
433 | (setq voicemacs--current-auth-key nil
434 | voicemacs--current-port nil
435 | voicemacs--server-process nil
436 | voicemacs--connected-clients nil)))
437 |
438 |
439 | (defun voicemacs--stop-server-safe ()
440 | "Stop the Voicemacs server, but suppress all errors.
441 |
442 | Safe to hook to things like `kill-emacs-hook'."
443 | (ignore-errors (voicemacs--stop-server)))
444 |
445 |
446 | ;; In particular we want to clean up lingering session files.
447 | (add-hook 'kill-emacs-hook #'voicemacs--stop-server-safe)
448 | (unless voicemacs--server-process
449 | ;; If Emacs crashes, the session file will linger. Try and help this a little
450 | ;; - clean up lingering sessions when Voicemacs is loaded.
451 | (voicemacs--erase-session-file))
452 |
453 |
454 | (provide 'voicemacs-server)
455 | ;;; voicemacs-server.el ends here
456 |
--------------------------------------------------------------------------------
/voicemacs.el:
--------------------------------------------------------------------------------
1 | (require 'cl)
2 | (require 'default-text-scale)
3 |
4 | (require 'voicemacs-base)
5 | (require 'voicemacs-command)
6 |
7 | (require 'voicemacs-avy)
8 | (require 'voicemacs-correct)
9 |
10 | (require 'voicemacs-it)
11 |
12 | ;; TODO: Redo the way these extension modules are loaded.
13 | (with-eval-after-load 'helm
14 | (require 'voicemacs-extend-helm))
15 | (with-eval-after-load 'dired
16 | (require 'voicemacs-extend-dired))
17 | (with-eval-after-load 'company
18 | (require 'voicemacs-extend-company))
19 |
20 |
21 | (voicemacs-define-sync voicemacs
22 | :update t
23 | :enable nil
24 | :disable nil)
25 |
26 |
27 | ;; Major Mode Sync
28 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
29 |
30 |
31 | (defun voicemacs--mode-derivation-chain (mode)
32 | "Get a list of `mode' plus all derivation ancestors."
33 | (when mode
34 | (append (list mode)
35 | (voicemacs--mode-derivation-chain
36 | (get mode 'derived-mode-parent)))))
37 |
38 |
39 | (voicemacs-define-sync-change-buffer major-mode-chain
40 | :update (voicemacs--mode-derivation-chain major-mode)
41 | :defer nil)
42 |
43 | (voicemacs-define-sync-change-buffer primary-major-mode
44 | :update major-mode
45 | :defer nil)
46 |
47 |
48 | ;; Minor Modes Sync
49 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
50 |
51 |
52 | (defun voicemacs--active-minor-modes ()
53 | "Get the currently active minor modes."
54 | ;; Different packages register their minor modes in different lists, so we
55 | ;; have to iterate over both.
56 | (cl-union
57 | (seq-filter 'voicemacs--bound-and-true-p
58 | minor-mode-list)
59 | (seq-filter 'voicemacs--bound-and-true-p
60 | (mapcar #'car minor-mode-alist))))
61 |
62 |
63 | (voicemacs-define-sync-change-buffer minor-modes
64 | :update (voicemacs--active-minor-modes)
65 | :defer t)
66 |
67 |
68 | ;; Defined Commands Sync
69 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
70 |
71 |
72 | (defun voicemacs--defined-commands ()
73 | "Get a list of all defined commands."
74 | ;; TODO: is there a dedicated variable for commands? Don't want to compute
75 | ;; unless we have to.
76 | (voicemacs--filter-atoms 'commandp))
77 |
78 |
79 | (defun voicemacs--temp-disable-name (func)
80 | "Helper for the `*-lazy-advise-defun' functions."
81 | (voicemacs--format-symbol "voicemacs--temp-disable-%s" func))
82 |
83 |
84 | (defun voicemacs--lazy-advise-defun (func)
85 | "Advise `defun', but suppress the advice when entire files are loaded.
86 |
87 | When loading many function definitions, we may not wish to run
88 | the advice with every call to `defun'.
89 |
90 | Advice will be run `:after' defun."
91 | (advice-add 'defun :after func)
92 | ;; Create a function to temporarily disable the advice we've given `defun'.
93 | ;; This function must be added as `:around' advice.
94 | (let ((temp-disable-func-name (voicemacs--temp-disable-name func)))
95 | (eval `(defun ,temp-disable-func-name (wrapped-func &rest args)
96 | (ignore-errors (advice-remove 'defun ,func))
97 | (voicemacs--first-result (apply wrapped-func args)
98 | (ignore-errors
99 | (advice-add 'defun :after ,func)
100 | ;; Since we suppressed it, we should manually queue once.
101 | (,func)))))
102 | (advice-add 'require :around temp-disable-func-name)
103 | (advice-add 'load :around temp-disable-func-name)))
104 |
105 |
106 | (defun voicemacs--undo-lazy-advise-defun (func)
107 | "Undo the effects of `voicemacs--lazy-advise-defun'."
108 | (let ((temp-disable-func-name (voicemacs--temp-disable-name func)))
109 | (advice-remove 'require temp-disable-func-name)
110 | (advice-remove 'load temp-disable-func-name)))
111 |
112 |
113 | (voicemacs-define-sync defined-commands
114 | :update (voicemacs--defined-commands)
115 | :enable (voicemacs--lazy-advise-defun sync-func)
116 | :disable (voicemacs--undo-lazy-advise-defun sync-func)
117 | :defer t
118 | ;; Command definitions will be relatively rare after startup. Delay more than
119 | ;; normal to reduce visible overhead. Cheating, but user shouldn't notice.
120 | :delay 1)
121 |
122 |
123 | ;; Buffer name sync
124 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
125 |
126 |
127 | (voicemacs-define-sync-change-buffer buffer-name
128 | :update (buffer-name)
129 | :defer t)
130 |
131 |
132 | ;; File path sync
133 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
134 |
135 |
136 | (voicemacs-define-sync-change-buffer buffer-file-name
137 | :update (buffer-file-name)
138 | :defer t)
139 |
140 |
141 | ;; Yasnippets Sync
142 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
143 |
144 |
145 | (defun voicemacs--snippet (template)
146 | "Make a voicemacs-style snippet from a yas `template'.
147 |
148 | Returns a hash table with minimal information about the snippet,
149 | to reduce the amount of data we have to sync."
150 | (let ((snippet (make-hash-table)))
151 | (puthash "name" (yas--template-name template) snippet)
152 | (puthash "key" (yas--template-key template) snippet)
153 | ;; TODO: Maybe allow spoken forms in snippets?
154 | snippet))
155 |
156 |
157 | (defun voicemacs--snippets-from-table (table)
158 | "Get a list of voicemacs-style snippets from a `table'.
159 |
160 | The structure (in JSON format) will be:
161 |
162 | [
163 | {\"name\": name, \"key\": key},
164 | {\"name\": name, \"key\": key},
165 | {\"name\": name, \"key\": key},
166 | ]
167 |
168 | Each dict here represents one snippet."
169 | (let ((snippets '()))
170 | (maphash (lambda (template-key template)
171 | (push (voicemacs--snippet template) snippets))
172 | (yas--table-uuidhash table))
173 | snippets))
174 |
175 |
176 | (defun voicemacs--get-snippets ()
177 | "Get all registered snippets in voicemacs format.
178 |
179 | The structure (in JSON format) will be:
180 |
181 | {
182 | snippet-list-name: snippet-list,
183 | snippet-list-name: snippet-list,
184 | }
185 |
186 | See `voicemacs--snippets-from-table' for the `snippet-list'
187 | structure."
188 | (let ((snippets (make-hash-table)))
189 | (maphash (lambda (key table)
190 | (puthash key (voicemacs--snippets-from-table table) snippets))
191 | yas--tables)
192 | snippets))
193 |
194 |
195 | (defun voicemacs-insert-snippet (snippet-name)
196 | (let ((where (if (region-active-p)
197 | (cons (region-beginning) (region-end))
198 | (cons (point) (point)))))
199 | (yas-expand-snippet
200 | (yas-lookup-snippet snippet-name)
201 | (car where) (cdr where))))
202 |
203 |
204 | (with-eval-after-load 'yasnippet
205 | (voicemacs-define-sync-change-buffer active-yasnippet-tables
206 | :update (yas--modes-to-activate)
207 | :defer t)
208 |
209 | (voicemacs-define-sync yasnippets
210 | :update (voicemacs--get-snippets)
211 | :enable (progn
212 | (add-hook 'yas-after-reload-hook sync-func)
213 | ;; These seem to be the two lowest-level functions that are used
214 | ;; to add & remove (and update) snippets.
215 | (advice-add 'yas--add-template :after sync-func)
216 | (advice-add 'yas--remove-template-by-uuid :after sync-func))
217 | :disable (progn
218 | (remove-hook 'yas-after-reload-hook sync-func)
219 | (advice-remove 'yas--add-template sync-func)
220 | (advice-remove 'yas--remove-template-by-uuid sync-func))
221 | :defer t
222 | ;; This is an expensive operation, don't fire during every sit.
223 | :delay 0.1)
224 |
225 | (voicemacs-expose-function 'voicemacs-insert-snippet))
226 |
227 |
228 | ;; Org-mode
229 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
230 |
231 |
232 | (with-eval-after-load 'org
233 | (voicemacs-define-sync-change-buffer org-todo-keywords
234 | :update (if (boundp 'org-todo-keywords)
235 | (append org-todo-keywords
236 | ;; Also add any buffer-local TODO keywords.
237 | (when (bound-and-true-p org-todo-keywords-1)
238 | (list (cons 'sequence org-todo-keywords-1)))))
239 | :defer t)
240 |
241 | (voicemacs-expose-function 'org-todo))
242 |
243 |
244 | ;; Cursor in a Comment?
245 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
246 |
247 |
248 | (defun voicemacs-in-comment-p (&optional pos)
249 | "Check if the cursor is in a comment by examining font faces.
250 |
251 | Uses current point by default. Provide `POS' to specify a
252 | different position.
253 |
254 | This function uses a similar method to that used by Flyspell."
255 | ;; `pos' defaults to point
256 | (unless (integerp pos)
257 | (setq pos (point)))
258 | ;; Check the face directly. Is it a comment face?
259 | (let* ((raw-faces (get-text-property pos 'face))
260 | ;; The 'face property could be a list, could be a single item.
261 | ;; Normalize it to a list.
262 | (faces-list (if (listp raw-faces)
263 | raw-faces
264 | (list raw-faces))))
265 | (or (member 'font-lock-comment-face faces-list)
266 | (member 'font-lock-comment-delimiter-face faces-list)
267 | (nth 4 (syntax-ppss)))))
268 |
269 |
270 | ;; TODO: Maybe also sync `in-string-p'?
271 | (voicemacs-define-sync in-comment
272 | ;; Sending over the wire, so we need True or False, not truthiness
273 | :update (if (voicemacs-in-comment-p) t :json-false)
274 | ;; TODO: Maybe extract "register a sync that sycs immediately when idle" `'macro?
275 | :enable (run-with-idle-timer 0 0 sync-func)
276 | :disable (cancel-function-timers sync-func)
277 | ;; TODO: Forces regular syncs when we move cursor through a comment. can be
278 | ;; slow, creates choppiness. Put this info in the title?
279 | :defer nil)
280 |
281 |
282 | ;; `evil-mode'
283 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
284 |
285 | (with-eval-after-load 'evil
286 | (defvar voicemacs--evil-state-hooks '(evil-emacs-state-entry-hook
287 | evil-insert-state-entry-hook
288 | evil-motion-state-entry-hook
289 | evil-normal-state-entry-hook
290 | evil-operator-state-entry-hook
291 | evil-replace-state-entry-hook
292 | evil-visual-state-entry-hook)
293 | "Hooks that run on state entry for every default Evil state.")
294 | (voicemacs-define-sync evil-state
295 | :update (and evil-mode evil-state)
296 | :enable (progn
297 | (mapc (lambda (hook)
298 | (add-hook hook sync-func))
299 | voicemacs--evil-state-hooks)
300 | ;; In case the hooks don't catch it.
301 | (run-with-idle-timer 0 0 sync-func))
302 | :disable (progn
303 | (mapc (lambda (hook)
304 | (remove-hook hook sync-func))
305 | voicemacs--evil-state-hooks)
306 | (cancel-function-timers sync-func))
307 | :defer nil))
308 |
309 |
310 | ;; Text on Screen
311 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
312 |
313 |
314 | (defun voicemacs--visible-text ()
315 | "Get all visible text in each window.
316 |
317 | Returns a list, each item is the visible text for one window."
318 | (remove nil
319 | (mapcar (lambda (window)
320 | ;; Sometimes tries to gether from invalid windows. Just
321 | ;; ignore those errors.
322 | (ignore-errors
323 | (with-selected-window window
324 | (buffer-substring-no-properties (window-start) (window-end)))))
325 | ;; All windows
326 | (cl-mapcan #'window-list (frame-list)))))
327 |
328 |
329 | (voicemacs-define-sync visible-text
330 | :update (voicemacs--visible-text)
331 | :enable (run-with-idle-timer 0.05 0 sync-func)
332 | :disable (cancel-function-timers sync-func)
333 | :defer nil)
334 |
335 |
336 | ;; Minibuffer Contents
337 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
338 |
339 |
340 | (voicemacs-define-sync minibuffer-prompt
341 | :update (minibuffer-prompt)
342 | :enable (run-with-idle-timer 0 0 sync-func)
343 | :disable (cancel-function-timers sync-func)
344 | :defer nil)
345 |
346 | ;; Note that a prompt *will not* be reported when `current-message' is called.
347 | ;; Only `minibuffer-prompt' will get it.
348 |
349 | (voicemacs-define-sync current-message
350 | ;; TODO: Crop extremely large current message?
351 | :update (let ((message- (current-message))
352 | ;; Restrict to ensure quick syncing
353 | (max-message-length 1000))
354 | (if (> (length message-) max-message-length)
355 | (substring message- 0 max-message-length)
356 | message-))
357 | :enable (run-with-idle-timer 0 0 sync-func)
358 | :disable (cancel-function-timers sync-func)
359 | :defer nil)
360 |
361 |
362 | ;; Active Symbols
363 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
364 |
365 |
366 | (defconst voicemacs-max-symbol-range-before (expt 10 6)
367 | "Max characters to scan after point when gathering symbols from buffer.")
368 | (defconst voicemacs-max-symbol-range-after (expt 10 6)
369 | "Max characters to scan before point when gathering symbols from buffer.")
370 |
371 | (defvar voicemacs--active-symbols (make-hash-table)
372 | "Set of symbols that are \"present\" in the current context.")
373 |
374 |
375 | (defun voicemacs--symbols-in-buffer ()
376 | "Get all symbols in the buffer.
377 |
378 | Note this only searches within the range defined by
379 | `voicemacs--max-symbol-range-before' and
380 | `voicemacs--max-symbol-range-after'."
381 | ;; Only sync symbols for modes where it makes sense.
382 | ;;
383 | ;; TODO: Allow list of custom modes
384 | (save-excursion
385 | (let ((symbols (make-hash-table)))
386 | (goto-char (max (- (point) voicemacs-max-symbol-range-before)))
387 | (while (re-search-forward "[a-zA-Z0-9]"
388 | voicemacs-max-symbol-range-after
389 | t)
390 | (let* ((bounds (bounds-of-thing-at-point 'symbol)))
391 | (when bounds
392 | (goto-char (cdr bounds))
393 | ;; Only extract names from code
394 | (unless (or (voicemacs-in-string-p)
395 | (voicemacs-in-comment-p))
396 | (voicemacs--set-add (buffer-substring-no-properties
397 | (car bounds) (cdr bounds))
398 | symbols)))))
399 | symbols)))
400 |
401 |
402 | (defun voicemacs--sync-symbols (&rest _)
403 | ;; TODO: Allow this to cover multiple buffers. Segment by project.
404 | (when (derived-mode-p 'text-mode 'prog-mode)
405 | (setq voicemacs--active-symbols (voicemacs--symbols-in-buffer))))
406 |
407 |
408 | (defun voicemacs--syncable-symbols (&rest _)
409 | ;; TODO: Extract probably from multiple buffers
410 | (voicemacs--set-to-list voicemacs--active-symbols))
411 |
412 |
413 | ;; TODO: Maybe re-enable symbols? Was failing in ein.
414 | ;; (voicemacs-define-sync active-symbols
415 | ;; :update (progn (voicemacs--sync-symbols)
416 | ;; ;; TODO: Only sync if they've changed.
417 | ;; (voicemacs--syncable-symbols))
418 | ;; :enable (progn (add-hook 'first-change-hook sync-func)
419 | ;; (voicemacs--hook-change-buffer sync-func))
420 | ;; :disable (progn (remove-hook 'first-change-hook sync-func)
421 | ;; (voicemacs--unhook-change-buffer sync-func))
422 | ;; :defer t
423 | ;; :delay 0.1)
424 |
425 |
426 | ;; Emacs Metadata
427 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
428 |
429 |
430 | ;; Whether it's Doom/Spacemacs shouldn't change after init - only need to check
431 | ;; once.
432 | (defun voicemacs--check-distribution ()
433 | (voicemacs--update-if-changed
434 | 'is-spacemacs
435 | (if (boundp 'spacemacs-version) t :json-false))
436 |
437 | ;; TODO: Untested. Checks this actually works with doom.
438 | (voicemacs--update-if-changed
439 | 'is-doom
440 | (if (boundp 'doom-version) t :json-false)))
441 |
442 | (add-hook 'after-init-hook 'voicemacs--check-distribution)
443 | ;; Check now in case the hook has been run.
444 | (voicemacs--check-distribution)
445 | ;; Janky on Doom, just re-run it after startup.
446 | (run-with-idle-timer 1 nil 'voicemacs--check-distribution)
447 |
448 |
449 | ;; Misc Commands
450 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
451 |
452 |
453 | (defun voicemacs-increase-text ()
454 | (interactive)
455 | (default-text-scale-mode 1)
456 | (default-text-scale-increase))
457 |
458 |
459 | (defun voicemacs-decrease-text ()
460 | (interactive)
461 | (default-text-scale-mode 1)
462 | (default-text-scale-decrease))
463 |
464 |
465 | (defun voicemacs--yas-will-clear-field? ()
466 | "Is the point in a yas field that will be cleared on insert?"
467 | (let ((current-field (ignore-errors (yas-current-field))))
468 | (and current-field
469 | (not (yas--field-modified-p current-field))
470 | ;; TODO: Imperfect, if user has moved then returned to the start it
471 | ;; won't be erased on insert.
472 | (eq (point) (marker-position (yas--field-start current-field))))))
473 |
474 |
475 | (cl-defun voicemacs-surrounding-text (&key (chars-before 30000)
476 | (chars-after 30000))
477 | "Get `num-chars' on each side of point.
478 |
479 | If the point is in an unaltered yasnippet field, the field will
480 | be altered as soon as the user starts typing - for this reason,
481 | it is ignored. The text around the field will be returned."
482 | (let ((before-end (if (voicemacs--yas-will-clear-field?)
483 | (marker-position (yas--field-start (yas-current-field)))
484 | (point)))
485 | (after-start (if (voicemacs--yas-will-clear-field?)
486 | (marker-position (yas--field-end (yas-current-field)))
487 | (point))))
488 | `((text-before . ,(buffer-substring-no-properties
489 | (max (point-min) (- before-end chars-before))
490 | before-end))
491 | (text-after . ,(buffer-substring-no-properties
492 | after-start
493 | (min (point-max) (+ after-start chars-after)))))))
494 |
495 |
496 | (voicemacs-expose-function 'voicemacs-surrounding-text)
497 |
498 |
499 | (defun voicemacs-switch-to-minibuffer ()
500 | "Switch to minibuffer window (iff active)"
501 | (interactive)
502 | (when (active-minibuffer-window)
503 | (select-frame-set-input-focus (window-frame (active-minibuffer-window)))
504 | (select-window (active-minibuffer-window))))
505 |
506 |
507 | (defun voicemacs-toggle-region ()
508 | "Toggle whether the region is active or not."
509 | (interactive)
510 | (if (region-active-p)
511 | (progn
512 | (deactivate-mark t)
513 | (message "Mark deactivated.")
514 | t)
515 | (activate-mark)
516 | (message "Mark activated")
517 | nil))
518 |
519 |
520 | ;; TODO: Just sync `isearch-forward'?
521 | (defun voicemacs-isearch-dwim (&optional prefix)
522 | "If isearching, repeat direction. Otherwise, start a forward isearch.
523 |
524 | When starting a new search, passes the prefix to the underlying
525 | isearch function."
526 | (interactive "P")
527 | (if isearch-mode
528 | ;; Call interactively so we can use command injection.
529 | (if isearch-forward
530 | (call-interactively 'isearch-repeat-forward)
531 | (call-interactively 'isearch-repeat-backward))
532 | (isearch-forward prefix)))
533 |
534 |
535 | ;; HACK: This can be used by the client to hold off on RPC calls until all
536 | ;; existing input has been processed.
537 | (defun voicemacs-input-pending? ()
538 | "Has all existing input been processed?"
539 | (if (input-pending-p) t :json-false))
540 |
541 | (voicemacs-expose-function 'voicemacs-input-pending?)
542 |
543 |
544 | (defun voicemacs-make-todo (keyword)
545 | "Turn the current line into a TODO item."
546 | (interactive "sTODO Keyword: ")
547 | (unless (voicemacs-in-comment-p)
548 | (comment-line nil))
549 | (goto-char (it-inner-start (it-object-at 'comment)))
550 | (insert keyword)
551 | (insert ": "))
552 |
553 |
554 | (defmacro voicemacs-diff-indentation (&rest body)
555 | "Return the change in indentation at point after running `BODY'.
556 |
557 | Only the line at point is tracked. The region is ignored."
558 | `(let ((indentation-before (current-indentation)))
559 | ,@body
560 | (- (current-indentation) indentation-before)))
561 |
562 |
563 | (defun voicemacs-relative-indent (&optional amount silent?)
564 | "Indent region `AMOUNT' backward from the automatic indentation level.
565 |
566 | If region is not active, operates on the line.
567 |
568 | This method indents the first line using
569 | `indent-according-to-mode', then changes the indentation of the
570 | rest of the block by the same amount. It then moves the block
571 | back `AMOUNT' number of tab stops."
572 | (interactive "P")
573 | (setq amount (or amount 0))
574 |
575 | ;; Indent relative
576 | (if (use-region-p)
577 | ;; Suppress region deactivation
578 | (let (deactivate-mark)
579 | (save-excursion
580 | (let* ((end-marker (copy-marker (region-end)))
581 | (difference (progn
582 | (goto-char (region-beginning))
583 | ;; TODO: Force deactivate?
584 | (deactivate-mark t)
585 | (voicemacs-diff-indentation
586 | (indent-according-to-mode)))))
587 | ;; (echo (point))
588 | ;; (echo end-marker)
589 | ;; Skip first line - we already indented it.
590 | (forward-line 1)
591 | ;; Implementation adapted from `indent.el'
592 | (let ((pr (unless (or silent? (minibufferp))
593 | (make-progress-reporter "Indenting region..." (point) end-marker))))
594 | ;; (echo (point))
595 | ;; (echo end-marker)
596 | (while (< (point) end-marker)
597 | (or (and (bolp) (eolp))
598 | (indent-line-to (+ (current-indentation) difference)))
599 | (forward-line 1)
600 | (and pr (progress-reporter-update pr (point))))
601 | (and pr (progress-reporter-done pr)))
602 | (activate-mark t))))
603 | (indent-according-to-mode))
604 | ;; Now reduce indentation from relative point
605 | (voicemacs-indent-rigidly-left amount)
606 | )
607 |
608 |
609 | (defun voicemacs-indent-rigidly-right (&optional times)
610 | "Indent right to the nearest tab stop(s)."
611 | (interactive "P")
612 | ;; Suppress region deactivation
613 | (let (deactivate-mark)
614 | (dotimes (i (or times 1))
615 | (if (use-region-p)
616 | (progn
617 | (indent-rigidly-right-to-tab-stop (save-excursion
618 | (goto-char (region-beginning))
619 | (deactivate-mark)
620 | (point-at-bol))
621 | (region-end))
622 | (activate-mark))
623 | (indent-rigidly-right-to-tab-stop (point-at-bol)
624 | (point-at-eol))))))
625 |
626 |
627 | (defun voicemacs-indent-rigidly-left (&optional times)
628 | "Indent right to the nearest tab stop(s)."
629 | (interactive "P")
630 | ;; Suppress region deactivation
631 | (let (deactivate-mark)
632 | (dotimes (i (or times 1))
633 | (if (use-region-p)
634 | (progn
635 | (indent-rigidly-left-to-tab-stop (save-excursion
636 | (goto-char (region-beginning))
637 | (deactivate-mark)
638 | (point-at-bol))
639 | (region-end))
640 | (activate-mark))
641 | (indent-rigidly-left-to-tab-stop (point-at-bol)
642 | (point-at-eol))))))
643 |
644 |
645 | (defun voicemacs-set-enable-mark ()
646 | "Set the mark at point (unless it's there already), and enable it."
647 | (interactive)
648 | (unless (= (car mark-ring) (point))
649 | (set-mark (point)))
650 | (activate-mark))
651 |
652 |
653 | ;; Misc Exposed Functions
654 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
655 |
656 |
657 | (voicemacs-expose-function 'x-focus-frame)
658 |
659 |
660 | (defun voicemacs-find-file (path)
661 | "Like `find-file', but returns a JSON-encodable value & has no wildcards."
662 | (if (find-file path) t :json-false))
663 | ;; TODO: Don't like exposing `find-file' tbh
664 | (voicemacs-expose-function 'voicemacs-find-file)
665 |
666 |
667 | (defun voicemacs-insert (text)
668 | "Insert text via RPC, and run relevant hooks.
669 |
670 | This may be faster than inserting key-by-key."
671 | ;; FIXME: Maybe use a higher-level interactive call?
672 | ;; FIXME: Hooks to keys?
673 | (command-execute (lambda () (interactive) (insert text)) t))
674 | (voicemacs-expose-function 'voicemacs-insert)
675 |
676 |
677 | (defun voicemacs-leader-key-details ()
678 | "Gets the current leader key, and whether it was the last key pressed."
679 | (cond ((boundp 'doom-leader-alt-key)
680 | (list doom-leader-alt-key
681 | (or (equal last-input-event (elt (kbd doom-leader-alt-key) 0))
682 | :json-false)))
683 | ((boundp 'dotspacemacs-leader-key)
684 | (list dotspacemacs-leader-key
685 | (or (equal last-input-event (elt (kbd dotspacemacs-leader-key) 0))
686 | :json-false)))
687 | (t '(nil :json-false))))
688 | (voicemacs-expose-function 'voicemacs-leader-key-details)
689 |
690 |
691 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
692 |
693 |
694 | ;; TODO: Pass back the specific frames this voicemacs session is covering. I.e.
695 | ;; the window IDs. (But how to handle WSL?) Or, perhaps just return whether
696 | ;; one of the current frames has focus?
697 |
698 |
699 | (provide 'voicemacs)
700 | ;;; voicemacs.el ends here
701 |
--------------------------------------------------------------------------------