├── CHANGELOG.org
├── LICENSE
├── README.org
├── README_CN.org
├── images
└── screenshots
│ ├── elfeed.png
│ ├── help.png
│ ├── info.png
│ └── nov.png
├── immersive-translate-baidu.el
├── immersive-translate-chatgpt.el
├── immersive-translate-curl.el
├── immersive-translate-deepl.el
├── immersive-translate-trans.el
└── immersive-translate.el
/CHANGELOG.org:
--------------------------------------------------------------------------------
1 | #+title: Emacs-immersive-translate changelog
2 | * v0.3.0(2023-07-24)
3 | ** New feaure: separate front-end and translating backends
4 | - Use =immersive-translate-backend= to select different translation services.
5 | - Use =immersive-translate-backend-alist= to add new backends.
6 | ** Add =immersive-translate--format-translation=
7 | ** Add =Translate-shell= backend
8 | * v0.2.0 (2023-07-21)
9 | ** New feature: enable multiple translation services
10 | Now users can select different translation services by setting =immersive-translate-service=.
11 | ** New feature: add =immersive-translate-auto-mode=
12 |
--------------------------------------------------------------------------------
/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.org:
--------------------------------------------------------------------------------
1 | #+TITLE: immersive-translate: Immersive Bilingual Translation
2 | [[https://melpa.org/#/immersive-translate][file:https://melpa.org/packages/immersive-translate-badge.svg]]
3 |
4 | [[README_CN.org][中文文档]]
5 | * Introductions
6 | Inspired by [[https://github.com/immersive-translate/immersive-translate][immersive-translate/immersive-translate]], I have implemented similar functionality in Emacs.
7 | * Screenshots
8 | ** elfeed
9 | [[images/screenshots/elfeed.png]]
10 | ** nov
11 | [[images/screenshots/nov.png]]
12 | ** info
13 | [[images/screenshots/info.png]]
14 | ** helpful/help
15 | [[images/screenshots/help.png]]
16 | * Installation
17 | 1. You need to install [[https://curl.se/][curl]] on your device first. If you want to use the translate-shell backend, you also need to install [[https://github.com/soimort/translate-shell][translate-shell]].
18 | 2. ~M-x package-install RET gptel RET~
19 |
20 | #+begin_src emacs-lisp
21 | (require 'immersive-translate)
22 | (add-hook 'elfeed-show-mode-hook #'immersive-translate-setup)
23 | (add-hook 'nov-pre-html-render-hook #'immersive-translate-setup)
24 | ;; use Baidu Translation
25 | (setq immersive-translate-backend 'baidu
26 | immersive-translate-baidu-appid "your-appid")
27 |
28 | ;; use ChatGPT
29 | ;; (setq immersive-translate-backend 'chatgpt
30 | ;; immersive-translate-chatgpt-host "api.openai.com")
31 |
32 | ;; use translate-shell
33 | ;; (setq immersive-translate-backend 'trans)
34 |
35 | #+end_src
36 | * Usage
37 | - =immersive-translate-buffer=
38 |
39 | Translate the current buffer. /Note/: This may consume a large number of tokens.
40 |
41 | - =immersive-translate-paragraph=
42 |
43 | Translate the current paragraph.
44 |
45 | - =immersive-translate-clear=
46 |
47 | Clear all translated text.
48 |
49 | - =immersive-translate-auto-mode=
50 |
51 | Translate, when enabled, automatically translate the visible portion of the current window.
52 |
53 | *Note*: Some translation services (e.g. baidu translation) has QPS(Queries Per Second) limits, so it is recommended to use =immersive-translate-auto-mode= instead of =immersive-translate-buffer= while using these services.
54 |
55 | - =immersive-translate-abort=
56 |
57 | Stop all ongoing translation processes in the current buffer.
58 | * Customization
59 | - =immersive-translate-backend=
60 |
61 | The translation backend used. See [[#api_key][API setting]] for details.
62 |
63 | Currently available translation services:
64 | - chatgpt (https://openai.com/api/)
65 | - baidu (https://fanyi-api.baidu.com/)
66 | - translate-shell (https://github.com/soimort/translate-shell)
67 | - DeepL (https://www.deepl.com/docs-api/translate-text/translate-text)
68 |
69 | - =immersive-translate-auto-idle=
70 |
71 | After enabling =immersive-translate-auto-mode=, the Emacs idle time required for the next translation to be executed.
72 |
73 | - =immersive-translate-exclude-shr-tag=
74 |
75 | The text contained in the tags of this variable will not be translated. This variable applies to all buffers generated by =shr.el=, such as buffers in =elfeed-show-mode=, =nov-mode=, and =mu4e-view-mode=.
76 |
77 | - =immersive-translate-chatgpt-system-prompt=
78 |
79 | System prompt used by ChatGPT.
80 |
81 | - =immersive-translate-chatgpt-user-prompt=
82 |
83 | User prompt used by ChatGPT.
84 |
85 | - =immersive-translate-disable-predicates=
86 |
87 | When the current paragraph does not need to be translated, return =t=. These functions in this list do not accept any parameters.
88 |
89 | - =immersive-translate-pending-message=
90 |
91 | Text displayed before the translation results are returned.
92 |
93 | - =immersive-translate-failed-message=
94 |
95 | Text displayed when translation fails.
96 |
97 | See =M-x customize-group RET immersive-translate RET= for details.
98 | * API setting
99 | :PROPERTIES:
100 | :CUSTOM_ID: api_key
101 | :END:
102 | The translation service of this plugin requires you to apply for the corresponding API key of the service in order to use it. For more details, please refer to [[https://immersivetranslate.com/docs/services/][Translation Service API Application]]
103 |
104 | This plugin retrieves the user's key through the built-in =auth-source.el=.
105 |
106 | 1. ChatGPT
107 |
108 | Assuming your =immersive-translate-chatgpt-host= is "api.openai.com" and the API key is 123456, add the following text to =~/.authinfo=:
109 |
110 | #+begin_example
111 | machine api.openai.com login apikey password 123456
112 | #+end_example
113 |
114 | 2. Baidu Translate
115 |
116 | Assuming your =immersive-translate-baidu-appid= is "foobar" and the API key is 123456, add the following text to =~/.authinfo=:
117 | #+begin_example
118 | machine fanyi-api.baidu.com login foobar password 123456
119 | #+end_example
120 |
121 | 3. DeepL
122 |
123 | Assuming your API key is 123456, add the following text to =~/.authinfo=:
124 |
125 | #+begin_example
126 | machine deepl.com login apikey password 123456
127 | #+end_example
128 | * Add a new translation backend (PRs welcome!)
129 | ** Add online translation service
130 | If you want to add new translation services, you can check the variables =immersive-translate-curl-get-translation-alist= and =immersive-translate-curl-get-args-alist=.
131 |
132 | The function in the variable =immersive-translate-curl-get-args-alist= is used to construct the input parameters required when making a request.
133 |
134 | The function in the variable =immersive-translate-curl-get-translation-alist= is used to parse the translation results returned by =curl=.
135 | ** Add local translation services
136 | See [[immersive-translate-trans.el]]
137 |
--------------------------------------------------------------------------------
/README_CN.org:
--------------------------------------------------------------------------------
1 | #+TITLE: immersive-translate: Immersive Bilingual Translation (WIP)
2 | [[https://melpa.org/#/immersive-translate][file:https://melpa.org/packages/immersive-translate-badge.svg]]
3 | * 项目简介
4 | 受 [[https://github.com/immersive-translate/immersive-translate][immersive-translate/immersive-translate]] 的启发,在 Emacs 中实现了类似的功能。
5 | * 使用截图
6 | ** elfeed
7 | [[images/screenshots/elfeed.png]]
8 | ** nov
9 | [[images/screenshots/nov.png]]
10 | ** info
11 | [[images/screenshots/info.png]]
12 | ** helpful/help
13 | [[images/screenshots/help.png]]
14 | * 安装
15 | 您的设备上需要先安装 [[https://curl.se/][curl]] ,如果需要使用 translate-shell 后端,则需要安装
16 | [[https://github.com/soimort/translate-shell][translate-shell]] 。
17 | #+begin_src emacs-lisp
18 | (require 'immersive-translate)
19 | (add-hook 'elfeed-show-mode-hook #'immersive-translate-setup)
20 | (add-hook 'nov-pre-html-render-hook #'immersive-translate-setup)
21 | ;; use Baidu Translation
22 | (setq immersive-translate-backend 'baidu
23 | immersive-translate-baidu-appid "your-appid")
24 |
25 | ;; use ChatGPT
26 | ;; (setq immersive-translate-backend 'chatgpt
27 | ;; immersive-translate-chatgpt-host "api.openai.com")
28 |
29 | ;; use translate-shell
30 | ;; (setq immersive-translate-backend 'trans)
31 |
32 | #+end_src
33 | * 使用
34 | - =immersive-translate-buffer=
35 |
36 | 翻译当前 buffer 。 *注意*: 这可能会消耗大量 Token 。
37 |
38 | - =immersive-translate-paragraph=
39 |
40 | 翻译当前段落。
41 |
42 | - =immersive-translate-clear=
43 |
44 | 清除所有翻译文本。
45 |
46 | - =immersive-translate-auto-mode=
47 |
48 | 开启后,自动翻译当前窗口可见部分的内容。
49 |
50 | *注意*: 一些翻译服务(如百度翻译)有每秒查询限制(QPS),因此建议在使用这些服务
51 | 时使用 =immersive-translate-auto-mode= 而不是 =immersive-translate-buffer= 。
52 |
53 | - =immersive-translate-abort=
54 |
55 | 停止当前 buffer 所有的正在进行的翻译进程。
56 | * 自定义设置
57 | - =immersive-translate-backend=
58 |
59 | 所使用的翻译后端。详见 [[#api_key][API 密钥设置]] 一节。
60 |
61 | 目前可用的翻译服务
62 | - chatgpt (https://openai.com/api/)
63 | - baidu (https://fanyi-api.baidu.com/)
64 | - translate-shell (https://github.com/soimort/translate-shell)
65 | - DeepL (https://www.deepl.com/docs-api/translate-text/translate-text)
66 |
67 | - =immersive-translate-auto-idle=
68 |
69 | 开启 =immersive-translate-auto-mode= 后,执行下次翻译时所需要的 Emacs 空闲时间。
70 |
71 | - =immersive-translate-exclude-shr-tag=
72 |
73 | 此变量中的标签所包含的文本都不会翻译 。此变量适用于所有由 =shr.el= 生成的 buffer,
74 | 如 =elfeed-show-mode= 、=nov-mode= 和 =mu4e-view-mode= 中的 buffer 。
75 |
76 | - =immersive-translate-chatgpt-system-prompt=
77 |
78 | System prompt used by ChatGPT.
79 |
80 | - =immersive-translate-chatgpt-user-prompt=
81 |
82 | User prompt used by ChatGPT.
83 |
84 | - =immersive-translate-disable-predicates=
85 |
86 | 当当前段落不需要翻译时,返回 =t= 。此列表中的函数不接受任何参数。
87 |
88 | - =immersive-translate-pending-message=
89 |
90 | 在返回翻译结果之前显示的文本。
91 |
92 | - =immersive-translate-failed-message=
93 |
94 | 翻译失败时显示的文本。
95 |
96 |
97 | 更多自定义配置见:=M-x customize-group RET immersive-translate RET=
98 | * API 密钥设置
99 | :PROPERTIES:
100 | :CUSTOM_ID: api_key
101 | :END:
102 | 此插件的翻译服务需要你申请对应服务的 API 密钥才能使用,详见
103 | [[https://immersivetranslate.com/docs/services/][翻译服务 API 申请]] 。
104 |
105 | 此插件通过内置的 =auth-source.el= 来获取用户的密钥:
106 |
107 | 1. ChatGPT
108 |
109 | 假设您的 =immersive-translate-chatgpt-host= 为 "api.openai.com" , API 密钥为
110 | 123456 。则在 =~/.authinfo= 中添加如下文本:
111 | #+begin_example
112 | machine api.openai.com login apikey password 123456
113 | #+end_example
114 |
115 | 2. 百度翻译
116 |
117 | 假设您的 =immersive-translate-baidu-appid= 为 "foobar" ,API 密钥为123456 。则在
118 | =~/.authinfo= 中添加如下文本:
119 | #+begin_example
120 | machine fanyi-api.baidu.com login foobar password 123456
121 | #+end_example
122 |
123 | 3. DeepL
124 |
125 | 假设您的 API 密钥 123456, 则在 =~/.authinfo= 中添加如下文本:
126 |
127 | #+begin_example
128 | machine deepl.com login apikey password 123456
129 | #+end_example
130 |
131 | * 添加新的翻译后端 (欢迎 PR!)
132 | ** 添加在线翻译服务
133 | 如果想要添加新的翻译服务,可以查看变量
134 | =immersive-translate-curl-get-translation-alist= 和
135 | =immersive-translate-curl-get-args-alist= 。
136 |
137 | 变量 =immersive-translate-curl-get-args-alist= 中的函数用于构造请求时所需的输入
138 | 参数。
139 |
140 | 变量 =immersive-translate-curl-get-translation-alist= 中的函数用于解析 =curl= 返回的
141 | 翻译结果。
142 | ** 添加本地翻译软件
143 | 参考 [[immersive-translate-trans.el]]
144 |
--------------------------------------------------------------------------------
/images/screenshots/elfeed.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Elilif/emacs-immersive-translate/1d00d558363985fa988fc40cd5093bfc6926d83e/images/screenshots/elfeed.png
--------------------------------------------------------------------------------
/images/screenshots/help.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Elilif/emacs-immersive-translate/1d00d558363985fa988fc40cd5093bfc6926d83e/images/screenshots/help.png
--------------------------------------------------------------------------------
/images/screenshots/info.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Elilif/emacs-immersive-translate/1d00d558363985fa988fc40cd5093bfc6926d83e/images/screenshots/info.png
--------------------------------------------------------------------------------
/images/screenshots/nov.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Elilif/emacs-immersive-translate/1d00d558363985fa988fc40cd5093bfc6926d83e/images/screenshots/nov.png
--------------------------------------------------------------------------------
/immersive-translate-baidu.el:
--------------------------------------------------------------------------------
1 | ;;; immersive-translate-baidu.el --- baidu translation backend -*- lexical-binding: t; -*-
2 |
3 | ;; Copyright (C) 2023 Eli Qian
4 |
5 | ;; Author: Eli Qian
6 | ;; Url: https://github.com/Elilif/emacs-immersive-translate
7 |
8 | ;; Version: 0.3.0
9 | ;; SPDX-License-Identifier: GPL-3.0-or-later
10 |
11 |
12 | ;;; Commentary:
13 | ;;
14 |
15 | (require 'immersive-translate-curl)
16 |
17 | ;;; Code:
18 |
19 | (declare-function immersive-translate-api-key "ext:immersive-translate")
20 | (declare-function immersive-translate-clear "ext:immersive-translate")
21 |
22 | (defgroup immersive-translate-baidu nil
23 | "Immersive translate baidu backend."
24 | :group 'immersive-translate)
25 |
26 | (defcustom immersive-translate-baidu-source-language "en"
27 | "The source language.
28 |
29 | See https://fanyi-api.baidu.com/doc/21 for more defails."
30 | :group 'immersive-translate-baidu
31 | :type 'string)
32 |
33 | (defcustom immersive-translate-baidu-target-language "zh"
34 | "The target language.
35 |
36 | See https://fanyi-api.baidu.com/doc/21 for more defails."
37 | :group 'immersive-translate-baidu
38 | :type 'string)
39 |
40 | (defcustom immersive-translate-baidu-appid ""
41 | "The appid used by Baidu Trasnlate API.
42 |
43 | See https://fanyi-api.baidu.com/doc/21 for more defails."
44 | :group 'immersive-translate-baidu
45 | :type 'string)
46 |
47 | (defvar immersive-translate-baidu-salt (number-to-string (random 10000)))
48 |
49 |
50 | (defun immersive-translate-baidu-generate-sign (content)
51 | "Generate the sign used by Baidu Trasnlate API.
52 |
53 | CONTENT is the text to be translated.
54 | See https://fanyi-api.baidu.com/doc/21 for more defails."
55 | (md5 (concat
56 | immersive-translate-baidu-appid
57 | content
58 | immersive-translate-baidu-salt
59 | (immersive-translate-api-key
60 | "fanyi-api.baidu.com"
61 | immersive-translate-baidu-appid))))
62 |
63 | (defun immersive-translate-baidu--request-data (content)
64 | "Generate data in POST request.
65 |
66 | CONTENT is the text to be translated.
67 | See https://fanyi-api.baidu.com/doc/21 for more defails."
68 | (if (not (string-empty-p immersive-translate-baidu-appid))
69 | (format "q=%s&from=%s&to=%s&appid=%s&salt=%s&sign=%s"
70 | content
71 | immersive-translate-baidu-source-language
72 | immersive-translate-baidu-target-language
73 | immersive-translate-baidu-appid
74 | immersive-translate-baidu-salt
75 | (immersive-translate-baidu-generate-sign content))
76 | (immersive-translate-clear)
77 | (user-error "Please set `immersive-translate-baidu-appid'!")))
78 |
79 | (defun immersive-translate-baidu-get-args (content token)
80 | "Produce list of arguments for calling Curl.
81 |
82 | CONTENT is the text to be translated, TOKEN is a unique
83 | identifier."
84 | (let* ((url "https://fanyi-api.baidu.com/api/trans/vip/translate")
85 | (data (encode-coding-string
86 | (immersive-translate-baidu--request-data content)
87 | 'utf-8))
88 | (headers
89 | '(("Content-Type" . "application/x-www-form-urlencoded"))))
90 | (append
91 | (list "--location" "--silent" "--compressed" "--disable"
92 | (format "-X%s" "POST")
93 | (format "-w(%s . %%{size_header})" token)
94 | (format "-m%s" 60)
95 | "-D-"
96 | (format "-d%s" data))
97 | (cl-loop for (key . val) in headers
98 | collect (format "-H%s: %s" key val))
99 | (list url))))
100 |
101 | (defun immersive-translate-curl-baidu-get-translation (response)
102 | "Get the translated text in RESPONSE returned by BAIDU."
103 | (or (map-nested-elt response '(:trans_result 0 :dst))
104 | (let ((result (concat
105 | (plist-get response :error_code)
106 | ": "
107 | (plist-get response :error_msg))))
108 | (propertize result 'error t))))
109 |
110 | (add-to-list 'immersive-translate-curl-get-translation-alist
111 | '(baidu . immersive-translate-curl-baidu-get-translation))
112 |
113 | (add-to-list 'immersive-translate-curl-get-args-alist
114 | '(baidu . immersive-translate-baidu-get-args))
115 |
116 | (defun immersive-translate-baidu-translate (info &optional callback)
117 | "Translate the content in INFO using Baidu Translation.
118 |
119 | INFO is a plist with the following keys:
120 | - :content (the text needed to be translated)
121 | - :buffer (the current buffer)
122 | - :position (marker at which to insert the response).
123 |
124 | Call CALLBACK with the response and INFO afterwards. If omitted
125 | the response is inserted into the current buffer after point."
126 | (immersive-translate-curl-do 'baidu info callback))
127 |
128 | (provide 'immersive-translate-baidu)
129 | ;;; immersive-translate-baidu.el ends here
130 |
--------------------------------------------------------------------------------
/immersive-translate-chatgpt.el:
--------------------------------------------------------------------------------
1 | ;;; immersive-translate-chatgpt.el --- chatgpt backend for immersive-translation -*- lexical-binding: t; -*-
2 |
3 | ;; Based on work by
4 | ;; Copyright (C) 2023 Karthik Chikmagalur
5 | ;; Original Author: Karthik Chikmagalur;;
6 | ;; Keywords: convenience
7 |
8 | ;; SPDX-License-Identifier: GPL-3.0-or-later
9 |
10 | ;; This program is free software; you can redistribute it and/or modify
11 | ;; it under the terms of the GNU General Public License as published by
12 | ;; the Free Software Foundation, either version 3 of the License, or
13 | ;; (at your option) any later version.
14 |
15 | ;; This program is distributed in the hope that it will be useful,
16 | ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 | ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 | ;; GNU General Public License for more details.
19 |
20 | ;; You should have received a copy of the GNU General Public License
21 | ;; along with this program. If not, see .
22 |
23 |
24 | ;;; Commentary:
25 | ;; 2023/07/21
26 | ;; Most of the code in this file is taken from
27 | ;; https://github.com/karthink/gptel/blob/master/gptel-curl.el, with the
28 | ;; following modifications:
29 | ;; 1. Renamed function and variable names.
30 | ;; 3. Modified part of the code to fit this project.
31 |
32 |
33 | ;;; Code:
34 |
35 | (require 'immersive-translate-curl)
36 |
37 | (declare-function immersive-translate-api-key "ext:immersive-translate")
38 |
39 | (defgroup immersive-translate-chatgpt nil
40 | "Immersive translate chatgpt backend."
41 | :group 'immersive-translate)
42 |
43 | (defcustom immersive-translate-chatgpt-host "api.openai.com"
44 | "The OpenAI API host queried by immersive-translate."
45 | :group 'immersive-translate-chatgpt
46 | :type 'string)
47 |
48 | (defcustom immersive-translate-chatgpt-model "gpt-3.5-turbo-0613"
49 | "GPT Model for chat.
50 |
51 | The current options are
52 | - \"gpt-3.5-turbo\"
53 | - \"gpt-3.5-turbo-16k\"
54 | - \"gpt-4\" (experimental)
55 | - \"gpt-4-32k\" (experimental)"
56 | :group 'immersive-translate-chatgpt
57 | :type '(choice
58 | (const :tag "GPT 3.5 turbo" "gpt-3.5-turbo")
59 | (const :tag "GPT 3.5 turbo 16k" "gpt-3.5-turbo-16k")
60 | (const :tag "GPT 4 (experimental)" "gpt-4")
61 | (const :tag "GPT 4 32k (experimental)" "gpt-4-32k")))
62 |
63 | (defcustom immersive-translate-chatgpt-temperature 0.7
64 | "\"Temperature\" of ChatGPT response.
65 |
66 | This is a number between 0.0 and 2.0 that controls the randomness
67 | of the response, with 2.0 being the most random."
68 | :group 'immersive-translate-chatgpt
69 | :type 'number)
70 |
71 | (defcustom immersive-translate-chatgpt-proxy ""
72 | "Path to a proxy to use for ChatGPT query.
73 | Passed to curl via --proxy arg, for example \"proxy.yourorg.com:80\"
74 | Leave it empty if you don't use a proxy."
75 | :group 'immersive-translate-chatgpt
76 | :type 'string)
77 |
78 | (defcustom immersive-translate-chatgpt-system-prompt "You are a professional translator."
79 | "System prompt used by ChatGPT."
80 | :group 'immersive-translate-chatgpt
81 | :type 'string)
82 |
83 | (defcustom immersive-translate-chatgpt-user-prompt "You will be provided with text delimited by triple backticks, your task is to translate the wrapped text into Chinese. You should only output the translated text. \n```%s```"
84 | "User prompt used by ChatGPT."
85 | :group 'immersive-translate-chatgpt
86 | :type 'string)
87 |
88 | (defun immersive-translate-chatgpt--request-data (prompts)
89 | "Encode data into JSON format..
90 |
91 | Argument PROMPTS are for sending to chatgpt."
92 | (let ((prompts-plist
93 | `(:model ,immersive-translate-chatgpt-model
94 | :messages [,@prompts])))
95 | (plist-put prompts-plist :temperature immersive-translate-chatgpt-temperature)
96 | prompts-plist))
97 |
98 | (defun immersive-translate-chatgpt-get-args (prompts token)
99 | "Produce list of arguments for calling Curl.
100 |
101 | PROMPTS is the data to send, TOKEN is a unique identifier."
102 | (let* ((url (format "https://%s/v1/chat/completions"
103 | immersive-translate-chatgpt-host))
104 | (data (encode-coding-string
105 | (json-encode (immersive-translate-chatgpt--request-data prompts))
106 | 'utf-8))
107 | (headers
108 | `(("Content-Type" . "application/json")
109 | ("Authorization" . ,(concat "Bearer " (immersive-translate-api-key
110 | immersive-translate-chatgpt-host
111 | "apikey"))))))
112 | (append
113 | (list "--location" "--silent" "--compressed" "--disable"
114 | (format "-X%s" "POST")
115 | (format "-w(%s . %%{size_header})" token)
116 | (format "-m%s" 60)
117 | "-D-"
118 | (format "-d%s" data))
119 | (when (not (string-empty-p immersive-translate-chatgpt-proxy))
120 | (list "--proxy" immersive-translate-chatgpt-proxy
121 | "--proxy-negotiate"
122 | "--proxy-user" ":"))
123 | (cl-loop for (key . val) in headers
124 | collect (format "-H%s: %s" key val))
125 | (list url))))
126 |
127 | (defun immersive-translate-chatgpt-create-prompt (content)
128 | "Create a full prompt suitable for sending to ChatGPT.
129 |
130 | CONTENT is the text to be translated."
131 | (let ((user-prompt (format immersive-translate-chatgpt-user-prompt content)))
132 | `((:role "system" :content ,immersive-translate-chatgpt-system-prompt)
133 | (:role "user" :content ,user-prompt))))
134 |
135 | (defun immersive-translate-curl-chatgpt-get-translation (response)
136 | "Get the translated text in RESPONSE returned by CHATGPT."
137 | (map-nested-elt response '(:choices 0 :message :content)))
138 |
139 | (add-to-list 'immersive-translate-curl-get-translation-alist
140 | '(chatgpt . immersive-translate-curl-chatgpt-get-translation))
141 |
142 | (add-to-list 'immersive-translate-curl-get-args-alist
143 | '(chatgpt . immersive-translate-chatgpt-get-args))
144 |
145 | (defun immersive-translate-chatgpt-translate (info &optional callback)
146 | "Translate the content in INFO using ChatGPT.
147 |
148 | INFO is a plist with the following keys:
149 | - :content (the text needed to be translated)
150 | - :buffer (the current buffer)
151 | - :position (marker at which to insert the response).
152 |
153 | Call CALLBACK with the response and INFO afterwards. If omitted
154 | the response is inserted into the current buffer after point."
155 | (immersive-translate-curl-do 'chatgpt info callback))
156 |
157 | (provide 'immersive-translate-chatgpt)
158 | ;;; immersive-translate-chatgpt.el ends here
159 |
--------------------------------------------------------------------------------
/immersive-translate-curl.el:
--------------------------------------------------------------------------------
1 | ;;; immersive-translate-curl.el --- curl support -*- lexical-binding: t; -*-
2 |
3 | ;; Based on work by
4 | ;; Copyright (C) 2023 Karthik Chikmagalur
5 | ;; Original Author: Karthik Chikmagalur;;
6 | ;; Keywords: convenience
7 |
8 | ;; SPDX-License-Identifier: GPL-3.0-or-later
9 |
10 | ;; This program is free software; you can redistribute it and/or modify
11 | ;; it under the terms of the GNU General Public License as published by
12 | ;; the Free Software Foundation, either version 3 of the License, or
13 | ;; (at your option) any later version.
14 |
15 | ;; This program is distributed in the hope that it will be useful,
16 | ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 | ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 | ;; GNU General Public License for more details.
19 |
20 | ;; You should have received a copy of the GNU General Public License
21 | ;; along with this program. If not, see .
22 |
23 | ;;; Commentary:
24 | ;; 2023/07/21
25 | ;; Most of the code in this file is taken from
26 | ;; https://github.com/karthink/gptel/blob/master/gptel-curl.el, with the
27 | ;; following modifications:
28 | ;; 1. Renamed function and variable names.
29 | ;; 2. Removed code related to streaming input.
30 | ;; 3. Modified part of the code to fit this project.
31 |
32 |
33 | ;;; Code:
34 |
35 | (eval-when-compile
36 | (require 'cl-lib)
37 | (require 'subr-x))
38 | (require 'map)
39 | (require 'json)
40 |
41 | (defvar immersive-translate--process-alist)
42 | (defvar immersive-translate-failed-message)
43 | (declare-function immersive-translate-callback "ext:immersive-translate")
44 |
45 | (defgroup immersive-translate-curl nil
46 | "Immersive translate curl lib."
47 | :group 'immersive-translate)
48 |
49 | (defcustom immersive-translate-curl-get-translation-alist '()
50 | "Alist of functions to get the translated text.
51 |
52 | Each element looks like (SERVICE . FUNCTION);
53 |
54 | SERVICE is the translation service, see
55 | `immersive-translate-service'; FUNCTION is a function of one
56 | argument, called with RESPONSE (a JSON object) returned in
57 | `immersive-translate-curl--parse-response'."
58 | :group 'immersive-translate-curl
59 | :type '(alist :key-type symbol :value-type function))
60 |
61 | (defcustom immersive-translate-curl-get-args-alist '()
62 | "Alist of functions to produce list of arguments for calling Curl. .
63 |
64 | Each element looks like (SERVICE . FUNCTION);
65 |
66 | SERVICE is the translation service; FUNCTION is a function of two
67 | arguments, called with CONTENT and TOKEN.
68 |
69 | CONTENT is the data to send, TOKEN is a unique identifier."
70 | :group 'immersive-translate-curl
71 | :type '(alist :key-type symbol :value-type function))
72 |
73 | (defun immersive-translate-curl--parse-response (buf token service)
74 | "Parse the buffer BUF with curl's response.
75 |
76 | TOKEN is used to disambiguate multiple requests in a single
77 | buffer. SERVICE is the translation API to use."
78 | (with-current-buffer buf
79 | (progn
80 | (goto-char (point-max))
81 | (search-backward token)
82 | (backward-char)
83 | (pcase-let* ((`(,_ . ,header-size) (read (current-buffer))))
84 | (goto-char (point-min))
85 |
86 | (if-let* ((http-msg (string-trim
87 | (buffer-substring (line-beginning-position)
88 | (line-end-position))))
89 | (http-status
90 | (save-match-data
91 | (and (string-match "HTTP/[.0-9]+ +\\([0-9]+\\)" http-msg)
92 | (match-string 1 http-msg))))
93 | (json-object-type 'plist)
94 | (response (progn (goto-char header-size)
95 | (condition-case nil
96 | (json-read)
97 | (json-readtable-error 'json-read-error)))))
98 | (cond
99 | ((equal http-status "200")
100 | (list (string-trim
101 | (or (funcall (alist-get
102 | service
103 | immersive-translate-curl-get-translation-alist)
104 | response)
105 | ""))
106 | http-msg))
107 | ((plist-get response :error)
108 | (let* ((error-plist (plist-get response :error))
109 | (error-msg (plist-get error-plist :message))
110 | (error-type (plist-get error-plist :type)))
111 | (list nil (concat "(" http-msg ") " (string-trim error-type)) error-msg)))
112 | ((eq response 'json-read-error)
113 | (list nil (concat "(" http-msg ") Malformed JSON in response.")
114 | "Malformed JSON in response"))
115 | (t (list nil (concat "(" http-msg ") Could not parse HTTP response.")
116 | "Could not parse HTTP response.")))
117 | (list nil (concat "(" http-msg ") Could not parse HTTP response.")
118 | "Could not parse HTTP response."))))))
119 |
120 | (defun immersive-translate-curl--sentinel (process _status)
121 | "Process sentinel for immersive-translate curl requests.
122 |
123 | PROCESS and _STATUS are process parameters."
124 | (let ((proc-buf (process-buffer process)))
125 | (when-let* (((eq (process-status process) 'exit))
126 | (proc-info (alist-get process immersive-translate--process-alist))
127 | (proc-token (plist-get proc-info :token))
128 | (proc-content (plist-get proc-info :content))
129 | (proc-callback (plist-get proc-info :callback))
130 | (proc-service (plist-get proc-info :service)))
131 | (pcase-let ((`(,response ,http-msg ,error)
132 | (immersive-translate-curl--parse-response proc-buf proc-token proc-service)))
133 | (plist-put proc-info :status http-msg)
134 | (when error (plist-put proc-info :error error))
135 | (when (and (plist-get proc-info :retry)
136 | (or (string-empty-p response)
137 | (get-text-property 0 'error response)))
138 | (setq response (concat
139 | response
140 | " "
141 | immersive-translate-failed-message))
142 | (funcall proc-callback response proc-info))
143 | (when (and proc-content
144 | (or (string-empty-p response)
145 | (get-text-property 0 'error response))
146 | (not (plist-get proc-info :retry)))
147 | (plist-put proc-info :retry t)
148 | (immersive-translate-curl-do proc-service proc-info proc-callback))
149 | (unless (plist-get proc-info :retry)
150 | (funcall proc-callback response proc-info))))
151 | (setf (alist-get process immersive-translate--process-alist nil 'remove) nil)
152 | (kill-buffer proc-buf)))
153 |
154 | (defun immersive-translate-curl-do (service info &optional callback)
155 | "Retrieve response to content in INFO.
156 |
157 | SERVICE is the translation API to use.Service.
158 | INFO is a plist with the following keys:
159 | - :content (the text needed to be translated)
160 | - :buffer (the current buffer)
161 | - :position (marker at which to insert the response).
162 |
163 | Call CALLBACK with the response and INFO afterwards. If omitted
164 | the response is inserted into the current buffer after point."
165 | (let* ((token (md5 (format "%s%s%s%s"
166 | (random) (emacs-pid) (user-full-name)
167 | (recent-keys))))
168 | (func (alist-get service immersive-translate-curl-get-args-alist))
169 | (args (funcall func (plist-get info :content) token))
170 | (process (apply #'start-process "immersive-translate-curl"
171 | (generate-new-buffer "*immersive-translate-curl*") "curl" args)))
172 | (with-current-buffer (process-buffer process)
173 | (set-process-query-on-exit-flag process nil)
174 | (setf (alist-get process immersive-translate--process-alist)
175 | (nconc (list
176 | :token token
177 | :service service
178 | :callback (or callback
179 | #'immersive-translate-callback))
180 | info))
181 | (set-process-sentinel process #'immersive-translate-curl--sentinel))))
182 |
183 | (provide 'immersive-translate-curl)
184 | ;;; immersive-translate-curl.el ends here
185 |
--------------------------------------------------------------------------------
/immersive-translate-deepl.el:
--------------------------------------------------------------------------------
1 | ;;; immersive-translate-deepl.el --- DeepL translation backend -*- lexical-binding: t; -*-
2 |
3 | ;; Copyright (C) 2023 Eli Qian
4 |
5 | ;; Author: Eli Qian
6 | ;; Url: https://github.com/Elilif/emacs-immersive-translate
7 |
8 | ;; Version: 0.3.0
9 | ;; SPDX-License-Identifier: GPL-3.0-or-later
10 |
11 |
12 | ;;; Commentary:
13 | ;;
14 |
15 | (require 'immersive-translate-curl)
16 |
17 | ;;; Code:
18 |
19 | (declare-function immersive-translate-api-key "ext:immersive-translate")
20 | (declare-function immersive-translate-clear "ext:immersive-translate")
21 |
22 | (defgroup immersive-translate-deepl nil
23 | "Immersive translate deepl backend."
24 | :group 'immersive-translate)
25 |
26 | (defcustom immersive-translate-deepl-target-language "ZH"
27 | "The target language.
28 |
29 | See https://www.deepl.com/docs-api/translate-text/translate-text
30 | for more defails."
31 | :group 'immersive-translate-deepl
32 | :type 'string)
33 |
34 | (defcustom immersive-translate-deepl-source-language "EN"
35 | "The source language.
36 |
37 | See https://www.deepl.com/docs-api/translate-text/translate-text
38 | for more defails."
39 | :group 'immersive-translate-deepl
40 | :type 'string)
41 |
42 | (defcustom immersive-translate-deepl-api "https://api-free.deepl.com/v2/translate"
43 | "DeepL API.
44 |
45 | See https://www.deepl.com/docs-api/translate-text/translate-text
46 | for more defails."
47 | :group 'immersive-translate-deepl
48 | :type 'string)
49 |
50 | (defun immersive-translate-deepl--request-data (content)
51 | "Encode data into JSON format..
52 |
53 | Argument PROMPTS are for sending to DeepL."
54 | `(("text" . (,content))
55 | ("source_lang" . ,immersive-translate-deepl-source-language)
56 | ("target_lang" . ,immersive-translate-deepl-target-language)))
57 |
58 | (defun immersive-translate-deepl-get-args (content token)
59 | "Produce list of arguments for calling Curl.
60 |
61 | CONTENT is the text to be translated, TOKEN is a unique
62 | identifier."
63 | (let* ((url immersive-translate-deepl-api)
64 | (data (encode-coding-string
65 | (json-encode (immersive-translate-deepl--request-data content))
66 | 'utf-8))
67 | (headers
68 | `(("Content-Type" . "application/json")
69 | ("Authorization" . ,(concat "DeepL-Auth-Key "
70 | (immersive-translate-api-key
71 | "deepl.com"
72 | "apikey"))))))
73 | (append
74 | (list "--location" "--silent" "--compressed" "--disable"
75 | (format "-X%s" "POST")
76 | (format "-w(%s . %%{size_header})" token)
77 | (format "-m%s" 60)
78 | "-D-"
79 | (format "-d%s" data))
80 | (cl-loop for (key . val) in headers
81 | collect (format "-H%s: %s" key val))
82 | (list url))))
83 |
84 | (defun immersive-translate-curl-deepl-get-translation (response)
85 | "Get the translated text in RESPONSE returned by DeepL."
86 | (or (map-nested-elt response '(:translations 0 :text))
87 | (let ((result (plist-get response :message)))
88 | (propertize result 'error t))))
89 |
90 | (add-to-list 'immersive-translate-curl-get-translation-alist
91 | '(deepl . immersive-translate-curl-deepl-get-translation))
92 |
93 | (add-to-list 'immersive-translate-curl-get-args-alist
94 | '(deepl . immersive-translate-deepl-get-args))
95 |
96 | (defun immersive-translate-deepl-translate (info &optional callback)
97 | "Translate the content in INFO using Baidu Translation.
98 |
99 | INFO is a plist with the following keys:
100 | - :content (the text needed to be translated)
101 | - :buffer (the current buffer)
102 | - :position (marker at which to insert the response).
103 |
104 | Call CALLBACK with the response and INFO afterwards. If omitted
105 | the response is inserted into the current buffer after point."
106 | (immersive-translate-curl-do 'deepl info callback))
107 |
108 | (provide 'immersive-translate-deepl)
109 | ;;; immersive-translate-deepl.el ends here
110 |
--------------------------------------------------------------------------------
/immersive-translate-trans.el:
--------------------------------------------------------------------------------
1 | ;;; immersive-translate-trans.el --- Translate-shell backend for immersive-translate -*- lexical-binding: t; -*-
2 |
3 | ;; Copyright (C) 2023 Eli Qian
4 |
5 | ;; Author: Eli Qian
6 | ;; Url: https://github.com/Elilif/emacs-immersive-translate
7 |
8 | ;; Version: 0.3.0
9 | ;; SPDX-License-Identifier: GPL-3.0-or-later
10 |
11 |
12 | ;;; Commentary:
13 | ;; translate-shell backends
14 |
15 | ;;; Code:
16 |
17 | (defvar immersive-translate--process-alist)
18 | (declare-function immersive-translate-callback "ext:immersive-translate")
19 |
20 | (defgroup immersive-translate-trans nil
21 | "Immersive translate translate-shell backend."
22 | :group 'immersive-translate)
23 |
24 | (defcustom immersive-translate-trans-engine "google"
25 | "Translation engine used by trans.
26 |
27 | See https://github.com/soimort/translate-shell for more details."
28 | :group 'immersive-translate-trans
29 | :type 'string)
30 |
31 | (defcustom immersive-translate-trans-source-language "en"
32 | "The source language need to be translated.
33 |
34 | See https://github.com/soimort/translate-shell#code-list for more
35 | details."
36 | :group 'immersive-translate-trans
37 | :type 'string)
38 |
39 | (defcustom immersive-translate-trans-target-language "zh-CN"
40 | "The target language.
41 |
42 | See https://github.com/soimort/translate-shell#code-list for more
43 | details."
44 | :group 'immersive-translate-trans
45 | :type 'string)
46 |
47 | (defcustom immersive-translate-trans-default-args "-show-original n -show-original-phonetics n -show-translation y -no-ansi -show-translation-phonetics n -show-prompt-message n -show-languages n -show-original-dictionary n -show-dictionary n -show-alternatives n"
48 | "Options passed to trans.
49 |
50 | See https://github.com/soimort/translate-shell for more details."
51 | :group 'immersive-translate-trans
52 | :type 'string)
53 |
54 | (defun immersive-translate-trans-make-command (text)
55 | "Generate the whole translate-shell command fot TEXT."
56 | (list (concat
57 | "trans"
58 | " -e " immersive-translate-trans-engine
59 | " -s " immersive-translate-trans-source-language
60 | " -t " immersive-translate-trans-target-language
61 | " "
62 | immersive-translate-trans-default-args
63 | " "
64 | (shell-quote-argument text))))
65 |
66 | (defun immersive-translate-trans--parse-response (buf)
67 | "Parse the buffer BUF with translate-shell's response."
68 | (with-current-buffer buf
69 | (goto-char (point-max))
70 | (let ((raw-content (buffer-substring-no-properties
71 | (line-beginning-position 0)
72 | (line-end-position 0))))
73 | (string-trim (or raw-content
74 | "")))))
75 |
76 |
77 | ;; TODO: define a more generic sentinel
78 | (defun immersive-translate-trans--sentinel (process _status)
79 | "Process sentinel for immersive-translate translate-shell process.
80 |
81 | PROCESS and _STATUS are process parameters."
82 | (let ((proc-buf (process-buffer process)))
83 | (when-let* (((eq (process-status process) 'exit))
84 | (proc-info (alist-get process immersive-translate--process-alist))
85 | (proc-content (plist-get proc-info :content))
86 | (proc-callback (plist-get proc-info :callback)))
87 | (pcase-let ((response
88 | (immersive-translate-trans--parse-response proc-buf)))
89 | (plist-put proc-info :status t)
90 | (when (and (plist-get proc-info :retry)
91 | (string-empty-p response))
92 | (setq response "No response."))
93 | (when (and proc-content
94 | (string-empty-p response)
95 | (not (plist-get proc-info :retry)))
96 | (plist-put proc-info :retry t)
97 | (immersive-translate-trans-translate proc-info proc-callback))
98 | (funcall proc-callback response proc-info)))
99 | (setf (alist-get process immersive-translate--process-alist nil 'remove) nil)
100 | (kill-buffer proc-buf)))
101 |
102 | ;; TODO: define a more generic function
103 | (defun immersive-translate-trans-translate (info &optional callback)
104 | "Translate the content in INFO.
105 |
106 | INFO is a plist with the following keys:
107 | - :content (the text needed to be translated)
108 | - :buffer (the current buffer)
109 | - :position (marker at which to insert the response).
110 |
111 | Call CALLBACK with the response and INFO afterwards. If omitted
112 | the response is inserted into the current buffer after point."
113 | (let* ((token (md5 (format "%s%s%s%s"
114 | (random) (emacs-pid) (user-full-name)
115 | (recent-keys))))
116 | (command (immersive-translate-trans-make-command (plist-get info :content)))
117 | (process (apply #'start-process-shell-command "immersive-translate-trans"
118 | (generate-new-buffer "*immersive-translate-trans*") command)))
119 | (with-current-buffer (process-buffer process)
120 | (set-process-query-on-exit-flag process nil)
121 | (setf (alist-get process immersive-translate--process-alist)
122 | (nconc (list :token token
123 | :callback (or callback
124 | #'immersive-translate-callback))
125 | info))
126 | (set-process-sentinel process #'immersive-translate-trans--sentinel))))
127 |
128 |
129 | (provide 'immersive-translate-trans)
130 | ;;; immersive-translate-trans.el ends here
131 |
132 |
--------------------------------------------------------------------------------
/immersive-translate.el:
--------------------------------------------------------------------------------
1 | ;;; immersive-translate.el --- Translate the current buffer immersively -*- lexical-binding: t; -*-
2 |
3 | ;; Copyright (C) 2023 Eli Qian
4 |
5 | ;; Author: Eli Qian
6 | ;; URL: https://github.com/Elilif/emacs-immersive-translate
7 | ;; Keywords: convenience, help, translate
8 | ;; Version: 0.3.0
9 | ;; Package-Requires: ((emacs "28.2"))
10 |
11 | ;; SPDX-License-Identifier: GPL-3.0-or-later
12 |
13 | ;;; Commentary:
14 | ;; Translate the current buffer immersively
15 |
16 | ;;; Code:
17 |
18 | (require 'dom)
19 | (require 'auth-source)
20 | (require 'text-property-search)
21 | (require 'immersive-translate-baidu)
22 | (require 'immersive-translate-chatgpt)
23 | (require 'immersive-translate-trans)
24 | (require 'immersive-translate-deepl)
25 |
26 |
27 |
28 | ;;;; Customizations
29 | (defgroup immersive-translate nil
30 | "Immersive translation."
31 | :group 'applications)
32 |
33 | (defcustom immersive-translate-auto-idle 0.5
34 | "Perform translation the next time Emacs is idle for seconds."
35 | :group 'immersive-translate
36 | :type 'number)
37 |
38 | (defcustom immersive-translate-backend 'baidu
39 | "The translation backend to use.
40 |
41 | The current options are
42 | - chatgpt
43 | - baidu
44 | - trans
45 | - deepl"
46 | :group 'immersive-translate
47 | :type '(choice
48 | (const :tag "ChatGPT" chatgpt)
49 | (const :tag "Baidu" baidu)
50 | (const :tag "translate-shell" trans)))
51 |
52 | (defcustom immersive-translate-backend-alist
53 | '((baidu . immersive-translate-baidu-translate)
54 | (chatgpt . immersive-translate-chatgpt-translate)
55 | (trans . immersive-translate-trans-translate)
56 | (deepl . immersive-translate-deepl-translate))
57 | "Alist of functions to do the translation job.
58 |
59 | Each element looks like (BACKEND . FUNCTION);
60 |
61 | BACKEND is the translation backend, see
62 | `immersive-translate-backend'; FUNCTION is a function of two
63 | argument."
64 | :group 'immersive-translate
65 | :type '(alist :key-type symbol :value-type function))
66 |
67 | (defcustom immersive-translate-translation-filter-functions
68 | '(immersive-translate--gptel-filter-result)
69 | "Abnormal hook for transforming the response from translation backends.
70 |
71 | This is useful if you want to format the response in some way,
72 | such as filling paragraphs, adding annotations or recording
73 | information in the response like links.
74 |
75 | Each function in this hook receives one argument: the response
76 | string. It should return the transformed string."
77 | :group 'immersive-translate
78 | :type 'hook)
79 |
80 | (defcustom immersive-translate-pending-message "🔄"
81 | "Text displayed before the translation results are returned."
82 | :group 'immersive-translate
83 | :type 'string)
84 |
85 | (defcustom immersive-translate-failed-message "🔀"
86 | "Text displayed when translation fails."
87 | :group 'immersive-translate
88 | :type 'string)
89 |
90 | (defcustom immersive-translate-exclude-shr-tag '(html
91 | base
92 | body
93 | a
94 | audio
95 | title
96 | img
97 | pre
98 | script
99 | style
100 | svg
101 | span
102 | sub
103 | sup
104 | br
105 | code
106 | tt
107 | hr
108 | div
109 | ol
110 | ul
111 | dl
112 | strong
113 | i
114 | u
115 | em
116 | table)
117 | "HTML components that should not be translated."
118 | :group 'immersive-translate
119 | :type '(repeat symbol))
120 |
121 | (defcustom immersive-translate-cache-directory (file-name-concat user-emacs-directory "var/immersive-translate/")
122 | "The directory where cached translations will be stored."
123 | :group 'immersive-translate
124 | :type 'directory)
125 |
126 | (defun immersive-translate--gptel-filter-result (str)
127 | (replace-regexp-in-string "```" "" str))
128 |
129 | (defun immersive-translate--info-code-block-p ()
130 | "Return non-nil if the current paragraph is a code block."
131 | (let ((current-line (thing-at-point 'line t)))
132 | (when (and
133 | (eq major-mode 'Info-mode)
134 | (string-match "^\\( \\{5,\\}\\)" current-line))
135 | (let* ((current-indent (length (match-string 1 current-line)))
136 | (prev-line (save-excursion
137 | (forward-line -2)
138 | (thing-at-point 'line t)))
139 | (prev-indent (if (string-match "^ +" prev-line)
140 | (length (match-string 0 prev-line))
141 | 0))
142 | (prev-is-kb-desc? (string-prefix-p "‘" prev-line))
143 | (small-indent-change? (< (- current-indent prev-indent) 5)))
144 | (or (not (or prev-is-kb-desc? small-indent-change?))
145 | (string-match-p "^ +\(" current-line))))))
146 |
147 | (defun immersive-translate--info-menu-p ()
148 | "Return non-nil if the current line is a menu."
149 | (when (eq major-mode 'Info-mode)
150 | (string-match-p "^\\*" (thing-at-point 'line t))))
151 |
152 | (defun immersive-translate--helpful-not-doc-p ()
153 | "Return non-nil if point is not in the doc section."
154 | (when (eq major-mode 'helpful-mode)
155 | (when-let ((doc-beg (save-excursion
156 | (goto-char (point-min))
157 | (re-search-forward "^Documentation$" nil 'noerror)
158 | (line-beginning-position)))
159 | (doc-end (save-excursion
160 | (goto-char (point-min))
161 | (re-search-forward "^References$" nil 'noerror)
162 | (line-beginning-position))))
163 | (or (< (point) doc-beg)
164 | (>= (point) doc-end)))))
165 |
166 | (defun immersive-translate--help-signature-p ()
167 | "Return non-nil if the current paragraph is a signature."
168 | (when (eq major-mode 'help-mode)
169 | (string-match-p "^ *\(" (thing-at-point 'line t))))
170 |
171 | (defun immersive-translate--translation-exist-p ()
172 | "Return non-nil if the current paragraph has been translated."
173 | (save-excursion
174 | (immersive-translate-end-of-paragraph)
175 | (when-let ((overlays (overlays-in (1- (point)) (1+ (point)))))
176 | (cl-some (lambda (ov)
177 | (overlay-get ov 'after-string))
178 | overlays))))
179 |
180 | (defcustom immersive-translate-disable-predicates '(immersive-translate--translation-exist-p
181 | immersive-translate--info-code-block-p
182 | immersive-translate--info-menu-p
183 | immersive-translate--helpful-not-doc-p
184 | immersive-translate--help-signature-p)
185 | "Predicates, return t when the current paragraph should not be translated.
186 |
187 | Predicate functions don't take any arguments."
188 | :group 'immersive-translate
189 | :type '(repeat function))
190 |
191 | (defvar immersive-translate--process-alist nil
192 | "Alist of active immersive-translate curl requests.")
193 | (defvar-local immersive-translate--translation-overlays nil)
194 | (defvar immersive-translate--timer nil)
195 | (defvar-local immersive-translate--window-start nil)
196 | (defvar-local immersive-translate--window-end nil)
197 |
198 | (defun immersive-translate-api-key (host user)
199 | "Lookup api key in the auth source.
200 |
201 | By default, `immersive-translate-chatgpt-host' is used as HOST
202 | and \"apikey\" as USER in Chatgpt backend.
203 | \"fanyi-api.baidu.com\" is used as HOST and
204 | `immersive-translate-baidu-appid' as USER in Baidu backend."
205 | (if-let ((secret (plist-get (car (auth-source-search
206 | :host host
207 | :user user
208 | :require '(:secret)))
209 | :secret)))
210 | (if (functionp secret)
211 | (encode-coding-string (funcall secret) 'utf-8)
212 | secret)
213 | (user-error "No %s found in the auth source" user)))
214 |
215 |
216 | ;;;; shr
217 | (defun immersive-translate--shr-set-bound (orig dom)
218 | "Set DOM bound.
219 |
220 | Advice for ORIG (shr-tag-*)."
221 | (let ((beg (point)))
222 | (funcall orig dom)
223 | (unless (= beg (point))
224 | (put-text-property beg (1+ beg) 'immersive-translate--beg (dom-tag dom))
225 | (save-excursion
226 | (save-restriction
227 | (widen)
228 | (skip-chars-backward "[ \n\t]")
229 | (put-text-property (1- (point)) (point) 'immersive-translate--end (dom-tag dom)))))))
230 |
231 | (defun immersive-translate--shr-tag-advice (dom)
232 | "Add advice for DOM."
233 | (let* ((tag (dom-tag dom))
234 | (function
235 | (intern (concat "shr-tag-" (symbol-name tag)) obarray)))
236 | (unless (memq tag immersive-translate-exclude-shr-tag)
237 | (advice-add function :around #'immersive-translate--shr-set-bound))))
238 |
239 |
240 | ;;;; paragraph get functions
241 | (defun immersive-translate--info-get-paragraph ()
242 | "Return the paragraph at point."
243 | (forward-paragraph -1)
244 | (forward-line)
245 | (let* ((eop (save-excursion
246 | (end-of-paragraph-text)
247 | (point)))
248 | (bop (save-excursion
249 | (re-search-forward "\\(^ [^ ].*\n \\{5,\\}\\)\\|\\(^ *‘.*’$\\)"
250 | (line-end-position 2)
251 | 'noerror)))
252 | (string (if bop
253 | (buffer-substring-no-properties bop eop)
254 | (buffer-substring-no-properties (point) eop))))
255 | (thread-last
256 | string
257 | (replace-regexp-in-string "\n" " ")
258 | (replace-regexp-in-string " +" " ")
259 | (replace-regexp-in-string "\\*[Nn]ote \\(.*?\n*.*?\\)::" "\"\\1\""))))
260 |
261 | (defun immersive-translate--helpful-get-paragraph ()
262 | "Return the paragraph at point."
263 | (forward-paragraph -1)
264 | (forward-line)
265 | (let ((para (thing-at-point 'paragraph t)))
266 | (string-trim-left para "\nDocumentation\n")))
267 |
268 | (defun immersive-translate--elfeed-get-paragraph ()
269 | "Return the paragraph at point."
270 | (save-excursion
271 | (immersive-translate-end-of-paragraph)
272 | (when-let* ((beg-prop (text-property-search-backward 'immersive-translate--beg))
273 | (beg-pos (prop-match-beginning beg-prop))
274 | (tag (prop-match-value beg-prop))
275 | (end-prop (text-property-search-forward 'immersive-translate--end))
276 | (end-pos (prop-match-beginning end-prop)))
277 | (if (eq tag 'li)
278 | (buffer-substring-no-properties (+ beg-pos 2) end-pos)
279 | (buffer-substring-no-properties beg-pos end-pos)))))
280 |
281 | (defun immersive-translate--elfeed-tube-get-paragraph ()
282 | "Return the paragraph at point."
283 | (forward-paragraph -1)
284 | (forward-line)
285 | (let ((para (thing-at-point 'paragraph t)))
286 | (string-trim-left para "\n\\[.*?\\] \\- \\[.*?\\]:\n")))
287 |
288 | (defun immersive-translate--elfeed-tube-p (&optional mode)
289 | "Return non-nil if the current feed in MODE is a Youtube RSS feed.
290 |
291 | Return nil otherwise."
292 | (when (eq mode 'elfeed-show-mode)
293 | (save-excursion
294 | (goto-char (point-min))
295 | (text-property-search-forward 'timestamp))))
296 |
297 | (defun immersive-translate--get-paragraph ()
298 | "Return the paragraph at point."
299 | (pcase major-mode
300 | ('Info-mode
301 | (immersive-translate--info-get-paragraph))
302 | ('helpful-mode
303 | (immersive-translate--helpful-get-paragraph))
304 | ((pred immersive-translate--elfeed-tube-p)
305 | (immersive-translate--elfeed-tube-get-paragraph))
306 | ((or 'elfeed-show-mode 'nov-mode 'mu4e-view-mode)
307 | (immersive-translate--elfeed-get-paragraph))
308 | (_
309 | (thing-at-point 'paragraph t))))
310 |
311 |
312 | ;;;; format functions
313 | (defun immersive-translate--get-indent (marker)
314 | "Return the indentation of the original text at MARKER."
315 | (with-current-buffer (marker-buffer marker)
316 | (save-excursion
317 | (goto-char marker)
318 | (save-excursion
319 | (re-search-backward "^\\( *\\)" (line-beginning-position))
320 | (match-string 1)))))
321 |
322 | (defun immersive-translate--format-translation (str marker)
323 | "Function which produces the string to insert as a translation.
324 |
325 | STR is the original translation. MARKER is the position where the
326 | translation should be inserted."
327 | (with-temp-buffer
328 | (insert str)
329 | (fill-region-as-paragraph (point-min) (point-max))
330 | (concat
331 | "\n"
332 | (replace-regexp-in-string
333 | "^"
334 | (immersive-translate--get-indent marker)
335 | (let ((string (buffer-substring-no-properties (point-min) (point-max))))
336 | (eval
337 | `(thread-last
338 | ,string
339 | ,@immersive-translate-translation-filter-functions))))
340 | "\n")))
341 |
342 | (defun immersive-translate--info-transform-response (str marker)
343 | "Format STR at MARKER in `Info-mode'."
344 | (let* ((fill-column 70)
345 | (str (string-trim-right str "[-=*]+")))
346 | (immersive-translate--format-translation str marker)))
347 |
348 | (defun immersive-translate--nov-transform-response (str marker)
349 | "Format STR at MARKER in `nov-mode'."
350 | (let ((fill-column (or (and (boundp 'nov-text-width)
351 | nov-text-width)
352 | 120)))
353 | (immersive-translate--format-translation str marker)))
354 |
355 | (defun immersive-translate--elfeed-transform-response (str marker)
356 | "Format STR at MARKER in `elfeed-mode'."
357 | (let ((fill-column (or (and (boundp 'shr-width)
358 | shr-width)
359 | 110)))
360 | (save-excursion
361 | (goto-char marker)
362 | (let* ((beg-prop (text-property-search-backward 'immersive-translate--beg))
363 | (tag (prop-match-value beg-prop)))
364 | (concat (immersive-translate--format-translation str marker)
365 | (if (eq tag 'li)
366 | "\n"
367 | ""))))))
368 |
369 | (defun immersive-translate--help-transform-response (str marker)
370 | "Format STR at MARKER in `help-mode'."
371 | (let ((fill-column 70))
372 | (immersive-translate--format-translation str marker)))
373 |
374 | (defun immersive-translate--transform-response (content-str &optional marker)
375 | "Format CONTENT-STR at MARKER."
376 | (pcase major-mode
377 | ('Info-mode
378 | (immersive-translate--info-transform-response content-str marker))
379 | ('nov-mode
380 | (immersive-translate--nov-transform-response content-str marker))
381 | ((or 'elfeed-show-mode 'mu4e-view-mode)
382 | (immersive-translate--elfeed-transform-response content-str marker))
383 | ((or 'helpful-mode
384 | 'help-mode)
385 | (immersive-translate--help-transform-response content-str marker))
386 | (_
387 | (immersive-translate--format-translation content-str marker))))
388 |
389 |
390 | ;;;; utility functions
391 | (defun immersive-translate--cache-filename (content)
392 | "Generate the full filename based on CONTENT."
393 | (let ((hash (sha1 (concat
394 | (prin1-to-string content)
395 | (symbol-name immersive-translate-backend)))))
396 | (expand-file-name (concat (symbol-name immersive-translate-backend)
397 | "-"
398 | hash)
399 | immersive-translate-cache-directory)))
400 |
401 | (defun immersive-translate--cache-translation (new-content origin-content)
402 | "Save NEW-CONTENT to a file.
403 |
404 | The filename is based on ORIGIN-CONTENT."
405 | (let ((file (immersive-translate--cache-filename origin-content)))
406 | (unless (file-directory-p immersive-translate-cache-directory)
407 | (make-directory immersive-translate-cache-directory t))
408 | (unless (file-exists-p file)
409 | (with-temp-file file
410 | (insert new-content)))))
411 |
412 | (defun immersive-translate--cache-p (content)
413 | "Return t if CONTENT is cached, else nil."
414 | (let* ((file (immersive-translate--cache-filename content)))
415 | (file-exists-p file)))
416 |
417 | (defun immersive-translate--cache-get (content)
418 | "Get the cache for CONTENT."
419 | (let* ((file (immersive-translate--cache-filename content)))
420 | (with-temp-buffer
421 | (insert-file-contents file)
422 | (buffer-string))))
423 |
424 | (defun immersive-translate--add-ov (response)
425 | "Add an after-string overlay after point.
426 |
427 | The value of after-string is RESPONSE."
428 | (let ((ovs (overlays-in (1- (point)) (point)))
429 | (new-ov (make-overlay (point) (1+ (point)))))
430 | (mapc (lambda (ov)
431 | (when (overlay-get ov 'after-string)
432 | (delete-overlay ov)))
433 | ovs)
434 | (overlay-put new-ov
435 | 'after-string
436 | response)
437 | (push new-ov immersive-translate--translation-overlays)))
438 |
439 | (defun immersive-translate-callback (response info)
440 | "Insert RESPONSE from ChatGPT into the current buffer.
441 |
442 | INFO is a plist containing information relevant to this buffer."
443 | (when-let* (((not (string-empty-p response)))
444 | (status-str (plist-get info :status))
445 | (origin-buffer (plist-get info :buffer))
446 | (start-marker (plist-get info :position))
447 | (origin-content (plist-get info :content)))
448 | (with-current-buffer origin-buffer
449 | (if response
450 | (progn
451 | (setq response (immersive-translate--transform-response response start-marker))
452 | (save-excursion
453 | (with-current-buffer (marker-buffer start-marker)
454 | (goto-char start-marker)
455 | (immersive-translate--add-ov response)
456 | (unless (string-match-p immersive-translate-failed-message response)
457 | (immersive-translate--cache-translation response origin-content)))))
458 | (message "Response error: (%s) %s"
459 | status-str (plist-get info :error))))))
460 |
461 | (defun immersive-translate-disable-p ()
462 | "Return non-nil if the current paragraph should not be translated.
463 |
464 | Nil otherwise."
465 | (cl-some (lambda (pred)
466 | (funcall pred))
467 | immersive-translate-disable-predicates))
468 |
469 | (defun immersive-translate-end-of-paragraph ()
470 | "Move to the end of the current paragraph."
471 | (pcase major-mode
472 | ((and (or 'elfeed-show-mode 'nov-mode 'mu4e-view-mode)
473 | (pred (not immersive-translate--elfeed-tube-p)))
474 | (unless (get-text-property (point) 'immersive-translate--beg)
475 | (text-property-search-backward 'immersive-translate--beg))
476 | (text-property-search-forward 'immersive-translate--end)
477 | (end-of-line))
478 | (_ (end-of-paragraph-text))))
479 |
480 | (defun immersive-translate-join-lin (paragraph)
481 | "Form the current PARAGRAPH into a continuous paragraph."
482 | (when paragraph
483 | (let ((new-str (string-clean-whitespace
484 | (replace-regexp-in-string "\n" " " paragraph))))
485 | (unless (string-empty-p new-str)
486 | new-str))))
487 |
488 | (defun immersive-translate-region (start end)
489 | "Translate the text between START and END."
490 | (save-excursion
491 | (goto-char start)
492 | (pcase major-mode
493 | ((and (or 'elfeed-show-mode 'nov-mode 'mu4e-view-mode)
494 | (pred (not immersive-translate--elfeed-tube-p)))
495 | (while (and (text-property-search-forward 'immersive-translate--end)
496 | (< (point) end))
497 | (immersive-translate-paragraph)))
498 | (_ (while (and
499 | (< (point) end)
500 | (re-search-forward "^\\s-*$" end 'noerror)
501 | (not (eobp)))
502 | (forward-line)
503 | (immersive-translate-paragraph))))))
504 |
505 | ;;;###autoload
506 | (defun immersive-translate-abort (buf)
507 | "Stop all active immersive-translate processes in BUF."
508 | (interactive (list (current-buffer)))
509 | (if-let* ((proc-attrs
510 | (cl-remove-if-not
511 | (lambda (proc-list)
512 | (eq (plist-get (cdr proc-list) :buffer) buf))
513 | immersive-translate--process-alist)))
514 | (dolist (proc-attr proc-attrs)
515 | (let ((proc (car proc-attr)))
516 | (setf (alist-get proc immersive-translate--process-alist nil 'remove) nil)
517 | (set-process-sentinel proc #'ignore)
518 | (delete-process proc)
519 | (kill-buffer (process-buffer proc))
520 | (message "Stopped all immersive-translate processes in buffer %S" (buffer-name buf))))
521 | (message "No immersive-translate process associated with buffer %S" (buffer-name buf))))
522 |
523 | (cl-defun immersive-translate-do-translate
524 | (&optional content &key callback
525 | (buffer (current-buffer))
526 | position
527 | (backend immersive-translate-backend))
528 | "Request a response from `immersive-translate-backend' for CONTENT.
529 |
530 | If PROMPT is
531 | - a string, it is used as is
532 | - A list of plists, it is used to create a full prompt suitable for
533 | sending to ChatGPT.
534 |
535 | Keyword arguments:
536 |
537 | CALLBACK, if supplied, is a function of two arguments, called
538 | with the RESPONSE (a string) and INFO (a plist):
539 |
540 | \(callback RESPONSE INFO)
541 |
542 | RESPONSE is nil if there was no response or an error.
543 |
544 | The INFO plist has (at least) the following keys:
545 | :content - The content that was sent with the request
546 | :buffer - The buffer current when the request was sent.
547 | :position - marker at the point the request was sent.
548 | :status - Short string describing the result of the request
549 |
550 | Example of a callback that messages the user with the response
551 | and info:
552 |
553 | \(lambda (response info)
554 | (if response
555 | (let ((posn (marker-position (plist-get info :position)))
556 | (buf (buffer-name (plist-get info :buffer))))
557 | (message \"Response for request from %S at %d: %s\"
558 | buf posn response))
559 | (message \"request failed with message: %s\"
560 | (plist-get info :status))))
561 |
562 | Or, for just the response:
563 |
564 | \(lambda (response _)
565 | ;; Do something with response
566 | (message (rot13-string response)))
567 |
568 | If CALLBACK is omitted, the response is inserted at the point the
569 | request was sent.
570 |
571 | BUFFER is the buffer the request belongs to. If omitted the
572 | current buffer is recorded.
573 |
574 | POSITION is a buffer position (integer or marker). If omitted,
575 | the value of (point) is recorded.
576 |
577 | BACKEND is the translation backend to use. If omitted, the value
578 | of `immersive-translate-backend' is used."
579 | (let* ((start-marker
580 | (cond
581 | ((null position)
582 | (if (use-region-p)
583 | (set-marker (make-marker) (region-end))
584 | (point-marker)))
585 | ((markerp position) position)
586 | ((integerp position)
587 | (set-marker (make-marker) position buffer))))
588 | (info (list :content content
589 | :buffer buffer
590 | :position start-marker)))
591 | (funcall (alist-get backend immersive-translate-backend-alist) info callback)))
592 |
593 | ;;;###autoload
594 | (defun immersive-translate-buffer ()
595 | "Translate the whole buffer."
596 | (interactive)
597 | (pcase major-mode
598 | ((pred immersive-translate--elfeed-tube-p)
599 | (save-excursion
600 | (goto-char (point-min))
601 | (let ((beg (search-forward "Transcript:\n" (point-max) 'noerror)))
602 | (immersive-translate-region beg (point-max)))))
603 | (_
604 | (immersive-translate-region (point-min) (point-max)))))
605 |
606 | ;;;###autoload
607 | (defun immersive-translate-paragraph ()
608 | "Translate the current paragraph."
609 | (interactive)
610 | (save-excursion
611 | (unless (immersive-translate-disable-p)
612 | (when-let* ((paragraph (immersive-translate-join-lin
613 | (immersive-translate--get-paragraph)))
614 | (content (if (eq immersive-translate-backend 'chatgpt)
615 | (immersive-translate-chatgpt-create-prompt paragraph)
616 | paragraph))
617 | (ov t))
618 | (immersive-translate-end-of-paragraph)
619 | (if (immersive-translate--cache-p content)
620 | (let ((translation (immersive-translate--cache-get content)))
621 | (immersive-translate--add-ov translation))
622 | (setq ov (make-overlay (1- (point)) (point)))
623 | (overlay-put ov
624 | 'after-string
625 | immersive-translate-pending-message)
626 | (immersive-translate-do-translate content))))))
627 |
628 | ;;;###autoload
629 | (defun immersive-translate-clear ()
630 | "Clear translations."
631 | (interactive)
632 | (let ((ovs (overlays-in (point-min) (point-max))))
633 | (mapc (lambda (ov)
634 | (when (overlay-get ov 'after-string)
635 | (delete-overlay ov)))
636 | ovs))
637 | (dolist (ov immersive-translate--translation-overlays)
638 | (delete-overlay ov))
639 | (setq immersive-translate--translation-overlays nil))
640 |
641 | (defun immersive-translate--auto-translate-window ()
642 | "Translate the text in the current window."
643 | (let ((start (window-start))
644 | (end (window-end)))
645 | (setq immersive-translate--window-start start
646 | immersive-translate--window-end end)
647 | (immersive-translate-region start end)))
648 |
649 | ;;;###autoload
650 | (define-minor-mode immersive-translate-auto-mode
651 | "Toggle `immersive-translate-auto-mode'.
652 |
653 | Translate paragraph under the cursor after Emacs is idle for
654 | `immersive-translate-auto-idle' seconds."
655 | :global nil
656 | :group 'immersive-translate
657 | (cond
658 | (immersive-translate-auto-mode
659 | (when (and immersive-translate--timer (timerp immersive-translate--timer))
660 | (cancel-timer immersive-translate--timer))
661 | (immersive-translate--auto-translate-window)
662 | (setq immersive-translate--timer
663 | (run-with-idle-timer immersive-translate-auto-idle t #'immersive-translate--auto-translate)))
664 | (t
665 | (cancel-timer immersive-translate--timer)
666 | (setq immersive-translate--timer nil
667 | immersive-translate--window-start nil
668 | immersive-translate--window-end nil))))
669 |
670 | (defun immersive-translate--auto-translate ()
671 | "Helper Function for `immersive-translate-auto-mode'."
672 | (when (and immersive-translate-auto-mode
673 | immersive-translate--window-end
674 | (or (< (window-start) immersive-translate--window-start)
675 | (> (window-end) immersive-translate--window-end)))
676 | (immersive-translate--auto-translate-window)))
677 |
678 | ;;;###autoload
679 | (defun immersive-translate-setup ()
680 | "Setup immersive-trasnlate."
681 | (advice-add 'shr-descend :before #'immersive-translate--shr-tag-advice))
682 |
683 |
684 | ;;;; provide
685 | (provide 'immersive-translate)
686 | ;;; immersive-translate.el ends here
687 |
--------------------------------------------------------------------------------