Codebase list pygtkspellcheck / 7abf48b
Import pygtkspellcheck_3.0.orig.tar.gz Raphaël Hertzog 7 years ago
31 changed file(s) with 3610 addition(s) and 0 deletion(s). Raw diff Collapse all Expand all
0 GNU GENERAL PUBLIC LICENSE
1 Version 3, 29 June 2007
2
3 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
4 Everyone is permitted to copy and distribute verbatim copies
5 of this license document, but changing it is not allowed.
6
7 Preamble
8
9 The GNU General Public License is a free, copyleft license for
10 software and other kinds of works.
11
12 The licenses for most software and other practical works are designed
13 to take away your freedom to share and change the works. By contrast,
14 the GNU General Public License is intended to guarantee your freedom to
15 share and change all versions of a program--to make sure it remains free
16 software for all its users. We, the Free Software Foundation, use the
17 GNU General Public License for most of our software; it applies also to
18 any other work released this way by its authors. You can apply it to
19 your programs, too.
20
21 When we speak of free software, we are referring to freedom, not
22 price. Our General Public Licenses are designed to make sure that you
23 have the freedom to distribute copies of free software (and charge for
24 them if you wish), that you receive source code or can get it if you
25 want it, that you can change the software or use pieces of it in new
26 free programs, and that you know you can do these things.
27
28 To protect your rights, we need to prevent others from denying you
29 these rights or asking you to surrender the rights. Therefore, you have
30 certain responsibilities if you distribute copies of the software, or if
31 you modify it: responsibilities to respect the freedom of others.
32
33 For example, if you distribute copies of such a program, whether
34 gratis or for a fee, you must pass on to the recipients the same
35 freedoms that you received. You must make sure that they, too, receive
36 or can get the source code. And you must show them these terms so they
37 know their rights.
38
39 Developers that use the GNU GPL protect your rights with two steps:
40 (1) assert copyright on the software, and (2) offer you this License
41 giving you legal permission to copy, distribute and/or modify it.
42
43 For the developers' and authors' protection, the GPL clearly explains
44 that there is no warranty for this free software. For both users' and
45 authors' sake, the GPL requires that modified versions be marked as
46 changed, so that their problems will not be attributed erroneously to
47 authors of previous versions.
48
49 Some devices are designed to deny users access to install or run
50 modified versions of the software inside them, although the manufacturer
51 can do so. This is fundamentally incompatible with the aim of
52 protecting users' freedom to change the software. The systematic
53 pattern of such abuse occurs in the area of products for individuals to
54 use, which is precisely where it is most unacceptable. Therefore, we
55 have designed this version of the GPL to prohibit the practice for those
56 products. If such problems arise substantially in other domains, we
57 stand ready to extend this provision to those domains in future versions
58 of the GPL, as needed to protect the freedom of users.
59
60 Finally, every program is threatened constantly by software patents.
61 States should not allow patents to restrict development and use of
62 software on general-purpose computers, but in those that do, we wish to
63 avoid the special danger that patents applied to a free program could
64 make it effectively proprietary. To prevent this, the GPL assures that
65 patents cannot be used to render the program non-free.
66
67 The precise terms and conditions for copying, distribution and
68 modification follow.
69
70 TERMS AND CONDITIONS
71
72 0. Definitions.
73
74 "This License" refers to version 3 of the GNU General Public License.
75
76 "Copyright" also means copyright-like laws that apply to other kinds of
77 works, such as semiconductor masks.
78
79 "The Program" refers to any copyrightable work licensed under this
80 License. Each licensee is addressed as "you". "Licensees" and
81 "recipients" may be individuals or organizations.
82
83 To "modify" a work means to copy from or adapt all or part of the work
84 in a fashion requiring copyright permission, other than the making of an
85 exact copy. The resulting work is called a "modified version" of the
86 earlier work or a work "based on" the earlier work.
87
88 A "covered work" means either the unmodified Program or a work based
89 on the Program.
90
91 To "propagate" a work means to do anything with it that, without
92 permission, would make you directly or secondarily liable for
93 infringement under applicable copyright law, except executing it on a
94 computer or modifying a private copy. Propagation includes copying,
95 distribution (with or without modification), making available to the
96 public, and in some countries other activities as well.
97
98 To "convey" a work means any kind of propagation that enables other
99 parties to make or receive copies. Mere interaction with a user through
100 a computer network, with no transfer of a copy, is not conveying.
101
102 An interactive user interface displays "Appropriate Legal Notices"
103 to the extent that it includes a convenient and prominently visible
104 feature that (1) displays an appropriate copyright notice, and (2)
105 tells the user that there is no warranty for the work (except to the
106 extent that warranties are provided), that licensees may convey the
107 work under this License, and how to view a copy of this License. If
108 the interface presents a list of user commands or options, such as a
109 menu, a prominent item in the list meets this criterion.
110
111 1. Source Code.
112
113 The "source code" for a work means the preferred form of the work
114 for making modifications to it. "Object code" means any non-source
115 form of a work.
116
117 A "Standard Interface" means an interface that either is an official
118 standard defined by a recognized standards body, or, in the case of
119 interfaces specified for a particular programming language, one that
120 is widely used among developers working in that language.
121
122 The "System Libraries" of an executable work include anything, other
123 than the work as a whole, that (a) is included in the normal form of
124 packaging a Major Component, but which is not part of that Major
125 Component, and (b) serves only to enable use of the work with that
126 Major Component, or to implement a Standard Interface for which an
127 implementation is available to the public in source code form. A
128 "Major Component", in this context, means a major essential component
129 (kernel, window system, and so on) of the specific operating system
130 (if any) on which the executable work runs, or a compiler used to
131 produce the work, or an object code interpreter used to run it.
132
133 The "Corresponding Source" for a work in object code form means all
134 the source code needed to generate, install, and (for an executable
135 work) run the object code and to modify the work, including scripts to
136 control those activities. However, it does not include the work's
137 System Libraries, or general-purpose tools or generally available free
138 programs which are used unmodified in performing those activities but
139 which are not part of the work. For example, Corresponding Source
140 includes interface definition files associated with source files for
141 the work, and the source code for shared libraries and dynamically
142 linked subprograms that the work is specifically designed to require,
143 such as by intimate data communication or control flow between those
144 subprograms and other parts of the work.
145
146 The Corresponding Source need not include anything that users
147 can regenerate automatically from other parts of the Corresponding
148 Source.
149
150 The Corresponding Source for a work in source code form is that
151 same work.
152
153 2. Basic Permissions.
154
155 All rights granted under this License are granted for the term of
156 copyright on the Program, and are irrevocable provided the stated
157 conditions are met. This License explicitly affirms your unlimited
158 permission to run the unmodified Program. The output from running a
159 covered work is covered by this License only if the output, given its
160 content, constitutes a covered work. This License acknowledges your
161 rights of fair use or other equivalent, as provided by copyright law.
162
163 You may make, run and propagate covered works that you do not
164 convey, without conditions so long as your license otherwise remains
165 in force. You may convey covered works to others for the sole purpose
166 of having them make modifications exclusively for you, or provide you
167 with facilities for running those works, provided that you comply with
168 the terms of this License in conveying all material for which you do
169 not control copyright. Those thus making or running the covered works
170 for you must do so exclusively on your behalf, under your direction
171 and control, on terms that prohibit them from making any copies of
172 your copyrighted material outside their relationship with you.
173
174 Conveying under any other circumstances is permitted solely under
175 the conditions stated below. Sublicensing is not allowed; section 10
176 makes it unnecessary.
177
178 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
179
180 No covered work shall be deemed part of an effective technological
181 measure under any applicable law fulfilling obligations under article
182 11 of the WIPO copyright treaty adopted on 20 December 1996, or
183 similar laws prohibiting or restricting circumvention of such
184 measures.
185
186 When you convey a covered work, you waive any legal power to forbid
187 circumvention of technological measures to the extent such circumvention
188 is effected by exercising rights under this License with respect to
189 the covered work, and you disclaim any intention to limit operation or
190 modification of the work as a means of enforcing, against the work's
191 users, your or third parties' legal rights to forbid circumvention of
192 technological measures.
193
194 4. Conveying Verbatim Copies.
195
196 You may convey verbatim copies of the Program's source code as you
197 receive it, in any medium, provided that you conspicuously and
198 appropriately publish on each copy an appropriate copyright notice;
199 keep intact all notices stating that this License and any
200 non-permissive terms added in accord with section 7 apply to the code;
201 keep intact all notices of the absence of any warranty; and give all
202 recipients a copy of this License along with the Program.
203
204 You may charge any price or no price for each copy that you convey,
205 and you may offer support or warranty protection for a fee.
206
207 5. Conveying Modified Source Versions.
208
209 You may convey a work based on the Program, or the modifications to
210 produce it from the Program, in the form of source code under the
211 terms of section 4, provided that you also meet all of these conditions:
212
213 a) The work must carry prominent notices stating that you modified
214 it, and giving a relevant date.
215
216 b) The work must carry prominent notices stating that it is
217 released under this License and any conditions added under section
218 7. This requirement modifies the requirement in section 4 to
219 "keep intact all notices".
220
221 c) You must license the entire work, as a whole, under this
222 License to anyone who comes into possession of a copy. This
223 License will therefore apply, along with any applicable section 7
224 additional terms, to the whole of the work, and all its parts,
225 regardless of how they are packaged. This License gives no
226 permission to license the work in any other way, but it does not
227 invalidate such permission if you have separately received it.
228
229 d) If the work has interactive user interfaces, each must display
230 Appropriate Legal Notices; however, if the Program has interactive
231 interfaces that do not display Appropriate Legal Notices, your
232 work need not make them do so.
233
234 A compilation of a covered work with other separate and independent
235 works, which are not by their nature extensions of the covered work,
236 and which are not combined with it such as to form a larger program,
237 in or on a volume of a storage or distribution medium, is called an
238 "aggregate" if the compilation and its resulting copyright are not
239 used to limit the access or legal rights of the compilation's users
240 beyond what the individual works permit. Inclusion of a covered work
241 in an aggregate does not cause this License to apply to the other
242 parts of the aggregate.
243
244 6. Conveying Non-Source Forms.
245
246 You may convey a covered work in object code form under the terms
247 of sections 4 and 5, provided that you also convey the
248 machine-readable Corresponding Source under the terms of this License,
249 in one of these ways:
250
251 a) Convey the object code in, or embodied in, a physical product
252 (including a physical distribution medium), accompanied by the
253 Corresponding Source fixed on a durable physical medium
254 customarily used for software interchange.
255
256 b) Convey the object code in, or embodied in, a physical product
257 (including a physical distribution medium), accompanied by a
258 written offer, valid for at least three years and valid for as
259 long as you offer spare parts or customer support for that product
260 model, to give anyone who possesses the object code either (1) a
261 copy of the Corresponding Source for all the software in the
262 product that is covered by this License, on a durable physical
263 medium customarily used for software interchange, for a price no
264 more than your reasonable cost of physically performing this
265 conveying of source, or (2) access to copy the
266 Corresponding Source from a network server at no charge.
267
268 c) Convey individual copies of the object code with a copy of the
269 written offer to provide the Corresponding Source. This
270 alternative is allowed only occasionally and noncommercially, and
271 only if you received the object code with such an offer, in accord
272 with subsection 6b.
273
274 d) Convey the object code by offering access from a designated
275 place (gratis or for a charge), and offer equivalent access to the
276 Corresponding Source in the same way through the same place at no
277 further charge. You need not require recipients to copy the
278 Corresponding Source along with the object code. If the place to
279 copy the object code is a network server, the Corresponding Source
280 may be on a different server (operated by you or a third party)
281 that supports equivalent copying facilities, provided you maintain
282 clear directions next to the object code saying where to find the
283 Corresponding Source. Regardless of what server hosts the
284 Corresponding Source, you remain obligated to ensure that it is
285 available for as long as needed to satisfy these requirements.
286
287 e) Convey the object code using peer-to-peer transmission, provided
288 you inform other peers where the object code and Corresponding
289 Source of the work are being offered to the general public at no
290 charge under subsection 6d.
291
292 A separable portion of the object code, whose source code is excluded
293 from the Corresponding Source as a System Library, need not be
294 included in conveying the object code work.
295
296 A "User Product" is either (1) a "consumer product", which means any
297 tangible personal property which is normally used for personal, family,
298 or household purposes, or (2) anything designed or sold for incorporation
299 into a dwelling. In determining whether a product is a consumer product,
300 doubtful cases shall be resolved in favor of coverage. For a particular
301 product received by a particular user, "normally used" refers to a
302 typical or common use of that class of product, regardless of the status
303 of the particular user or of the way in which the particular user
304 actually uses, or expects or is expected to use, the product. A product
305 is a consumer product regardless of whether the product has substantial
306 commercial, industrial or non-consumer uses, unless such uses represent
307 the only significant mode of use of the product.
308
309 "Installation Information" for a User Product means any methods,
310 procedures, authorization keys, or other information required to install
311 and execute modified versions of a covered work in that User Product from
312 a modified version of its Corresponding Source. The information must
313 suffice to ensure that the continued functioning of the modified object
314 code is in no case prevented or interfered with solely because
315 modification has been made.
316
317 If you convey an object code work under this section in, or with, or
318 specifically for use in, a User Product, and the conveying occurs as
319 part of a transaction in which the right of possession and use of the
320 User Product is transferred to the recipient in perpetuity or for a
321 fixed term (regardless of how the transaction is characterized), the
322 Corresponding Source conveyed under this section must be accompanied
323 by the Installation Information. But this requirement does not apply
324 if neither you nor any third party retains the ability to install
325 modified object code on the User Product (for example, the work has
326 been installed in ROM).
327
328 The requirement to provide Installation Information does not include a
329 requirement to continue to provide support service, warranty, or updates
330 for a work that has been modified or installed by the recipient, or for
331 the User Product in which it has been modified or installed. Access to a
332 network may be denied when the modification itself materially and
333 adversely affects the operation of the network or violates the rules and
334 protocols for communication across the network.
335
336 Corresponding Source conveyed, and Installation Information provided,
337 in accord with this section must be in a format that is publicly
338 documented (and with an implementation available to the public in
339 source code form), and must require no special password or key for
340 unpacking, reading or copying.
341
342 7. Additional Terms.
343
344 "Additional permissions" are terms that supplement the terms of this
345 License by making exceptions from one or more of its conditions.
346 Additional permissions that are applicable to the entire Program shall
347 be treated as though they were included in this License, to the extent
348 that they are valid under applicable law. If additional permissions
349 apply only to part of the Program, that part may be used separately
350 under those permissions, but the entire Program remains governed by
351 this License without regard to the additional permissions.
352
353 When you convey a copy of a covered work, you may at your option
354 remove any additional permissions from that copy, or from any part of
355 it. (Additional permissions may be written to require their own
356 removal in certain cases when you modify the work.) You may place
357 additional permissions on material, added by you to a covered work,
358 for which you have or can give appropriate copyright permission.
359
360 Notwithstanding any other provision of this License, for material you
361 add to a covered work, you may (if authorized by the copyright holders of
362 that material) supplement the terms of this License with terms:
363
364 a) Disclaiming warranty or limiting liability differently from the
365 terms of sections 15 and 16 of this License; or
366
367 b) Requiring preservation of specified reasonable legal notices or
368 author attributions in that material or in the Appropriate Legal
369 Notices displayed by works containing it; or
370
371 c) Prohibiting misrepresentation of the origin of that material, or
372 requiring that modified versions of such material be marked in
373 reasonable ways as different from the original version; or
374
375 d) Limiting the use for publicity purposes of names of licensors or
376 authors of the material; or
377
378 e) Declining to grant rights under trademark law for use of some
379 trade names, trademarks, or service marks; or
380
381 f) Requiring indemnification of licensors and authors of that
382 material by anyone who conveys the material (or modified versions of
383 it) with contractual assumptions of liability to the recipient, for
384 any liability that these contractual assumptions directly impose on
385 those licensors and authors.
386
387 All other non-permissive additional terms are considered "further
388 restrictions" within the meaning of section 10. If the Program as you
389 received it, or any part of it, contains a notice stating that it is
390 governed by this License along with a term that is a further
391 restriction, you may remove that term. If a license document contains
392 a further restriction but permits relicensing or conveying under this
393 License, you may add to a covered work material governed by the terms
394 of that license document, provided that the further restriction does
395 not survive such relicensing or conveying.
396
397 If you add terms to a covered work in accord with this section, you
398 must place, in the relevant source files, a statement of the
399 additional terms that apply to those files, or a notice indicating
400 where to find the applicable terms.
401
402 Additional terms, permissive or non-permissive, may be stated in the
403 form of a separately written license, or stated as exceptions;
404 the above requirements apply either way.
405
406 8. Termination.
407
408 You may not propagate or modify a covered work except as expressly
409 provided under this License. Any attempt otherwise to propagate or
410 modify it is void, and will automatically terminate your rights under
411 this License (including any patent licenses granted under the third
412 paragraph of section 11).
413
414 However, if you cease all violation of this License, then your
415 license from a particular copyright holder is reinstated (a)
416 provisionally, unless and until the copyright holder explicitly and
417 finally terminates your license, and (b) permanently, if the copyright
418 holder fails to notify you of the violation by some reasonable means
419 prior to 60 days after the cessation.
420
421 Moreover, your license from a particular copyright holder is
422 reinstated permanently if the copyright holder notifies you of the
423 violation by some reasonable means, this is the first time you have
424 received notice of violation of this License (for any work) from that
425 copyright holder, and you cure the violation prior to 30 days after
426 your receipt of the notice.
427
428 Termination of your rights under this section does not terminate the
429 licenses of parties who have received copies or rights from you under
430 this License. If your rights have been terminated and not permanently
431 reinstated, you do not qualify to receive new licenses for the same
432 material under section 10.
433
434 9. Acceptance Not Required for Having Copies.
435
436 You are not required to accept this License in order to receive or
437 run a copy of the Program. Ancillary propagation of a covered work
438 occurring solely as a consequence of using peer-to-peer transmission
439 to receive a copy likewise does not require acceptance. However,
440 nothing other than this License grants you permission to propagate or
441 modify any covered work. These actions infringe copyright if you do
442 not accept this License. Therefore, by modifying or propagating a
443 covered work, you indicate your acceptance of this License to do so.
444
445 10. Automatic Licensing of Downstream Recipients.
446
447 Each time you convey a covered work, the recipient automatically
448 receives a license from the original licensors, to run, modify and
449 propagate that work, subject to this License. You are not responsible
450 for enforcing compliance by third parties with this License.
451
452 An "entity transaction" is a transaction transferring control of an
453 organization, or substantially all assets of one, or subdividing an
454 organization, or merging organizations. If propagation of a covered
455 work results from an entity transaction, each party to that
456 transaction who receives a copy of the work also receives whatever
457 licenses to the work the party's predecessor in interest had or could
458 give under the previous paragraph, plus a right to possession of the
459 Corresponding Source of the work from the predecessor in interest, if
460 the predecessor has it or can get it with reasonable efforts.
461
462 You may not impose any further restrictions on the exercise of the
463 rights granted or affirmed under this License. For example, you may
464 not impose a license fee, royalty, or other charge for exercise of
465 rights granted under this License, and you may not initiate litigation
466 (including a cross-claim or counterclaim in a lawsuit) alleging that
467 any patent claim is infringed by making, using, selling, offering for
468 sale, or importing the Program or any portion of it.
469
470 11. Patents.
471
472 A "contributor" is a copyright holder who authorizes use under this
473 License of the Program or a work on which the Program is based. The
474 work thus licensed is called the contributor's "contributor version".
475
476 A contributor's "essential patent claims" are all patent claims
477 owned or controlled by the contributor, whether already acquired or
478 hereafter acquired, that would be infringed by some manner, permitted
479 by this License, of making, using, or selling its contributor version,
480 but do not include claims that would be infringed only as a
481 consequence of further modification of the contributor version. For
482 purposes of this definition, "control" includes the right to grant
483 patent sublicenses in a manner consistent with the requirements of
484 this License.
485
486 Each contributor grants you a non-exclusive, worldwide, royalty-free
487 patent license under the contributor's essential patent claims, to
488 make, use, sell, offer for sale, import and otherwise run, modify and
489 propagate the contents of its contributor version.
490
491 In the following three paragraphs, a "patent license" is any express
492 agreement or commitment, however denominated, not to enforce a patent
493 (such as an express permission to practice a patent or covenant not to
494 sue for patent infringement). To "grant" such a patent license to a
495 party means to make such an agreement or commitment not to enforce a
496 patent against the party.
497
498 If you convey a covered work, knowingly relying on a patent license,
499 and the Corresponding Source of the work is not available for anyone
500 to copy, free of charge and under the terms of this License, through a
501 publicly available network server or other readily accessible means,
502 then you must either (1) cause the Corresponding Source to be so
503 available, or (2) arrange to deprive yourself of the benefit of the
504 patent license for this particular work, or (3) arrange, in a manner
505 consistent with the requirements of this License, to extend the patent
506 license to downstream recipients. "Knowingly relying" means you have
507 actual knowledge that, but for the patent license, your conveying the
508 covered work in a country, or your recipient's use of the covered work
509 in a country, would infringe one or more identifiable patents in that
510 country that you have reason to believe are valid.
511
512 If, pursuant to or in connection with a single transaction or
513 arrangement, you convey, or propagate by procuring conveyance of, a
514 covered work, and grant a patent license to some of the parties
515 receiving the covered work authorizing them to use, propagate, modify
516 or convey a specific copy of the covered work, then the patent license
517 you grant is automatically extended to all recipients of the covered
518 work and works based on it.
519
520 A patent license is "discriminatory" if it does not include within
521 the scope of its coverage, prohibits the exercise of, or is
522 conditioned on the non-exercise of one or more of the rights that are
523 specifically granted under this License. You may not convey a covered
524 work if you are a party to an arrangement with a third party that is
525 in the business of distributing software, under which you make payment
526 to the third party based on the extent of your activity of conveying
527 the work, and under which the third party grants, to any of the
528 parties who would receive the covered work from you, a discriminatory
529 patent license (a) in connection with copies of the covered work
530 conveyed by you (or copies made from those copies), or (b) primarily
531 for and in connection with specific products or compilations that
532 contain the covered work, unless you entered into that arrangement,
533 or that patent license was granted, prior to 28 March 2007.
534
535 Nothing in this License shall be construed as excluding or limiting
536 any implied license or other defenses to infringement that may
537 otherwise be available to you under applicable patent law.
538
539 12. No Surrender of Others' Freedom.
540
541 If conditions are imposed on you (whether by court order, agreement or
542 otherwise) that contradict the conditions of this License, they do not
543 excuse you from the conditions of this License. If you cannot convey a
544 covered work so as to satisfy simultaneously your obligations under this
545 License and any other pertinent obligations, then as a consequence you may
546 not convey it at all. For example, if you agree to terms that obligate you
547 to collect a royalty for further conveying from those to whom you convey
548 the Program, the only way you could satisfy both those terms and this
549 License would be to refrain entirely from conveying the Program.
550
551 13. Use with the GNU Affero General Public License.
552
553 Notwithstanding any other provision of this License, you have
554 permission to link or combine any covered work with a work licensed
555 under version 3 of the GNU Affero General Public License into a single
556 combined work, and to convey the resulting work. The terms of this
557 License will continue to apply to the part which is the covered work,
558 but the special requirements of the GNU Affero General Public License,
559 section 13, concerning interaction through a network will apply to the
560 combination as such.
561
562 14. Revised Versions of this License.
563
564 The Free Software Foundation may publish revised and/or new versions of
565 the GNU General Public License from time to time. Such new versions will
566 be similar in spirit to the present version, but may differ in detail to
567 address new problems or concerns.
568
569 Each version is given a distinguishing version number. If the
570 Program specifies that a certain numbered version of the GNU General
571 Public License "or any later version" applies to it, you have the
572 option of following the terms and conditions either of that numbered
573 version or of any later version published by the Free Software
574 Foundation. If the Program does not specify a version number of the
575 GNU General Public License, you may choose any version ever published
576 by the Free Software Foundation.
577
578 If the Program specifies that a proxy can decide which future
579 versions of the GNU General Public License can be used, that proxy's
580 public statement of acceptance of a version permanently authorizes you
581 to choose that version for the Program.
582
583 Later license versions may give you additional or different
584 permissions. However, no additional obligations are imposed on any
585 author or copyright holder as a result of your choosing to follow a
586 later version.
587
588 15. Disclaimer of Warranty.
589
590 THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
591 APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
592 HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
593 OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
594 THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
595 PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
596 IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
597 ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
598
599 16. Limitation of Liability.
600
601 IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
602 WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
603 THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
604 GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
605 USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
606 DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
607 PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
608 EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
609 SUCH DAMAGES.
610
611 17. Interpretation of Sections 15 and 16.
612
613 If the disclaimer of warranty and limitation of liability provided
614 above cannot be given local legal effect according to their terms,
615 reviewing courts shall apply local law that most closely approximates
616 an absolute waiver of all civil liability in connection with the
617 Program, unless a warranty or assumption of liability accompanies a
618 copy of the Program in return for a fee.
619
620 END OF TERMS AND CONDITIONS
621
622 How to Apply These Terms to Your New Programs
623
624 If you develop a new program, and you want it to be of the greatest
625 possible use to the public, the best way to achieve this is to make it
626 free software which everyone can redistribute and change under these terms.
627
628 To do so, attach the following notices to the program. It is safest
629 to attach them to the start of each source file to most effectively
630 state the exclusion of warranty; and each file should have at least
631 the "copyright" line and a pointer to where the full notice is found.
632
633 <one line to give the program's name and a brief idea of what it does.>
634 Copyright (C) <year> <name of author>
635
636 This program is free software: you can redistribute it and/or modify
637 it under the terms of the GNU General Public License as published by
638 the Free Software Foundation, either version 3 of the License, or
639 (at your option) any later version.
640
641 This program is distributed in the hope that it will be useful,
642 but WITHOUT ANY WARRANTY; without even the implied warranty of
643 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
644 GNU General Public License for more details.
645
646 You should have received a copy of the GNU General Public License
647 along with this program. If not, see <http://www.gnu.org/licenses/>.
648
649 Also add information on how to contact you by electronic and paper mail.
650
651 If the program does terminal interaction, make it output a short
652 notice like this when it starts in an interactive mode:
653
654 <program> Copyright (C) <year> <name of author>
655 This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
656 This is free software, and you are welcome to redistribute it
657 under certain conditions; type `show c' for details.
658
659 The hypothetical commands `show w' and `show c' should show the appropriate
660 parts of the General Public License. Of course, your program's commands
661 might be different; for a GUI interface, you would use an "about box".
662
663 You should also get your employer (if you work as a programmer) or school,
664 if any, to sign a "copyright disclaimer" for the program, if necessary.
665 For more information on this, and how to apply and follow the GNU GPL, see
666 <http://www.gnu.org/licenses/>.
667
668 The GNU General Public License does not permit incorporating your program
669 into proprietary programs. If your program is a subroutine library, you
670 may consider it more useful to permit linking proprietary applications with
671 the library. If this is what you want to do, use the GNU Lesser General
672 Public License instead of this License. But first, please read
673 <http://www.gnu.org/philosophy/why-not-lgpl.html>.
0 include LICENSE.txt
1 include MANIFEST.in
2 include README.md
3 graft examples
4 graft doc
5 graft l10n
6 prune l10n/mo
7 prune l10n/isos
8 recursive-exclude l10n *.pyc
9
0 Metadata-Version: 1.1
1 Name: pygtkspellcheck
2 Version: 3.0
3 Summary: A simple but quite powerful Python spell checking library for GtkTextViews based on Enchant.
4 Home-page: http://koehlma.github.com/projects/pygtkspellcheck.html
5 Author: Maximilian Köhl & Carlos Jenkins
6 Author-email: linuxmaxi@googlemail.com & carlos@jenkins.co.cr
7 License: GPLv3+
8 Download-URL: https://github.com/koehlma/pygtkspellcheck/tarball/master
9 Description: It supports both Gtk's Python bindings, PyGObject andPyGtk, and for both Python 2 and 3 with automatic switchingand binding autodetection. For automatic translation of theuser interface it can use GEdit's translation files.
10 Platform: UNKNOWN
11 Classifier: Development Status :: 5 - Production/Stable
12 Classifier: Environment :: X11 Applications :: Gnome
13 Classifier: Intended Audience :: Developers
14 Classifier: License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)
15 Classifier: Operating System :: MacOS :: MacOS X
16 Classifier: Operating System :: Microsoft :: Windows
17 Classifier: Operating System :: POSIX
18 Classifier: Programming Language :: Python :: 2
19 Classifier: Programming Language :: Python :: 3
20 Classifier: Topic :: Software Development :: Localization
0 # About
1 PyGtkSpellCheck is a spellchecking library written in pure Python for Gtk based
2 on [Enchant](http://www.abisource.com/projects/enchant/).
3 It supports both Gtk's Python bindings,
4 [PyGObject](https://live.gnome.org/PyGObject/) and
5 [PyGtk](http://www.pygtk.org/), and for both Python
6 2 and 3 with automatic switching and binding autodetection. For automatic
7 translation of the user interface it can use GEdit's translation files.
8
9 # Features
10 * Localized names of the available languages.
11 * Supports word, line and multiline ignore regexes.
12 * Support for ignore custom tags on Gtk's TextBuffer.
13 * Enable and disable of spellchecking with preferences memory.
14 * Support for hotswap of Gtk's TextBuffers.
15 * PyGObject and PyGtk compatible with automatic detection.
16 * Python 2 and 3 support.
17 * As Enchant, support for Hunspell (LibreOffice) and Aspell (GNU) dictionaries.
18
19 # Documentation
20 You can find the documentation at http://pygtkspellcheck.readthedocs.org/ .
21
22 # Homepage
23 You can find the project page at http://koehlma.github.com/projects/pygtkspellcheck.html .
24
25 # License
26 This program is free software: you can redistribute it and/or modify
27 it under the terms of the GNU General Public License as published by
28 the Free Software Foundation, either version 3 of the License, or
29 (at your option) any later version.
30
31 This program is distributed in the hope that it will be useful,
32 but WITHOUT ANY WARRANTY; without even the implied warranty of
33 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
34 GNU General Public License for more details.
35
36 You should have received a copy of the GNU General Public License
37 along with this program. If not, see <http://www.gnu.org/licenses/>.
0 # Makefile for Sphinx documentation
1 #
2
3 # You can set these variables from the command line.
4 SPHINXOPTS =
5 SPHINXBUILD = sphinx-build
6 PAPER =
7 BUILDDIR = build
8
9 # Internal variables.
10 PAPEROPT_a4 = -D latex_paper_size=a4
11 PAPEROPT_letter = -D latex_paper_size=letter
12 ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
13 # the i18n builder cannot share the environment and doctrees with the others
14 I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
15
16 .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
17
18 help:
19 @echo "Please use \`make <target>' where <target> is one of"
20 @echo " html to make standalone HTML files"
21 @echo " dirhtml to make HTML files named index.html in directories"
22 @echo " singlehtml to make a single large HTML file"
23 @echo " pickle to make pickle files"
24 @echo " json to make JSON files"
25 @echo " htmlhelp to make HTML files and a HTML help project"
26 @echo " qthelp to make HTML files and a qthelp project"
27 @echo " devhelp to make HTML files and a Devhelp project"
28 @echo " epub to make an epub"
29 @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
30 @echo " latexpdf to make LaTeX files and run them through pdflatex"
31 @echo " text to make text files"
32 @echo " man to make manual pages"
33 @echo " texinfo to make Texinfo files"
34 @echo " info to make Texinfo files and run them through makeinfo"
35 @echo " gettext to make PO message catalogs"
36 @echo " changes to make an overview of all changed/added/deprecated items"
37 @echo " linkcheck to check all external links for integrity"
38 @echo " doctest to run all doctests embedded in the documentation (if enabled)"
39
40 clean:
41 -rm -rf $(BUILDDIR)/*
42
43 html:
44 $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
45 @echo
46 @echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
47
48 dirhtml:
49 $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
50 @echo
51 @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
52
53 singlehtml:
54 $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
55 @echo
56 @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
57
58 pickle:
59 $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
60 @echo
61 @echo "Build finished; now you can process the pickle files."
62
63 json:
64 $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
65 @echo
66 @echo "Build finished; now you can process the JSON files."
67
68 htmlhelp:
69 $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
70 @echo
71 @echo "Build finished; now you can run HTML Help Workshop with the" \
72 ".hhp project file in $(BUILDDIR)/htmlhelp."
73
74 qthelp:
75 $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
76 @echo
77 @echo "Build finished; now you can run "qcollectiongenerator" with the" \
78 ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
79 @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/PythonGTKSpellchecker.qhcp"
80 @echo "To view the help file:"
81 @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/PythonGTKSpellchecker.qhc"
82
83 devhelp:
84 $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
85 @echo
86 @echo "Build finished."
87 @echo "To view the help file:"
88 @echo "# mkdir -p $$HOME/.local/share/devhelp/PythonGTKSpellchecker"
89 @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/PythonGTKSpellchecker"
90 @echo "# devhelp"
91
92 epub:
93 $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
94 @echo
95 @echo "Build finished. The epub file is in $(BUILDDIR)/epub."
96
97 latex:
98 $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
99 @echo
100 @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
101 @echo "Run \`make' in that directory to run these through (pdf)latex" \
102 "(use \`make latexpdf' here to do that automatically)."
103
104 latexpdf:
105 $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
106 @echo "Running LaTeX files through pdflatex..."
107 $(MAKE) -C $(BUILDDIR)/latex all-pdf
108 @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
109
110 text:
111 $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
112 @echo
113 @echo "Build finished. The text files are in $(BUILDDIR)/text."
114
115 man:
116 $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
117 @echo
118 @echo "Build finished. The manual pages are in $(BUILDDIR)/man."
119
120 texinfo:
121 $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
122 @echo
123 @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
124 @echo "Run \`make' in that directory to run these through makeinfo" \
125 "(use \`make info' here to do that automatically)."
126
127 info:
128 $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
129 @echo "Running Texinfo files through makeinfo..."
130 make -C $(BUILDDIR)/texinfo info
131 @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
132
133 gettext:
134 $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
135 @echo
136 @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
137
138 changes:
139 $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
140 @echo
141 @echo "The overview file is in $(BUILDDIR)/changes."
142
143 linkcheck:
144 $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
145 @echo
146 @echo "Link check complete; look for any errors in the above output " \
147 "or in $(BUILDDIR)/linkcheck/output.txt."
148
149 doctest:
150 $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
151 @echo "Testing of doctests in the sources finished, look at the " \
152 "results in $(BUILDDIR)/doctest/output.txt."
0 #!/usr/bin/env python
1 # -*- coding:utf-8 -*-
2 #
3 # Copyright (C) 2012, Maximilian Köhl <linuxmaxi@googlemail.com>
4 # Copyright (C) 2012, Carlos Jenkins <carlos@jenkins.co.cr>
5 #
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18
19 ENCODING = 'UTF-8'
20
21 import sys
22 import argparse
23
24 # Python 2/3 unicode
25 import sys
26 if sys.version_info.major == 3:
27 io_in = lambda x: x
28 io_out = io_in
29 else:
30 io_in = lambda x: x.decode(ENCODING)
31 io_out = lambda x: x.encode(ENCODING)
32
33 # Pipes Python enconding nightmare
34 if sys.stdout.encoding is None:
35 import codecs
36 sys.stdout = codecs.getwriter(ENCODING)(sys.stdout)
37
38 # Find metadata dict
39 from os.path import join, dirname
40 sys.path.append(join(dirname(__file__), '../src/'))
41 from gtkspellcheck import __metadata__
42
43 # Parse command line
44 parser = argparse.ArgumentParser(description='Insert metadata into plain text files.')
45 parser.add_argument('infile', type=argparse.FileType('r'),
46 help='path to the template file or stdin pipe.')
47 parser.add_argument('-w', '--writeback', action='store_true',
48 help='write the output back to the input file.')
49 args = parser.parse_args()
50
51 # Read content
52 out_content = io_in(args.infile.read())
53 args.infile.close()
54
55 # Replace variables
56 # FIXME: Stop wasting memory like crazy!
57 for key, value in __metadata__.items():
58 out_content = out_content.replace(key, value)
59
60 # Print/Write new content
61 if args.writeback:
62 try:
63 with open(args.infile.name, 'w') as out_handler:
64 out_handler.write(io_out(out_content))
65 except Exception as e:
66 sys.stderr.write(str(e) + '\n')
67 sys.exit(-1)
68 else:
69 print(out_content)
70
71 sys.exit(0)
0 @ECHO OFF
1
2 REM Command file for Sphinx documentation
3
4 if "%SPHINXBUILD%" == "" (
5 set SPHINXBUILD=sphinx-build2
6 )
7 set BUILDDIR=build
8 set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% source
9 set I18NSPHINXOPTS=%SPHINXOPTS% source
10 if NOT "%PAPER%" == "" (
11 set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
12 set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%
13 )
14
15 if "%1" == "" goto help
16
17 if "%1" == "help" (
18 :help
19 echo.Please use `make ^<target^>` where ^<target^> is one of
20 echo. html to make standalone HTML files
21 echo. dirhtml to make HTML files named index.html in directories
22 echo. singlehtml to make a single large HTML file
23 echo. pickle to make pickle files
24 echo. json to make JSON files
25 echo. htmlhelp to make HTML files and a HTML help project
26 echo. qthelp to make HTML files and a qthelp project
27 echo. devhelp to make HTML files and a Devhelp project
28 echo. epub to make an epub
29 echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
30 echo. text to make text files
31 echo. man to make manual pages
32 echo. texinfo to make Texinfo files
33 echo. gettext to make PO message catalogs
34 echo. changes to make an overview over all changed/added/deprecated items
35 echo. linkcheck to check all external links for integrity
36 echo. doctest to run all doctests embedded in the documentation if enabled
37 goto end
38 )
39
40 if "%1" == "clean" (
41 for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
42 del /q /s %BUILDDIR%\*
43 goto end
44 )
45
46 if "%1" == "html" (
47 %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
48 if errorlevel 1 exit /b 1
49 echo.
50 echo.Build finished. The HTML pages are in %BUILDDIR%/html.
51 goto end
52 )
53
54 if "%1" == "dirhtml" (
55 %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
56 if errorlevel 1 exit /b 1
57 echo.
58 echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
59 goto end
60 )
61
62 if "%1" == "singlehtml" (
63 %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
64 if errorlevel 1 exit /b 1
65 echo.
66 echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
67 goto end
68 )
69
70 if "%1" == "pickle" (
71 %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
72 if errorlevel 1 exit /b 1
73 echo.
74 echo.Build finished; now you can process the pickle files.
75 goto end
76 )
77
78 if "%1" == "json" (
79 %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
80 if errorlevel 1 exit /b 1
81 echo.
82 echo.Build finished; now you can process the JSON files.
83 goto end
84 )
85
86 if "%1" == "htmlhelp" (
87 %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
88 if errorlevel 1 exit /b 1
89 echo.
90 echo.Build finished; now you can run HTML Help Workshop with the ^
91 .hhp project file in %BUILDDIR%/htmlhelp.
92 goto end
93 )
94
95 if "%1" == "qthelp" (
96 %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
97 if errorlevel 1 exit /b 1
98 echo.
99 echo.Build finished; now you can run "qcollectiongenerator" with the ^
100 .qhcp project file in %BUILDDIR%/qthelp, like this:
101 echo.^> qcollectiongenerator %BUILDDIR%\qthelp\PythonGTKSpellchecker.qhcp
102 echo.To view the help file:
103 echo.^> assistant -collectionFile %BUILDDIR%\qthelp\PythonGTKSpellchecker.ghc
104 goto end
105 )
106
107 if "%1" == "devhelp" (
108 %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
109 if errorlevel 1 exit /b 1
110 echo.
111 echo.Build finished.
112 goto end
113 )
114
115 if "%1" == "epub" (
116 %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
117 if errorlevel 1 exit /b 1
118 echo.
119 echo.Build finished. The epub file is in %BUILDDIR%/epub.
120 goto end
121 )
122
123 if "%1" == "latex" (
124 %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
125 if errorlevel 1 exit /b 1
126 echo.
127 echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
128 goto end
129 )
130
131 if "%1" == "text" (
132 %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
133 if errorlevel 1 exit /b 1
134 echo.
135 echo.Build finished. The text files are in %BUILDDIR%/text.
136 goto end
137 )
138
139 if "%1" == "man" (
140 %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
141 if errorlevel 1 exit /b 1
142 echo.
143 echo.Build finished. The manual pages are in %BUILDDIR%/man.
144 goto end
145 )
146
147 if "%1" == "texinfo" (
148 %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo
149 if errorlevel 1 exit /b 1
150 echo.
151 echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.
152 goto end
153 )
154
155 if "%1" == "gettext" (
156 %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale
157 if errorlevel 1 exit /b 1
158 echo.
159 echo.Build finished. The message catalogs are in %BUILDDIR%/locale.
160 goto end
161 )
162
163 if "%1" == "changes" (
164 %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
165 if errorlevel 1 exit /b 1
166 echo.
167 echo.The overview file is in %BUILDDIR%/changes.
168 goto end
169 )
170
171 if "%1" == "linkcheck" (
172 %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
173 if errorlevel 1 exit /b 1
174 echo.
175 echo.Link check complete; look for any errors in the above output ^
176 or in %BUILDDIR%/linkcheck/output.txt.
177 goto end
178 )
179
180 if "%1" == "doctest" (
181 %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
182 if errorlevel 1 exit /b 1
183 echo.
184 echo.Testing of doctests in the sources finished, look at the ^
185 results in %BUILDDIR%/doctest/output.txt.
186 goto end
187 )
188
189 :end
0 <!DOCTYPE html>
1 <html lang="en">
2 <head>
3 <meta http-equiv="content-type" content="text/html; charset=utf-8">
4 <meta http-equiv="refresh" content="2; URL=http://pygtkspellcheck.readthedocs.org/">
5
6 <title>PyGtkSpellcheck - Documentation</title>
7
8 <meta name="author" content="Maximilian Köhl">
9 </head>
10 <body>
11 The documentation has moved to <a href="http://pygtkspellcheck.readthedocs.org">Read the Docs</a>.
12 </body>
13 </html>
0 Python GTK Spellcheck
1 =====================
2 PyGtkSpellcheck is a simple but quite powerful spellchecking library written in
3 pure Python for Gtk based on Enchant_.
4 It supports PyGObject_ as well as PyGtk_ for Python 2 and 3 with automatic
5 switching and binding detection.
6 For automatic translation of the user interface it can use Gedit’s translation
7 files.
8
9 .. _Enchant: http://www.abisource.com/projects/enchant/
10 .. _PyGObject: https://live.gnome.org/PyGObject/
11 .. _PyGtk: http://www.pygtk.org/
12
13 Features
14 ^^^^^^^^
15 - Localized names of the available languages.
16 - Supports word, line and multiline ignore regexes.
17 - Supports ignore custom tags on Gtk's TextBuffer.
18 - Enable and disable of spellchecking with preferences memory.
19 - Supports hotswap of Gtk's TextBuffers.
20 - PyGObject and PyGtk compatible with automatic detection.
21 - Python 2 and 3 support.
22 - As Enchant, support for Hunspell (LibreOffice) and Aspell (GNU) dictionaries.
23
24
25 Documentation
26 ^^^^^^^^^^^^^
27 You can find the documentation at `Read the Docs`_.
28
29 .. _Read the Docs: http://pygtkspellcheck.readthedocs.org/
30
31 Development
32 ^^^^^^^^^^^
33 Development happens at `GitHub`_.
34
35 .. _GitHub: https://github.com/koehlma/pygtkspellcheck
36
37 License
38 ^^^^^^^
39 PyGtkSpellcheck is released under `GPLv3`_ or at your opinion any later version.
40
41 .. _GPLv3: https://www.gnu.org/licenses/gpl-3.0.html
0 # -*- coding: utf-8 -*-
1 #
2 # Python GTK Spellchecker documentation build configuration file, created by
3 # sphinx-quickstart2 on Tue Apr 10 18:57:32 2012.
4 #
5 # This file is execfile()d with the current directory set to its containing dir.
6 #
7 # Note that not all possible configuration values are present in this
8 # autogenerated file.
9 #
10 # All configuration values have a default; values that are commented out
11 # serve to show the default.
12
13 import sys, os
14
15 # If extensions (or modules to document with autodoc) are in another directory,
16 # add these directories to sys.path here. If the directory is relative to the
17 # documentation root, use os.path.abspath to make it absolute, like shown here.
18 #sys.path.insert(0, os.path.abspath('.'))
19
20 doc_directory = os.path.dirname(os.path.abspath(__file__))
21 sys.path.append(os.path.join(doc_directory, '..', '..', 'src'))
22
23 import sys
24
25 # Support for readthedocs.org
26 class Mock(object):
27 def __init__(self, *args, **kwargs):
28 pass
29
30 def __call__(self, *args, **kwargs):
31 return Mock()
32
33 @classmethod
34 def __getattr__(self, name):
35 if name in ('__file__', '__path__'):
36 return '/dev/null'
37 elif name[0] == name[0].upper():
38 return type(name, (), {})
39 else:
40 return Mock()
41
42 MOCK_MODULES = ['enchant']
43 for mod_name in MOCK_MODULES:
44 try:
45 __import__(mod_name)
46 except:
47 sys.modules[mod_name] = Mock()
48
49 import gtkspellcheck as m
50
51 start_file = 'index'
52
53 # -- General configuration -----------------------------------------------------
54
55 # If your documentation needs a minimal Sphinx version, state it here.
56 #needs_sphinx = '1.0'
57
58 # Add any Sphinx extension module names here, as strings. They can be extensions
59 # coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
60 extensions = ['sphinx.ext.autodoc']
61
62 # Add any paths that contain templates here, relative to this directory.
63 templates_path = ['_templates']
64
65 # The suffix of source filenames.
66 source_suffix = '.rst'
67
68 # The encoding of source files.
69 #source_encoding = 'utf-8-sig'
70
71 # The master toctree document.
72 master_doc = start_file
73
74 # General information about the project.
75 project = m.__project__
76 copyright = m.__authors__
77
78 # The version info for the project you're documenting, acts as replacement for
79 # |version| and |release|, also used in various other places throughout the
80 # built documents.
81 #
82 # The short X.Y version.
83 version = m.__version__
84 # The full version, including alpha/beta/rc tags.
85 release = m.__version__
86
87 # The language for content autogenerated by Sphinx. Refer to documentation
88 # for a list of supported languages.
89 #language = None
90
91 # There are two options for replacing |today|: either, you set today to some
92 # non-false value, then it is used:
93 #today = ''
94 # Else, today_fmt is used as the format for a strftime call.
95 #today_fmt = '%B %d, %Y'
96
97 # List of patterns, relative to source directory, that match files and
98 # directories to ignore when looking for source files.
99 exclude_patterns = []
100
101 # The reST default role (used for this markup: `text`) to use for all documents.
102 #default_role = None
103
104 # If true, '()' will be appended to :func: etc. cross-reference text.
105 #add_function_parentheses = True
106
107 # If true, the current module name will be prepended to all description
108 # unit titles (such as .. function::).
109 #add_module_names = True
110
111 # If true, sectionauthor and moduleauthor directives will be shown in the
112 # output. They are ignored by default.
113 #show_authors = False
114
115 # The name of the Pygments (syntax highlighting) style to use.
116 pygments_style = 'sphinx'
117
118 # A list of ignored prefixes for module index sorting.
119 #modindex_common_prefix = []
120
121
122 # -- Options for HTML output ---------------------------------------------------
123
124 # The theme to use for HTML and HTML Help pages. See the documentation for
125 # a list of builtin themes.
126 html_theme = 'default'
127
128 # Theme options are theme-specific and customize the look and feel of a theme
129 # further. For a list of options available for each theme, see the
130 # documentation.
131 #html_theme_options = {}
132
133 # Add any paths that contain custom themes here, relative to this directory.
134 #html_theme_path = []
135
136 # The name for this set of Sphinx documents. If None, it defaults to
137 # "<project> v<release> documentation".
138 #html_title = None
139
140 # A shorter title for the navigation bar. Default is the same as html_title.
141 #html_short_title = None
142
143 # The name of an image file (relative to this directory) to place at the top
144 # of the sidebar.
145 #html_logo = None
146
147 # The name of an image file (within the static path) to use as favicon of the
148 # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
149 # pixels large.
150 #html_favicon = None
151
152 # Add any paths that contain custom static files (such as style sheets) here,
153 # relative to this directory. They are copied after the builtin static files,
154 # so a file named "default.css" will overwrite the builtin "default.css".
155 #html_static_path = ['_static']
156
157 # If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
158 # using the given strftime format.
159 #html_last_updated_fmt = '%b %d, %Y'
160
161 # If true, SmartyPants will be used to convert quotes and dashes to
162 # typographically correct entities.
163 #html_use_smartypants = True
164
165 # Custom sidebar templates, maps document names to template names.
166 #html_sidebars = {}
167
168 # Additional templates that should be rendered to pages, maps page names to
169 # template names.
170 #html_additional_pages = {}
171
172 # If false, no module index is generated.
173 #html_domain_indices = True
174
175 # If false, no index is generated.
176 #html_use_index = True
177
178 # If true, the index is split into individual pages for each letter.
179 #html_split_index = False
180
181 # If true, links to the reST sources are added to the pages.
182 #html_show_sourcelink = True
183
184 # If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
185 #html_show_sphinx = True
186
187 # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
188 #html_show_copyright = True
189
190 # If true, an OpenSearch description file will be output, and all pages will
191 # contain a <link> tag referring to it. The value of this option must be the
192 # base URL from which the finished HTML is served.
193 #html_use_opensearch = ''
194
195 # This is the file name suffix for HTML files (e.g. ".xhtml").
196 #html_file_suffix = None
197
198 # Output file base name for HTML help builder.
199 htmlhelp_basename = m.__short_name__ + 'doc'
200
201
202 # -- Options for LaTeX output --------------------------------------------------
203
204 latex_elements = {
205 # The paper size ('letterpaper' or 'a4paper').
206 #'papersize': 'letterpaper',
207
208 # The font size ('10pt', '11pt' or '12pt').
209 #'pointsize': '10pt',
210
211 # Additional stuff for the LaTeX preamble.
212 #'preamble': '',
213 }
214
215 # Grouping the document tree into LaTeX files. List of tuples
216 # (source start file, target name, title, author, documentclass [howto/manual]).
217 latex_documents = [
218 (start_file, m.__short_name__ + '.tex', m.__project__ + ' Documentation',
219 m.__authors__.replace('&', r'\&'), 'manual'),
220 ]
221
222 # The name of an image file (relative to this directory) to place at the top of
223 # the title page.
224 #latex_logo = None
225
226 # For "manual" documents, if this is true, then toplevel headings are parts,
227 # not chapters.
228 #latex_use_parts = False
229
230 # If true, show page references after internal links.
231 #latex_show_pagerefs = False
232
233 # If true, show URL addresses after external links.
234 #latex_show_urls = False
235
236 # Documents to append as an appendix to all manuals.
237 #latex_appendices = []
238
239 # If false, no module index is generated.
240 #latex_domain_indices = True
241
242
243 # -- Options for manual page output --------------------------------------------
244
245 # One entry per manual page. List of tuples
246 # (source start file, name, description, authors, manual section).
247 man_pages = [
248 (start_file, m.__short_name__, m.__project__ + ' Documentation',
249 m.__authors__.split(' & '), 1)
250 ]
251
252 # If true, show URL addresses after external links.
253 #man_show_urls = False
254
255
256 # -- Options for Texinfo output ------------------------------------------------
257
258 # Grouping the document tree into Texinfo files. List of tuples
259 # (source start file, target name, title, author,
260 # dir menu entry, description, category)
261 texinfo_documents = [
262 (start_file, m.__short_name__, m.__project__ + ' Documentation',
263 m.__authors__, m.__short_name__, m.__desc_short__,
264 'Miscellaneous'),
265 ]
266
267 # Documents to append as an appendix to all manuals.
268 #texinfo_appendices = []
269
270 # If false, no module index is generated.
271 #texinfo_domain_indices = True
272
273 # How to display URL addresses: 'footnote', 'no', or 'inline'.
274 #texinfo_show_urls = 'footnote'
0 Python GTK Spellcheck
1 =====================
2
3 PyGtkSpellCheck is a spellchecking library written in pure Python for Gtk based
4 on Enchant_.
5 It supports both Gtk's Python bindings, PyGObject_ and PyGtk_, and for both
6 Python 2 and 3 with automatic switching and binding autodetection. For
7 automatic translation of the user interface it can use GEdit's translation
8 files.
9
10 .. _Enchant: http://www.abisource.com/projects/enchant/
11 .. _PyGObject: https://live.gnome.org/PyGObject/
12 .. _PyGtk: http://www.pygtk.org/
13
14
15 Features
16 --------
17
18 - Localized names of the available languages.
19 - Supports word, line and multiline ignore regexes.
20 - Supports ignore custom tags on Gtk's TextBuffer.
21 - Enable and disable of spellchecking with preferences memory.
22 - Supports hotswap of Gtk's TextBuffers.
23 - PyGObject and PyGtk compatible with automatic detection.
24 - Python 2 and 3 support.
25 - As Enchant, support for Hunspell (LibreOffice) and Aspell (GNU) dictionaries.
26
27
28 Download
29 --------
30
31 Source distribution
32 ^^^^^^^^^^^^^^^^^^^
33
34 PyPI package available at: http://pypi.python.org/pypi/pygtkspellcheck/
35
36 ``pip install pygtkspellcheck``
37
38 Ubuntu/Debian
39 ^^^^^^^^^^^^^
40
41 Install packages:
42
43 - Python 3:
44 - ``sudo apt-get install python3-gtkspellcheck``
45 - https://github.com/downloads/koehlma/pygtkspellcheck/python3-gtkspellcheck_3.0-1_all.deb
46
47 - Python 2:
48 - ``sudo apt-get install python-gtkspellcheck``
49 - https://github.com/downloads/koehlma/pygtkspellcheck/python-gtkspellcheck_3.0-1_all.deb
50
51 - Documentation:
52 - ``sudo apt-get install python-gtkspellcheck-doc``
53 - https://github.com/downloads/koehlma/pygtkspellcheck/python-gtkspellcheck-doc_3.0-1_all.deb
54
55 Archlinux
56 ^^^^^^^^^
57
58 Available in the `Archlinux User Repository`_:
59
60 .. _Archlinux User Repository: https://aur.archlinux.org/
61
62 - Python 3:
63 - ``yaourt -S python-gtkspellcheck``
64 - https://aur.archlinux.org/packages.php?ID=61200
65 - https://github.com/downloads/koehlma/pygtkspellcheck/python-gtkspellcheck-3.0-1-any.pkg.tar.xz
66
67 - Python 2:
68 - ``yaourt -S python2-gtkspellcheck``
69 - https://aur.archlinux.org/packages.php?ID=61199
70 - https://github.com/downloads/koehlma/pygtkspellcheck/python2-gtkspellcheck-3.0-1-any.pkg.tar.xz
71
72 Hacking
73 ^^^^^^^
74
75 Development repository is available at: https://github.com/koehlma/pygtkspellcheck
76
77 ``git clone git://github.com/koehlma/pygtkspellcheck.git``
78
79 Or download last sources in a `ZIP`_ or `Tarball`_ file.
80
81 .. _ZIP: https://github.com/koehlma/pygtkspellcheck/zipball/master
82 .. _Tarball: https://github.com/koehlma/pygtkspellcheck/tarball/master
83
84
85 API Reference
86 -------------
87
88 The main object is called Spellchecker and can be associated with any
89 GtkTextView:
90
91 .. toctree::
92 :maxdepth: 1
93
94 spellchecker
95
96 This library also includes a utility module to unpack `LibreOffice .oxt
97 extension dictionaries`_ (Hunspell). This is especially useful for MS Windows
98 users to include dictionaries for this library. Use this to extract the
99 Hunspell dictionaries out of the extension and then pass to the Spellchecker
100 the path to the location of the extraction in the params argument with the key
101 ``enchant.myspell.dictionary.path``.
102
103 .. _LibreOffice .oxt extension dictionaries: http://extensions.services.openoffice.org/dictionary
104
105 .. toctree::
106 :maxdepth: 1
107
108 oxt_import
109
110
111 Examples
112 --------
113
114 - `PyGObject Simple Example`_
115 - `PyGtk Simple Example`_
116
117 .. _PyGObject Simple Example: https://github.com/koehlma/pygtkspellcheck/blob/master/examples/simple_pygobject.py
118 .. _PyGtk Simple Example: https://github.com/koehlma/pygtkspellcheck/blob/master/examples/simple_pygtk.py
119
120
121 License
122 -------
123
124 This program is free software: you can redistribute it and/or modify
125 it under the terms of the GNU General Public License as published by
126 the Free Software Foundation, either version 3 of the License, or
127 (at your option) any later version.
128
129 This program is distributed in the hope that it will be useful,
130 but WITHOUT ANY WARRANTY; without even the implied warranty of
131 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
132 GNU General Public License for more details.
133
134 You should have received a copy of the GNU General Public License
135 along with this program. If not, see <http://www.gnu.org/licenses/>.
0 oxt_import module reference
1 ===========================
2
3 .. autofunction:: gtkspellcheck.oxt_import.deflate_oxt
0 SpellChecker class reference
1 ============================
2
3 .. autoclass:: gtkspellcheck.spellcheck.SpellChecker
4 :members:
0 # -*- coding:utf-8 -*-
1 #
2 # Copyright (C) 2012, Maximilian Köhl <linuxmaxi@googlemail.com>
3 # Copyright (C) 2012, Carlos Jenkins <carlos@jenkins.co.cr>
4 #
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
17
18 # Load example if running from source, ignore this
19 import sys
20 from os.path import join, dirname
21 sys.path.append(join(dirname(__file__), '../src/'))
22
23 import locale
24
25 from gi.repository import Gtk as gtk
26
27 from gtkspellcheck import SpellChecker
28
29 if __name__ == '__main__':
30 def quit(*args):
31 gtk.main_quit()
32
33 window = gtk.Window.new(gtk.WindowType.TOPLEVEL)
34 window.set_title('PyGtkSpellCheck Example')
35 view = gtk.TextView.new()
36
37 spellchecker = SpellChecker(view, locale.getdefaultlocale()[0], collapse=False)
38
39 for code, name in spellchecker.languages:
40 print('code: %5s, language: %s' % (code, name))
41
42 window.set_default_size(600, 400)
43 window.add(view)
44 window.show_all()
45 window.connect('delete-event', quit)
46 gtk.main()
0 # -*- coding:utf-8 -*-
1 #
2 # Copyright (C) 2012, Maximilian Köhl <linuxmaxi@googlemail.com>
3 # Copyright (C) 2012, Carlos Jenkins <carlos@jenkins.co.cr>
4 #
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
17
18 # Load example if running from source, ignore this
19 import sys
20 from os.path import join, dirname
21 sys.path.append(join(dirname(__file__), '../src/'))
22
23 import locale
24
25 import gtk
26
27 from gtkspellcheck import SpellChecker
28
29 if __name__ == '__main__':
30 def quit(*args):
31 gtk.main_quit()
32
33 window = gtk.Window(gtk.WINDOW_TOPLEVEL)
34 window.set_title('PyGtkSpellCheck Example')
35 view = gtk.TextView()
36
37 spellchecker = SpellChecker(view, locale.getdefaultlocale()[0], collapse=False)
38
39 for code, name in spellchecker.languages:
40 print('code: %5s, language: %s' % (code, name))
41
42 window.set_default_size(600, 400)
43 window.add(view)
44 window.show_all()
45 window.connect('delete-event', quit)
46 gtk.main()
0 # -*- coding:utf-8 -*-
1 #
2 # Copyright (C) 2012, Maximilian Köhl <linuxmaxi@googlemail.com>
3 # Copyright (C) 2012, Carlos Jenkins <carlos@jenkins.co.cr>
4 #
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
17
18 # Load example if running from source, ignore this
19 import sys
20 from os.path import join, dirname
21 sys.path.append(join(dirname(__file__), '../src/'))
22
23 import locale
24
25 from gi.repository import Gtk as gtk
26
27 from gtkspellcheck import SpellChecker
28
29 if __name__ == '__main__':
30 def quit(*args):
31 gtk.main_quit()
32
33 window = gtk.Window.new(gtk.WindowType.TOPLEVEL)
34 window.set_title('PyGtkSpellCheck Example')
35 view = gtk.TextView.new()
36
37 spellchecker = SpellChecker(view, locale.getdefaultlocale()[0])
38
39 for code, name in spellchecker.languages:
40 print('code: %5s, language: %s' % (code, name))
41
42 window.set_default_size(600, 400)
43 window.add(view)
44 window.show_all()
45 window.connect('delete-event', quit)
46 gtk.main()
0 # -*- coding:utf-8 -*-
1 #
2 # Copyright (C) 2012, Maximilian Köhl <linuxmaxi@googlemail.com>
3 # Copyright (C) 2012, Carlos Jenkins <carlos@jenkins.co.cr>
4 #
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
17
18 # Load example if running from source, ignore this
19 import sys
20 from os.path import join, dirname
21 sys.path.append(join(dirname(__file__), '../src/'))
22
23 import locale
24
25 import gtk
26
27 from gtkspellcheck import SpellChecker
28
29 if __name__ == '__main__':
30 def quit(*args):
31 gtk.main_quit()
32
33 window = gtk.Window(gtk.WINDOW_TOPLEVEL)
34 window.set_title('PyGtkSpellCheck Example')
35 view = gtk.TextView()
36
37 spellchecker = SpellChecker(view, locale.getdefaultlocale()[0])
38
39 for code, name in spellchecker.languages:
40 print('code: %5s, language: %s' % (code, name))
41
42 window.set_default_size(600, 400)
43 window.add(view)
44 window.show_all()
45 window.connect('delete-event', quit)
46 gtk.main()
0 #!/usr/bin/env python
1
2 import os
3 import sys
4 import shutil
5
6 where_am_i = os.path.normpath(os.path.dirname(os.path.abspath(os.path.realpath(__file__))))
7 os.chdir(where_am_i)
8
9 if sys.version_info.major == 3:
10 import msgfmt3 as msgfmt
11 else:
12 import msgfmt2 as msgfmt
13
14 def build_mo_files():
15 """Compile available localization files"""
16
17 APP = 'pygtkspellcheck'
18 locale_dir = 'mo'
19 po_dir = 'pygtkspellcheck'
20
21 if os.path.exists(locale_dir):
22 shutil.rmtree(locale_dir)
23 os.mkdir(locale_dir)
24
25 available_langs = [f[:-3] for f in os.listdir(po_dir) if f.endswith('.po')]
26
27 print('Languages: {langs}'.format(langs=str(available_langs)))
28
29 for lang in available_langs:
30 po_file = os.path.join(po_dir, lang + '.po')
31 lang_dir = os.path.join(locale_dir, lang)
32 mo_dir = os.path.join(lang_dir, 'LC_MESSAGES')
33 mo_file = os.path.join(mo_dir, APP + '.mo')
34
35 if not os.path.exists(mo_dir):
36 os.makedirs(mo_dir)
37
38 print('Compiling {0} to {1}'.format(po_file, mo_file))
39 msgfmt.make(po_file, mo_file)
40
41 if __name__ == '__main__':
42 build_mo_files()
43
0 #!/bin/bash
1 xgettext --keyword=translatable --sort-output -o pygtkspellcheck/en.po \
2 ../src/gtkspellcheck/spellcheck.py ../src/gtkspellcheck/oxt_import.py
3 echo "Done!"
0 #! /usr/bin/env python
1 # -*- coding: iso-8859-1 -*-
2 # Written by Martin v. Löwis <loewis@informatik.hu-berlin.de>
3
4 """Generate binary message catalog from textual translation description.
5
6 This program converts a textual Uniforum-style message catalog (.po file) into
7 a binary GNU catalog (.mo file). This is essentially the same function as the
8 GNU msgfmt program, however, it is a simpler implementation.
9
10 Usage: msgfmt.py [OPTIONS] filename.po
11
12 Options:
13 -o file
14 --output-file=file
15 Specify the output file to write to. If omitted, output will go to a
16 file named filename.mo (based off the input file name).
17
18 -h
19 --help
20 Print this message and exit.
21
22 -V
23 --version
24 Display version information and exit.
25 """
26
27 import sys
28 import os
29 import getopt
30 import struct
31 import array
32
33 __version__ = "1.1"
34
35 MESSAGES = {}
36
37
38 def usage(code, msg=''):
39 print >> sys.stderr, __doc__
40 if msg:
41 print >> sys.stderr, msg
42 sys.exit(code)
43
44
45 def add(id, str, fuzzy):
46 "Add a non-fuzzy translation to the dictionary."
47 global MESSAGES
48 if not fuzzy and str:
49 MESSAGES[id] = str
50
51
52 def generate():
53 "Return the generated output."
54 global MESSAGES
55 keys = MESSAGES.keys()
56 # the keys are sorted in the .mo file
57 keys.sort()
58 offsets = []
59 ids = strs = ''
60 for id in keys:
61 # For each string, we need size and file offset. Each string is NUL
62 # terminated; the NUL does not count into the size.
63 offsets.append((len(ids), len(id), len(strs), len(MESSAGES[id])))
64 ids += id + '\0'
65 strs += MESSAGES[id] + '\0'
66 output = ''
67 # The header is 7 32-bit unsigned integers. We don't use hash tables, so
68 # the keys start right after the index tables.
69 # translated string.
70 keystart = 7*4+16*len(keys)
71 # and the values start after the keys
72 valuestart = keystart + len(ids)
73 koffsets = []
74 voffsets = []
75 # The string table first has the list of keys, then the list of values.
76 # Each entry has first the size of the string, then the file offset.
77 for o1, l1, o2, l2 in offsets:
78 koffsets += [l1, o1+keystart]
79 voffsets += [l2, o2+valuestart]
80 offsets = koffsets + voffsets
81 output = struct.pack("Iiiiiii",
82 0x950412deL, # Magic
83 0, # Version
84 len(keys), # # of entries
85 7*4, # start of key index
86 7*4+len(keys)*8, # start of value index
87 0, 0) # size and offset of hash table
88 output += array.array("i", offsets).tostring()
89 output += ids
90 output += strs
91 return output
92
93
94 def make(filename, outfile):
95 ID = 1
96 STR = 2
97
98 # Compute .mo name from .po name and arguments
99 if filename.endswith('.po'):
100 infile = filename
101 else:
102 infile = filename + '.po'
103 if outfile is None:
104 outfile = os.path.splitext(infile)[0] + '.mo'
105
106 try:
107 lines = open(infile).readlines()
108 except IOError, msg:
109 print >> sys.stderr, msg
110 sys.exit(1)
111
112 section = None
113 fuzzy = 0
114
115 # Parse the catalog
116 lno = 0
117 for l in lines:
118 lno += 1
119 # If we get a comment line after a msgstr, this is a new entry
120 if l[0] == '#' and section == STR:
121 add(msgid, msgstr, fuzzy)
122 section = None
123 fuzzy = 0
124 # Record a fuzzy mark
125 if l[:2] == '#,' and 'fuzzy' in l:
126 fuzzy = 1
127 # Skip comments
128 if l[0] == '#':
129 continue
130 # Now we are in a msgid section, output previous section
131 if l.startswith('msgid') and not l.startswith('msgid_plural'):
132 if section == STR:
133 add(msgid, msgstr, fuzzy)
134 section = ID
135 l = l[5:]
136 msgid = msgstr = ''
137 is_plural = False
138 # This is a message with plural forms
139 elif l.startswith('msgid_plural'):
140 if section != ID:
141 print >> sys.stderr, 'msgid_plural not preceeded by msgid on %s:%d' %\
142 (infile, lno)
143 sys.exit(1)
144 l = l[12:]
145 msgid += '\0' # separator of singular and plural
146 is_plural = True
147 # Now we are in a msgstr section
148 elif l.startswith('msgstr'):
149 section = STR
150 if l.startswith('msgstr['):
151 if not is_plural:
152 print >> sys.stderr, 'plural without msgid_plural on %s:%d' %\
153 (infile, lno)
154 sys.exit(1)
155 l = l.split(']', 1)[1]
156 if msgstr:
157 msgstr += '\0' # Separator of the various plural forms
158 else:
159 if is_plural:
160 print >> sys.stderr, 'indexed msgstr required for plural on %s:%d' %\
161 (infile, lno)
162 sys.exit(1)
163 l = l[6:]
164 # Skip empty lines
165 l = l.strip()
166 if not l:
167 continue
168 # XXX: Does this always follow Python escape semantics?
169 l = eval(l)
170 if section == ID:
171 msgid += l
172 elif section == STR:
173 msgstr += l
174 else:
175 print >> sys.stderr, 'Syntax error on %s:%d' % (infile, lno), \
176 'before:'
177 print >> sys.stderr, l
178 sys.exit(1)
179 # Add last entry
180 if section == STR:
181 add(msgid, msgstr, fuzzy)
182
183 # Compute output
184 output = generate()
185
186 try:
187 open(outfile,"wb").write(output)
188 except IOError,msg:
189 print >> sys.stderr, msg
190
191 def main():
192 try:
193 opts, args = getopt.getopt(sys.argv[1:], 'hVo:',
194 ['help', 'version', 'output-file='])
195 except getopt.error, msg:
196 usage(1, msg)
197
198 outfile = None
199 # parse options
200 for opt, arg in opts:
201 if opt in ('-h', '--help'):
202 usage(0)
203 elif opt in ('-V', '--version'):
204 print >> sys.stderr, "msgfmt.py", __version__
205 sys.exit(0)
206 elif opt in ('-o', '--output-file'):
207 outfile = arg
208 # do it
209 if not args:
210 print >> sys.stderr, 'No input file given'
211 print >> sys.stderr, "Try `msgfmt --help' for more information."
212 return
213
214 for filename in args:
215 make(filename, outfile)
216
217
218 if __name__ == '__main__':
219 main()
0 #! /usr/bin/python3.2
1 # Written by Martin v. Löwis <loewis@informatik.hu-berlin.de>
2
3 """Generate binary message catalog from textual translation description.
4
5 This program converts a textual Uniforum-style message catalog (.po file) into
6 a binary GNU catalog (.mo file). This is essentially the same function as the
7 GNU msgfmt program, however, it is a simpler implementation.
8
9 Usage: msgfmt.py [OPTIONS] filename.po
10
11 Options:
12 -o file
13 --output-file=file
14 Specify the output file to write to. If omitted, output will go to a
15 file named filename.mo (based off the input file name).
16
17 -h
18 --help
19 Print this message and exit.
20
21 -V
22 --version
23 Display version information and exit.
24 """
25
26 import sys
27 import os
28 import getopt
29 import struct
30 import array
31 from email.parser import HeaderParser
32
33 __version__ = "1.1"
34
35 MESSAGES = {}
36
37
38
39 def usage(code, msg=''):
40 print(__doc__, file=sys.stderr)
41 if msg:
42 print(msg, file=sys.stderr)
43 sys.exit(code)
44
45
46
47 def add(id, str, fuzzy):
48 "Add a non-fuzzy translation to the dictionary."
49 global MESSAGES
50 if not fuzzy and str:
51 MESSAGES[id] = str
52
53
54
55 def generate():
56 "Return the generated output."
57 global MESSAGES
58 # the keys are sorted in the .mo file
59 keys = sorted(MESSAGES.keys())
60 offsets = []
61 ids = strs = b''
62 for id in keys:
63 # For each string, we need size and file offset. Each string is NUL
64 # terminated; the NUL does not count into the size.
65 offsets.append((len(ids), len(id), len(strs), len(MESSAGES[id])))
66 ids += id + b'\0'
67 strs += MESSAGES[id] + b'\0'
68 output = ''
69 # The header is 7 32-bit unsigned integers. We don't use hash tables, so
70 # the keys start right after the index tables.
71 # translated string.
72 keystart = 7*4+16*len(keys)
73 # and the values start after the keys
74 valuestart = keystart + len(ids)
75 koffsets = []
76 voffsets = []
77 # The string table first has the list of keys, then the list of values.
78 # Each entry has first the size of the string, then the file offset.
79 for o1, l1, o2, l2 in offsets:
80 koffsets += [l1, o1+keystart]
81 voffsets += [l2, o2+valuestart]
82 offsets = koffsets + voffsets
83 output = struct.pack("Iiiiiii",
84 0x950412de, # Magic
85 0, # Version
86 len(keys), # # of entries
87 7*4, # start of key index
88 7*4+len(keys)*8, # start of value index
89 0, 0) # size and offset of hash table
90 output += array.array("i", offsets).tostring()
91 output += ids
92 output += strs
93 return output
94
95
96
97 def make(filename, outfile):
98 ID = 1
99 STR = 2
100
101 # Compute .mo name from .po name and arguments
102 if filename.endswith('.po'):
103 infile = filename
104 else:
105 infile = filename + '.po'
106 if outfile is None:
107 outfile = os.path.splitext(infile)[0] + '.mo'
108
109 try:
110 lines = open(infile, 'rb').readlines()
111 except IOError as msg:
112 print(msg, file=sys.stderr)
113 sys.exit(1)
114
115 section = None
116 fuzzy = 0
117
118 # Start off assuming Latin-1, so everything decodes without failure,
119 # until we know the exact encoding
120 encoding = 'latin-1'
121
122 # Parse the catalog
123 lno = 0
124 for l in lines:
125 l = l.decode(encoding)
126 lno += 1
127 # If we get a comment line after a msgstr, this is a new entry
128 if l[0] == '#' and section == STR:
129 add(msgid, msgstr, fuzzy)
130 section = None
131 fuzzy = 0
132 # Record a fuzzy mark
133 if l[:2] == '#,' and 'fuzzy' in l:
134 fuzzy = 1
135 # Skip comments
136 if l[0] == '#':
137 continue
138 # Now we are in a msgid section, output previous section
139 if l.startswith('msgid') and not l.startswith('msgid_plural'):
140 if section == STR:
141 add(msgid, msgstr, fuzzy)
142 if not msgid:
143 # See whether there is an encoding declaration
144 p = HeaderParser()
145 charset = p.parsestr(msgstr.decode(encoding)).get_content_charset()
146 if charset:
147 encoding = charset
148 section = ID
149 l = l[5:]
150 msgid = msgstr = b''
151 is_plural = False
152 # This is a message with plural forms
153 elif l.startswith('msgid_plural'):
154 if section != ID:
155 print('msgid_plural not preceeded by msgid on %s:%d' % (infile, lno),
156 file=sys.stderr)
157 sys.exit(1)
158 l = l[12:]
159 msgid += b'\0' # separator of singular and plural
160 is_plural = True
161 # Now we are in a msgstr section
162 elif l.startswith('msgstr'):
163 section = STR
164 if l.startswith('msgstr['):
165 if not is_plural:
166 print('plural without msgid_plural on %s:%d' % (infile, lno),
167 file=sys.stderr)
168 sys.exit(1)
169 l = l.split(']', 1)[1]
170 if msgstr:
171 msgstr += b'\0' # Separator of the various plural forms
172 else:
173 if is_plural:
174 print('indexed msgstr required for plural on %s:%d' % (infile, lno),
175 file=sys.stderr)
176 sys.exit(1)
177 l = l[6:]
178 # Skip empty lines
179 l = l.strip()
180 if not l:
181 continue
182 # XXX: Does this always follow Python escape semantics?
183 l = eval(l)
184 if section == ID:
185 msgid += l.encode(encoding)
186 elif section == STR:
187 msgstr += l.encode(encoding)
188 else:
189 print('Syntax error on %s:%d' % (infile, lno), \
190 'before:', file=sys.stderr)
191 print(l, file=sys.stderr)
192 sys.exit(1)
193 # Add last entry
194 if section == STR:
195 add(msgid, msgstr, fuzzy)
196
197 # Compute output
198 output = generate()
199
200 try:
201 open(outfile,"wb").write(output)
202 except IOError as msg:
203 print(msg, file=sys.stderr)
204
205
206
207 def main():
208 try:
209 opts, args = getopt.getopt(sys.argv[1:], 'hVo:',
210 ['help', 'version', 'output-file='])
211 except getopt.error as msg:
212 usage(1, msg)
213
214 outfile = None
215 # parse options
216 for opt, arg in opts:
217 if opt in ('-h', '--help'):
218 usage(0)
219 elif opt in ('-V', '--version'):
220 print("msgfmt.py", __version__, file=sys.stderr)
221 sys.exit(0)
222 elif opt in ('-o', '--output-file'):
223 outfile = arg
224 # do it
225 if not args:
226 print('No input file given', file=sys.stderr)
227 print("Try `msgfmt --help' for more information.", file=sys.stderr)
228 return
229
230 for filename in args:
231 make(filename, outfile)
232
233
234 if __name__ == '__main__':
235 main()
0 msgid ""
1 msgstr ""
2 "Project-Id-Version: gtkspellchecker\n"
3 "Report-Msgid-Bugs-To: \n"
4 "POT-Creation-Date: 2012-07-23 00:08+0100\n"
5 "PO-Revision-Date: 2012-07-23 00:08+0100\n"
6 "Last-Translator: Maximilian Köhl <linuxmaxi@googlemail.com>\n"
7 "Language-Team: \n"
8 "Language: \n"
9 "MIME-Version: 1.0\n"
10 "Content-Type: text/plain; charset=UTF-8\n"
11 "Content-Transfer-Encoding: 8bit\n"
12 "X-Poedit-KeywordsList: _;gettext;gettext_noop\n"
13 "X-Poedit-Basepath: /home/maximilian/Entwicklung/pygtkspellcheck/src\n"
14 "X-Poedit-Language: German\n"
15 "X-Poedit-SourceCharset: utf-8\n"
16 "X-Poedit-SearchPath-0: ./gtkspellcheck\n"
17
18 #: ../src/gtkspellcheck/spellcheck.py:412
19 msgid "(no suggestions)"
20 msgstr "(keine Vorschläge)"
21
22 #: ../src/gtkspellcheck/spellcheck.py:433
23 #: ../src/gtkspellcheck/spellcheck.py:436
24 msgid "Add \"{word}\" to Dictionary"
25 msgstr "\"{word}\" zum Wörterbuch hinzufügen"
26
27 #: ../src/gtkspellcheck/spellcheck.py:440
28 #: ../src/gtkspellcheck/spellcheck.py:442
29 msgid "Ignore All"
30 msgstr "Alles ignorieren"
31
32 #: ../src/gtkspellcheck/spellcheck.py:457
33 #: ../src/gtkspellcheck/spellcheck.py:459
34 msgid "Languages"
35 msgstr "Sprachen"
36
37 #: ../src/gtkspellcheck/spellcheck.py:470
38 #: ../src/gtkspellcheck/spellcheck.py:473
39 msgid "Suggestions"
40 msgstr "Vorschläge"
41
42 #: ../src/gtkspellcheck/oxt_import.py:138
43 msgid "'{0}' declared in registry but not found within the extension."
44 msgstr "'{0}' wurde in der Wörterbuch Datenbank angegeben, kann aber nicht gefunden werden."
45
46 #: ../src/gtkspellcheck/oxt_import.py:141
47 msgid "Error while processing extension {0}."
48 msgstr "Fehler beim Bearbeiten der Erweiterung {0}."
49
50 #: ../src/gtkspellcheck/oxt_import.py:144
51 msgid "Extension '{0}' has no dictionary registry."
52 msgstr "Erweiterung '{0}' hat keine Wörterbuch Datenbank."
53
54 #: ../src/gtkspellcheck/oxt_import.py:146
55 msgid "Extension '{0}' is not a valid zip file."
56 msgstr "Erweiterung '{0}' ist keine Zip-Datei."
57
58 #: ../src/gtkspellcheck/oxt_import.py:86
59 msgid "Extract path is not a directory."
60 msgstr "Ziel ist kein Verzeichnis."
61
62 #: ../src/gtkspellcheck/oxt_import.py:160
63 msgid "Unable to move extension, file with same name exists within move_path."
64 msgstr "Die Erweiterung konnte nicht verschoben werden, eine Datei mit gleichem Namen existiert bereits."
65
66 #: ../src/gtkspellcheck/oxt_import.py:162
67 msgid "Unable to move extension, move_path is not a directory."
68 msgstr "Die Erweiterung konnte nicht verschoben werden, Ziel ist kein Verzeichnis."
0 # SOME DESCRIPTIVE TITLE.
1 # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
2 # This file is distributed under the same license as the PACKAGE package.
3 # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
4 #
5 #, fuzzy
6 msgid ""
7 msgstr ""
8 "Project-Id-Version: PACKAGE VERSION\n"
9 "Report-Msgid-Bugs-To: \n"
10 "POT-Creation-Date: 2012-07-23 14:00+0200\n"
11 "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
12 "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
13 "Language-Team: LANGUAGE <LL@li.org>\n"
14 "Language: \n"
15 "MIME-Version: 1.0\n"
16 "Content-Type: text/plain; charset=CHARSET\n"
17 "Content-Transfer-Encoding: 8bit\n"
18
19 #: ../src/gtkspellcheck/spellcheck.py:412
20 msgid "(no suggestions)"
21 msgstr ""
22
23 #: ../src/gtkspellcheck/spellcheck.py:433
24 #: ../src/gtkspellcheck/spellcheck.py:436
25 msgid "Add \"{word}\" to Dictionary"
26 msgstr ""
27
28 #: ../src/gtkspellcheck/spellcheck.py:440
29 #: ../src/gtkspellcheck/spellcheck.py:442
30 msgid "Ignore All"
31 msgstr ""
32
33 #: ../src/gtkspellcheck/spellcheck.py:457
34 #: ../src/gtkspellcheck/spellcheck.py:459
35 msgid "Languages"
36 msgstr ""
37
38 #: ../src/gtkspellcheck/spellcheck.py:470
39 #: ../src/gtkspellcheck/spellcheck.py:473
40 msgid "Suggestions"
41 msgstr ""
42
43 #: ../src/gtkspellcheck/oxt_import.py:138
44 msgid "'{0}' declared in registry but not found within the extension."
45 msgstr ""
46
47 #: ../src/gtkspellcheck/oxt_import.py:141
48 msgid "Error while processing extension {0}."
49 msgstr ""
50
51 #: ../src/gtkspellcheck/oxt_import.py:144
52 msgid "Extension '{0}' has no dictionary registry."
53 msgstr ""
54
55 #: ../src/gtkspellcheck/oxt_import.py:146
56 msgid "Extension '{0}' is not a valid zip file."
57 msgstr ""
58
59 #: ../src/gtkspellcheck/oxt_import.py:86
60 msgid "Extract path is not a directory."
61 msgstr ""
62
63 #: ../src/gtkspellcheck/oxt_import.py:160
64 msgid "Unable to move extension, file with same name exists within move_path."
65 msgstr ""
66
67 #: ../src/gtkspellcheck/oxt_import.py:162
68 msgid "Unable to move extension, move_path is not a directory."
69 msgstr ""
0 # SOME DESCRIPTIVE TITLE.
1 # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
2 # This file is distributed under the same license as the PACKAGE package.
3 # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
4 #
5 msgid ""
6 msgstr ""
7 "Project-Id-Version: pygtkspellcheck_3.0a\n"
8 "Report-Msgid-Bugs-To: \n"
9 "POT-Creation-Date: 2012-07-23 05:23-0600\n"
10 "PO-Revision-Date: 2012-07-23 05:26-0600\n"
11 "Last-Translator: Carlos Jenkins <carlos@jenkins.co.cr>\n"
12 "Language-Team: Carlos Jenkins <carlos@jenkins.co.cr>\n"
13 "Language: \n"
14 "MIME-Version: 1.0\n"
15 "Content-Type: text/plain; charset=utf-8\n"
16 "Content-Transfer-Encoding: 8bit\n"
17 "X-Poedit-Language: Spanish\n"
18
19 #: ../src/gtkspellcheck/spellcheck.py:412
20 msgid "(no suggestions)"
21 msgstr "(sin sugerencias)"
22
23 #: ../src/gtkspellcheck/spellcheck.py:433
24 #: ../src/gtkspellcheck/spellcheck.py:436
25 msgid "Add \"{word}\" to Dictionary"
26 msgstr "Agregar \"{word}\" al Diccionario"
27
28 #: ../src/gtkspellcheck/spellcheck.py:440
29 #: ../src/gtkspellcheck/spellcheck.py:442
30 msgid "Ignore All"
31 msgstr "Ignorar Todos"
32
33 #: ../src/gtkspellcheck/spellcheck.py:457
34 #: ../src/gtkspellcheck/spellcheck.py:459
35 msgid "Languages"
36 msgstr "Idiomas"
37
38 #: ../src/gtkspellcheck/spellcheck.py:470
39 #: ../src/gtkspellcheck/spellcheck.py:473
40 msgid "Suggestions"
41 msgstr "Sugerencias"
42
43 #: ../src/gtkspellcheck/oxt_import.py:138
44 msgid "'{0}' declared in registry but not found within the extension."
45 msgstr "'{0}' ha sido declarado en el archivo de registro pero no pudo ser encontrado dentro de la extensión."
46
47 #: ../src/gtkspellcheck/oxt_import.py:141
48 msgid "Error while processing extension {0}."
49 msgstr "Hubo un error al procesar la extensión {0}."
50
51 #: ../src/gtkspellcheck/oxt_import.py:144
52 msgid "Extension '{0}' has no dictionary registry."
53 msgstr "La extensión '{0}' no tiene un archivo de registro de diccionarios."
54
55 #: ../src/gtkspellcheck/oxt_import.py:146
56 msgid "Extension '{0}' is not a valid zip file."
57 msgstr "La extensión '{0}' no es un archivo zip válido."
58
59 #: ../src/gtkspellcheck/oxt_import.py:86
60 msgid "Extract path is not a directory."
61 msgstr "La ruta de extracción no es un directorio."
62
63 #: ../src/gtkspellcheck/oxt_import.py:160
64 msgid "Unable to move extension, file with same name exists within move_path."
65 msgstr "No fue posible mover el archivo de la extensión, un archivo del mismo nombre ya existe dentro de move_path."
66
67 #: ../src/gtkspellcheck/oxt_import.py:162
68 msgid "Unable to move extension, move_path is not a directory."
69 msgstr "No fue posible mover el archivo de la extensión, move_path no es un directorio."
0 # -*- coding:utf-8 -*-
1 #
2 # Copyright (C) 2012, Maximilian Köhl <linuxmaxi@googlemail.com>
3 # Copyright (C) 2012, Carlos Jenkins <carlos@jenkins.co.cr>
4 #
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
17
18 from __future__ import print_function
19
20 import os
21 import sys
22
23 from distutils.core import setup
24
25 cmdclass = {}
26 try:
27 from sphinx.setup_command import BuildDoc
28 cmdclass['build_sphinx'] = BuildDoc
29 except ImportError as e:
30 print(e)
31 print('Unable to import Sphinx custom command. Documentation build will '
32 'be unavailable. Install python-sphinx to solve this.')
33
34 try:
35 from sphinx_pypi_upload import UploadDoc
36 cmdclass['upload_sphinx'] = UploadDoc
37 except ImportError as e:
38 print(e)
39 print('Unable to import Sphinx custom command. Documentation upload '
40 'be unavailable. Install http://pypi.python.org/pypi/Sphinx-PyPI-'
41 'upload/ to solve this.')
42
43 sys.path.insert(0, './src/')
44 import gtkspellcheck as m
45
46 if len(sys.argv) > 1 and sys.argv[1] == 'register':
47 m.__desc_long__ = open(os.path.join('.', 'doc', 'pypi', 'page.rst'), 'r').read()
48 print('pypi registration: override `long_description`')
49
50 setup(name=m.__short_name__,
51 version=m.__version__,
52 description=m.__desc_short__,
53 long_description=m.__desc_long__,
54 author=m.__authors__,
55 author_email=m.__emails__,
56 url=m.__website__,
57 download_url=m.__download_url__,
58 license='GPLv3+',
59 package_dir={'': 'src'},
60 packages=['gtkspellcheck', 'pylocales'],
61 package_data={'pylocales' : ['locales.db']},
62 classifiers=[
63 'Development Status :: 5 - Production/Stable',
64 'Environment :: X11 Applications :: Gnome',
65 'Intended Audience :: Developers',
66 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
67 'Operating System :: MacOS :: MacOS X', # Should work on MacOS X I think...
68 'Operating System :: Microsoft :: Windows',
69 'Operating System :: POSIX',
70 'Programming Language :: Python :: 2',
71 'Programming Language :: Python :: 3',
72 'Topic :: Software Development :: Localization'],
73 cmdclass=cmdclass)
0 # -*- coding:utf-8 -*-
1 #
2 # Copyright (C) 2012, Maximilian Köhl <linuxmaxi@googlemail.com>
3 # Copyright (C) 2012, Carlos Jenkins <carlos@jenkins.co.cr>
4 #
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
17
18 # Python 2/3 unicode
19 import sys
20 if sys.version_info.major == 3:
21 u = lambda x: x
22 else:
23 u = lambda x: x.decode('utf-8')
24
25 # Metadata
26 __version__ = '3.0'
27 __project__ = 'Python GTK Spellcheck'
28 __short_name__ = 'pygtkspellcheck'
29 __authors__ = u('Maximilian Köhl & Carlos Jenkins')
30 __emails__ = u('linuxmaxi@googlemail.com & carlos@jenkins.co.cr')
31 __website__ = 'http://koehlma.github.com/projects/pygtkspellcheck.html'
32 __download_url__ = 'https://github.com/koehlma/pygtkspellcheck/tarball/master'
33 __source__ = 'https://github.com/koehlma/pygtkspellcheck/'
34 __vcs__ = 'git://github.com/koehlma/pygtkspellcheck.git'
35 __copyright__ = u('2012, Maximilian Köhl & Carlos Jenkins')
36 __desc_short__ = 'A simple but quite powerful Python spell checking library for GtkTextViews based on Enchant.'
37 __desc_long__ = ('It supports both Gtk\'s Python bindings, PyGObject and'
38 'PyGtk, and for both Python 2 and 3 with automatic switching'
39 'and binding autodetection. For automatic translation of the'
40 'user interface it can use GEdit\'s translation files.')
41
42 __metadata__ = {'__version__' : __version__,
43 '__project__' : __project__,
44 '__short_name__' : __short_name__,
45 '__authors__' : __authors__,
46 '__emails__' : __emails__,
47 '__website__' : __website__,
48 '__download_url__' : __download_url__,
49 '__source__' : __source__,
50 '__vcs__' : __vcs__,
51 '__copyright__' : __copyright__,
52 '__desc_short__' : __desc_short__,
53 '__desc_long__' : __desc_long__}
54
55 # import SpellChecker class
56 from gtkspellcheck.spellcheck import SpellChecker
0 # -*- coding:utf-8 -*-
1 #
2 # Copyright (C) 2012, Carlos Jenkins <carlos@jenkins.co.cr>
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17 """
18 Uncompress, read and install LibreOffice .oxt dictionaries extensions.
19
20 This module extracts the .dic and .aff (Hunspell) dictionaries from all the
21 .oxt extensions found on some directory.
22
23 Extensions like the ones found here:
24
25 http://extensions.services.openoffice.org/dictionary
26 """
27
28 import os
29 import xml.dom.minidom
30 import shutil
31 import logging
32 import gettext
33 from zipfile import ZipFile, BadZipfile
34
35 # Expose
36 __all__ = ['deflate_oxt']
37
38 logger = logging.getLogger(__name__)
39 _ = gettext.translation('pygtkspellcheck', fallback=True).gettext
40
41 def deflate_oxt(oxt_path, extract_path, override=False, move_path=None):
42 """
43 Uncompress, read and install LibreOffice ``.oxt`` dictionaries extensions.
44
45 :param oxt_path: path to a directory containing the ``.oxt`` extensions.
46 :param extract_path: path to extract Hunspell dictionaries files.
47 :param override: override files.
48 :param move_path: Optional path to move the ``.oxt`` files after processing.
49 :rtype: None
50
51 This function extracts the Hunspell dictionaries (``.dic`` and ``.aff``
52 files) from all the ``.oxt`` extensions found on ``oxt_path`` directory to
53 the ``extract_path`` directory.
54
55 Extensions like the ones found here:
56
57 http://extensions.services.openoffice.org/dictionary
58
59 In detail, this functions does the following:
60
61 1. Find all the ``.oxt`` extension files within ``oxt_path``
62 2. Open (unzip) each extension.
63 3. Find the dictionary definition file within (*dictionaries.xcu*)
64 4. Parse the dictionary definition file and locate the dictionaries files.
65 5. Uncompress those files to ``extract_path``.
66
67 By default file overriding is disabled, set ``override`` parameter to True
68 if you want to enable it. As and additional option, each processed extension
69 can be moved to ``move_path``.
70 """
71
72 # Get the real, absolute and normalized path
73 oxt_path = os.path.normpath(os.path.abspath(os.path.realpath(oxt_path)))
74
75 # Check that the input directory exists
76 if not os.path.isdir(oxt_path):
77 return
78
79 # Create extract directory if not exists
80 if not os.path.exists(extract_path):
81 os.makedirs(extract_path)
82
83 # Check that the extract path is a directory
84 if not os.path.isdir(extract_path):
85 logger.error(_('Extract path is not a directory.'))
86 return
87
88 # Get all .oxt extension at given path
89 oxt_files = [extension for extension in os.listdir(oxt_path) if extension.lower().endswith('.oxt')]
90
91 for extension_name in oxt_files:
92
93 extension_path = os.path.join(oxt_path, extension_name)
94
95 try:
96 with ZipFile(extension_path, 'r') as extension_file:
97
98 # List of files within the extension file
99 files_within = extension_file.namelist()
100
101 # Find the dictionaries registry
102 registry = 'dictionaries.xcu'
103 if not registry in files_within:
104 for file_path in files_within:
105 if file_path.lower().endswith(registry):
106 registry = file_path
107
108 if registry in files_within:
109 try:
110 # Find within the registry the entry for dictionaries
111 registry_content = extension_file.read(registry)
112 dom = xml.dom.minidom.parseString(registry_content)
113 dic_locations = _find_dictionaries_location(dom)
114
115 if dic_locations:
116 for dic_location in dic_locations:
117
118 # Get the list of files considered dictionaries for current entry
119 dic_location = dic_location.replace('%origin%', os.path.dirname(registry))
120 dic_files = []
121 for dic_file in dic_location.split(' '):
122 if dic_file.startswith('/'):
123 dic_file = dic_file[1:]
124 dic_files.append(os.path.normpath(dic_file))
125
126 # Extract files if they exists within the extension file
127 for dic_file in dic_files:
128 if dic_file in files_within:
129 target = os.path.join(extract_path, os.path.basename(dic_file))
130 # Extract only if we are overriding or file doesn't exists
131 if (override and os.path.isfile(target)) or (not os.path.exists(target)):
132 # Extract a single file without caring about folder structure
133 with extension_file.open(dic_file) as source:
134 with file(target, 'wb') as destination:
135 shutil.copyfileobj(source, destination)
136 else:
137 logger.warning(_('\'{0}\' declared in registry but not found within the extension.').format(dic_file))
138
139 except Exception as inst:
140 logger.exception(_('Error while processing extension {0}.').format(extension_name))
141 pass
142 else:
143 logger.error(_('Extension \'{0}\' has no dictionary registry.').format(extension_name))
144 except BadZipfile:
145 logger.error(_('Extension \'{0}\' is not a valid zip file.').format(extension_name))
146
147
148 # Move the extension after processing if user requires it
149 if move_path is not None:
150 # Create move path if it doesn't exists
151 if not os.path.exists(move_path):
152 os.makedirs(move_path)
153 # Move to the given path only if it is a directory and target doesn't exists
154 if os.path.isdir(move_path):
155 if not os.path.exists(os.path.join(move_path, extension_name)) or override:
156 #print('Move from ', extension_path, ' to ', move_path)
157 shutil.move(extension_path, move_path)
158 else:
159 logger.warning(_('Unable to move extension, file with same name exists within move_path.'))
160 else:
161 logger.warning(_('Unable to move extension, move_path is not a directory.'))
162
163
164 def _find_dictionaries_location(dom):
165 """Find the location of the dictionaries files in the extension XML registry"""
166
167 def _is_text_node(element):
168 return element.firstChild.nodeType == xml.dom.Node.TEXT_NODE
169
170 result = []
171
172 root = dom.getElementsByTagName('oor:component-data')[0]
173
174 for value in root.getElementsByTagName('value'):
175 if _is_text_node(value) and value.firstChild.data == 'DICT_SPELL':
176 dict_node = value.parentNode.parentNode
177 for prop in dict_node.getElementsByTagName('prop'):
178 if prop.hasAttribute('oor:name') and prop.getAttribute('oor:name') == 'Locations':
179 dict_value = prop.getElementsByTagName('value')[0]
180 # <value>%origin%/es_CR.aff %origin%/es_CR.dic</value>
181 if _is_text_node(dict_value):
182 result.append(dict_value.firstChild.data)
183 # <value><it>%origin%/es_CR.aff</it><it>%origin%/es_CR.dic</it></value>
184 else:
185 for item in dict_value.getElementsByTagName('it'):
186 result.append(item.firstChild.data)
187 break
188 return result
189
0 # -*- coding:utf-8 -*-
1 #
2 # Copyright (C) 2012, Maximilian Köhl <linuxmaxi@googlemail.com>
3 # Copyright (C) 2012, Carlos Jenkins <carlos@jenkins.co.cr>
4 #
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
17
18 """
19 A spellchecking library written in pure Python for Gtk based on Enchant. It
20 supports both Gtk's Python bindings, PyGObject and PyGtk, and for both Python 2
21 and 3 with automatic switching and binding autodetection. For automatic
22 translation of the user interface it can use GEdit's translation files.
23 """
24
25 import enchant
26 import gettext
27 import logging
28 import re
29 import sys
30
31 from pylocales import code_to_name
32
33 # Public Objects
34 __all__ = ['SpellChecker']
35
36 # Logger
37 logger = logging.getLogger(__name__)
38
39 # Find which Gtk binding to use based on client's binding
40 if 'gi.repository.Gtk' in sys.modules:
41 gtk = sys.modules['gi.repository.Gtk']
42 _pygobject = True
43 elif 'gtk' in sys.modules:
44 gtk = sys.modules['gtk']
45 _pygobject = False
46 else:
47 logger.error('No Gtk module found. Spellcheck will be unusable.')
48
49 # Select base list class for Python3/2
50 try:
51 from collections import UserList
52 _list = UserList
53 except ImportError:
54 _list = list
55
56 # Select basestring for Python2/3
57 if sys.version_info.major == 3:
58 basestring = str
59
60 # Map between Gedit's translation and PyGtkSpellcheck's own
61 _GEDIT_MAP = {'Languages' : 'Languages',
62 'Ignore All' : 'Ignore _All',
63 'Suggestions' : 'Suggestions',
64 '(no suggestions)' : '(no suggested words)',
65 'Add "{word}" to Dictionary' : 'Add w_ord'}
66
67 # Translation
68 if gettext.find('gedit'):
69 _gedit = gettext.translation('gedit', fallback=True).gettext
70 _ = lambda message: _gedit(_GEDIT_MAP[message]).replace('_', '')
71 else:
72 _ = gettext.translation('pygtkspellcheck', fallback=True).gettext
73
74 class SpellChecker(object):
75 """
76 Main spellchecking class, everything important happens here.
77
78 :param view: GtkTextView the SpellChecker should be attached to.
79 :param language: the language which should be used for spellchecking.
80 Use a combination of two letter lower-case ISO 639 language code with a
81 two letter upper-case ISO 3166 country code, for example en_US or de_DE.
82 :param prefix: a prefix for some internal GtkTextMarks.
83 :param collapse: enclose suggestions in its own menu.
84 :param params: dictionary with Enchant broker parameters that should be set
85 e.g. `enchant.myspell.dictionary.path`.
86
87 .. attribute:: languages
88
89 A list of supported languages.
90
91 .. function:: exists(language)
92
93 checks if a language exists
94
95 :param language: language to check
96 """
97 FILTER_WORD = 'word'
98 FILTER_LINE = 'line'
99 FILTER_TEXT = 'text'
100
101 DEFAULT_FILTERS = {FILTER_WORD : [r'[0-9.,]+'],
102 FILTER_LINE : [r'(https?|ftp|file):((//)|(\\\\))+[\w\d:#@%/;$()~_?+-=\\.&]+',
103 r'[\w\d]+@[\w\d.]+'],
104 FILTER_TEXT : []}
105
106 class _LanguageList(_list):
107 def __init__(self, *args, **kwargs):
108 if sys.version_info.major == 3:
109 super().__init__(*args, **kwargs)
110 else:
111 _list.__init__(self, *args, **kwargs)
112 self.mapping = dict(self)
113
114 @classmethod
115 def from_broker(cls, broker):
116 return cls(sorted([(language, code_to_name(language))
117 for language in broker.list_languages()],
118 key=lambda language: language[1]))
119
120 def exists(self, language):
121 return language in self.mapping
122
123 class _Mark():
124 def __init__(self, buffer, name, start):
125 self._buffer = buffer
126 self._name = name
127 self._mark = self._buffer.create_mark(self._name, start, True)
128
129 @property
130 def iter(self):
131 return self._buffer.get_iter_at_mark(self._mark)
132
133 @property
134 def inside_word(self):
135 return self.iter.inside_word()
136
137 @property
138 def word(self):
139 start = self.iter
140 if not start.starts_word():
141 start.backward_word_start()
142 end = self.iter
143 if end.inside_word():
144 end.forward_word_end()
145 return start, end
146
147 def move(self, location):
148 self._buffer.move_mark(self._mark, location)
149
150 def __init__(self, view, language='en', prefix='gtkspellchecker', collapse=True, params={}):
151 self._view = view
152 self.collapse = collapse
153 self._view.connect('populate-popup', lambda entry, menu: self._extend_menu(menu))
154 self._view.connect('popup-menu', self._click_move_popup)
155 self._view.connect('button-press-event', self._click_move_button)
156 self._prefix = prefix
157 if _pygobject:
158 self._misspelled = gtk.TextTag.new('{prefix}-misspelled'.format(prefix=self._prefix))
159 else:
160 self._misspelled = gtk.TextTag('{prefix}-misspelled'.format(prefix=self._prefix))
161 self._misspelled.set_property('underline', 4)
162 self._broker = enchant.Broker()
163 for param, value in params: self._broker.set_param(param, value)
164 self.languages = SpellChecker._LanguageList.from_broker(self._broker)
165 self._language = language if self.languages.exists(language) else 'en'
166 self._dictionary = self._broker.request_dict(language)
167 self._deferred_check = False
168 self._filters = dict(SpellChecker.DEFAULT_FILTERS)
169 self._regexes = {SpellChecker.FILTER_WORD : re.compile('|'.join(self._filters[SpellChecker.FILTER_WORD])),
170 SpellChecker.FILTER_LINE : re.compile('|'.join(self._filters[SpellChecker.FILTER_LINE])),
171 SpellChecker.FILTER_TEXT : re.compile('|'.join(self._filters[SpellChecker.FILTER_TEXT]), re.MULTILINE)}
172 self._enabled = True
173 self.buffer_initialize()
174
175 @property
176 def language(self):
177 """
178 The language used for spellchecking
179 """
180 return self._language
181
182 @language.setter
183 def language(self, language):
184 if language != self._language and self.languages.exists(language):
185 self._language = language
186 self._dictionary = self._broker.request_dict(language)
187 self.recheck()
188
189 @property
190 def enabled(self):
191 """
192 Enable or disable spellchecking
193 """
194 return self._enabled
195
196 @enabled.setter
197 def enabled(self, enabled):
198 if enabled and not self._enabled:
199 self.enable()
200 elif not enabled and self._enabled:
201 self.disable()
202
203 def buffer_initialize(self):
204 """
205 Initialize the GtkTextBuffer associated with the GtkTextView.
206 If you associate a new GtkTextBuffer with the GtkTextView call this method.
207 """
208 self._buffer = self._view.get_buffer()
209 self._buffer.connect('insert-text', self._before_text_insert)
210 self._buffer.connect_after('insert-text', self._after_text_insert)
211 self._buffer.connect_after('delete-range', self._range_delete)
212 self._buffer.connect_after('mark-set', self._mark_set)
213 start = self._buffer.get_bounds()[0]
214 self._marks = {'insert-start' : SpellChecker._Mark(self._buffer, '{prefix}-insert-start'.format(prefix=self._prefix), start),
215 'insert-end' : SpellChecker._Mark(self._buffer, '{prefix}-insert-end'.format(prefix=self._prefix), start),
216 'click' : SpellChecker._Mark(self._buffer, '{prefix}-click'.format(prefix=self._prefix), start)}
217 self._table = self._buffer.get_tag_table()
218 self._table.add(self._misspelled)
219 self.ignored_tags = []
220 def tag_added(tag, *args):
221 if hasattr(tag, 'spell_check') and not getattr(tag, 'spell_check'):
222 self.ignored_tags.append(tag)
223 def tag_removed(tag, *args):
224 if tag in self.ignored_tags:
225 self.ignored_tags.remove(tag)
226 self._table.connect('tag-added', tag_added)
227 self._table.connect('tag-removed', tag_removed)
228 self._table.foreach(tag_added, None)
229 self.no_spell_check = self._table.lookup('no-spell-check')
230 if not self.no_spell_check:
231 if _pygobject:
232 self.no_spell_check = gtk.TextTag.new('no-spell-check')
233 else:
234 self.no_spell_check = gtk.TextTag('no-spell-check')
235 self._table.add(self.no_spell_check)
236 self.recheck()
237
238 def recheck(self):
239 """
240 Rechecks the spelling of the whole text.
241 """
242 start, end = self._buffer.get_bounds()
243 self.check_range(start, end, True)
244
245 def disable(self):
246 """
247 Disable spellchecking.
248 """
249 self._enabled = False
250 start, end = self._buffer.get_bounds()
251 self._buffer.remove_tag(self._misspelled, start, end)
252
253 def enable(self):
254 """
255 Enable spellchecking.
256 """
257 self._enabled = True
258 self.recheck()
259
260 def append_filter(self, regex, filter_type):
261 """
262 Append a new filter to the filter list.
263 Filters are useful to ignore some misspelled words based on regular expressions.
264
265 :param regex: the regex used for filtering
266 :param filter_type: the type of the filter
267
268 Filter Types:
269
270 :const:`SpellChecker.FILTER_WORD`: The regex must match the whole word you want to filter.
271 The word separation is done by Pango's word separation algorythm so, for example, urls won't work here because they are split in many words.
272
273 :const:`SpellChecker.FILTER_LINE`: If the expression you want to match is a single line expression use this type.
274 It should not be an open end expression because then the rest of the line with the text you want to filter will become correct.
275
276 :const:`SpellChecker.FILTER_TEXT`: Use this if you want to filter multiline expressions.
277 The regex will be compiled with the `MULTILINE` flag.
278 Same with open end expressions apply here.
279 """
280 self._filters[filter_type].append(regex)
281 if filter_type == SpellChecker.FILTER_TEXT:
282 self._regexes[filter_type] = re.compile('|'.join(self._filters[filter_type]), re.MULTILINE)
283 else:
284 self._regexes[filter_type] = re.compile('|'.join(self._filters[filter_type]))
285
286 def remove_filter(self, regex, filter_type):
287 """
288 Remove a filter from the filter list.
289
290 :param regex: the regex which used for filtering
291 :param filter_type: the type of the filter
292 """
293 self._filters[filter_type].remove(regex)
294 if filter_type == SpellChecker.FILTER_TEXT:
295 self._regexes[filter_type] = re.compile('|'.join(self._filters[filter_type]), re.MULTILINE)
296 else:
297 self._regexes[filter_type] = re.compile('|'.join(self._filters[filter_type]))
298
299 def append_ignore_tag(self, tag):
300 """
301 Appends a tag to the list of ignored tags.
302 A string will be automatic resolved into a tag object.
303
304 :param tag: tag object or tag name
305 """
306 if isinstance(tag, basestring):
307 tag = self._table.lookup(tag)
308 self.ignored_tags.append(tag)
309
310 def remove_ignore_tag(self, tag):
311 """
312 Removes a tag from the list of ignored tags.
313 A string will be automatic resolved into a tag object.
314
315 :param tag: tag object or tag name
316 """
317 if isinstance(tag, basestring):
318 tag = self._table.lookup(tag)
319 self.ignored_tags.remove(tag)
320
321 def add_to_dictionary(self, word):
322 """
323 Adds a word to user's dictionary.
324
325 :param word: the word to add
326 """
327 self._dictionary.add_to_pwl(word)
328 self.recheck()
329
330 def ignore_all(self, word):
331 """
332 Ignores a word for the current session.
333
334 :param word: the word to ignore
335 """
336 self._dictionary.add_to_session(word)
337 self.recheck()
338
339 def check_range(self, start, end, force_all=False):
340 """
341 Checks a specified range between two GtkTextIters.
342
343 :param start: start iter - checking starts here
344 :param end: end iter - checking ends here
345 """
346 if not self._enabled:
347 return
348 if end.inside_word(): end.forward_word_end()
349 if not start.starts_word() and (start.inside_word() or start.ends_word()): start.backward_word_start()
350 self._buffer.remove_tag(self._misspelled, start, end)
351 cursor = self._buffer.get_iter_at_mark(self._buffer.get_insert())
352 precursor = cursor.copy()
353 precursor.backward_char()
354 highlight = cursor.has_tag(self._misspelled) or precursor.has_tag(self._misspelled)
355 if not start.get_offset():
356 start.forward_word_end()
357 start.backward_word_start()
358 word_start = start.copy()
359 while word_start.compare(end) < 0:
360 word_end = word_start.copy()
361 word_end.forward_word_end()
362 in_word = (word_start.compare(cursor) < 0) and (cursor.compare(word_end) <= 0)
363 if in_word and not force_all:
364 if highlight:
365 self._check_word(word_start, word_end)
366 else:
367 self._deferred_check = True
368 else:
369 self._check_word(word_start, word_end)
370 self._deferred_check = False
371 word_end.forward_word_end()
372 word_end.backward_word_start()
373 if word_start.equal(word_end):
374 break
375 word_start = word_end.copy()
376
377 def _languages_menu(self):
378 def _set_language(item, code):
379 self.language = code
380 if _pygobject:
381 menu = gtk.Menu.new()
382 group = []
383 else:
384 menu = gtk.Menu()
385 group = gtk.RadioMenuItem()
386 connect = []
387 for code, name in self.languages:
388 if _pygobject:
389 item = gtk.RadioMenuItem.new_with_label(group, name)
390 group.append(item)
391 else:
392 item = gtk.RadioMenuItem(group, name)
393 if code == self.language:
394 item.set_active(True)
395 connect.append((item, code))
396 menu.append(item)
397 for item, code in connect:
398 item.connect('activate', _set_language, code)
399 return menu
400
401 def _suggestion_menu(self, word):
402 menu = []
403 suggestions = self._dictionary.suggest(word)
404 if not suggestions:
405 if _pygobject:
406 item = gtk.MenuItem.new()
407 label = gtk.Label.new('')
408 else:
409 item = gtk.MenuItem()
410 label = gtk.Label()
411 try:
412 label.set_halign(gtk.Align.LEFT)
413 except AttributeError:
414 label.set_alignment(0.0, 0.5)
415 label.set_markup('<i>{text}</i>'.format(text=_('(no suggestions)')))
416 item.add(label)
417 menu.append(item)
418 else:
419 for suggestion in suggestions:
420 if _pygobject:
421 item = gtk.MenuItem.new()
422 label = gtk.Label.new('')
423 else:
424 item = gtk.MenuItem()
425 label = gtk.Label()
426 label.set_markup('<b>{text}</b>'.format(text=suggestion))
427 try:
428 label.set_halign(gtk.Align.LEFT)
429 except AttributeError:
430 label.set_alignment(0.0, 0.5)
431 item.add(label)
432 item.connect('activate', self._replace_word, word, suggestion)
433 menu.append(item)
434 if _pygobject:
435 menu.append(gtk.SeparatorMenuItem.new())
436 item = gtk.MenuItem.new_with_label(_('Add "{word}" to Dictionary').format(word=word))
437 else:
438 menu.append(gtk.SeparatorMenuItem())
439 item = gtk.MenuItem(_('Add "{word}" to Dictionary').format(word=word))
440 item.connect('activate', lambda *args: self.add_to_dictionary(word))
441 menu.append(item)
442 if _pygobject:
443 item = gtk.MenuItem.new_with_label(_('Ignore All'))
444 else:
445 item = gtk.MenuItem(_('Ignore All'))
446 item.connect('activate', lambda *args: self.ignore_all(word))
447 menu.append(item)
448 return menu
449
450 def _extend_menu(self, menu):
451 if not self._enabled:
452 return
453 if _pygobject:
454 separator = gtk.SeparatorMenuItem.new()
455 else:
456 separator = gtk.SeparatorMenuItem()
457 separator.show()
458 menu.prepend(separator)
459 if _pygobject:
460 languages = gtk.MenuItem.new_with_label(_('Languages'))
461 else:
462 languages = gtk.MenuItem(_('Languages'))
463 languages.set_submenu(self._languages_menu())
464 languages.show_all()
465 menu.prepend(languages)
466 if self._marks['click'].inside_word:
467 start, end = self._marks['click'].word
468 if start.has_tag(self._misspelled):
469 word = self._buffer.get_text(start, end, False)
470 submenu_items = self._suggestion_menu(word)
471 if self.collapse:
472 if _pygobject:
473 suggestions = gtk.MenuItem.new_with_label(_('Suggestions'))
474 submenu = gtk.Menu.new()
475 else:
476 suggestions = gtk.MenuItem(_('Suggestions'))
477 submenu = gtk.Menu()
478 for i in submenu_items:
479 submenu.append(i)
480 suggestions.set_submenu(submenu)
481 suggestions.show_all()
482 menu.prepend(suggestions)
483 else:
484 submenu_items.reverse()
485 for i in submenu_items:
486 menu.prepend(i)
487 menu.show_all()
488
489 def _click_move_popup(self, *args):
490 self._marks['click'].move(self._buffer.get_iter_at_mark(self._buffer.get_insert()))
491 return False
492
493 def _click_move_button(self, widget, event):
494 if event.button == 3:
495 if self._deferred_check: self._check_deferred_range(True)
496 x, y = self._view.window_to_buffer_coords(2, int(event.x), int(event.y))
497 self._marks['click'].move(self._view.get_iter_at_location(x, y))
498 return False
499
500 def _before_text_insert(self, textbuffer, location, text, length):
501 self._marks['insert-start'].move(location)
502
503 def _after_text_insert(self, textbuffer, location, text, length):
504 start = self._marks['insert-start'].iter
505 self.check_range(start, location)
506 self._marks['insert-end'].move(location)
507
508 def _range_delete(self, textbuffer, start, end):
509 self.check_range(start, end)
510
511 def _mark_set(self, textbuffer, location, mark):
512 if mark == self._buffer.get_insert() and self._deferred_check:
513 self._check_deferred_range(False)
514
515 def _replace_word(self, item, old_word, new_word):
516 start, end = self._marks['click'].word
517 offset = start.get_offset()
518 self._buffer.begin_user_action()
519 self._buffer.delete(start, end)
520 self._buffer.insert(self._buffer.get_iter_at_offset(offset), new_word)
521 self._buffer.end_user_action()
522 self._dictionary.store_replacement(old_word, new_word)
523
524 def _check_deferred_range(self, force_all):
525 start = self._marks['insert-start'].iter
526 end = self._marks['insert-end'].iter
527 self.check_range(start, end, force_all)
528
529 def _check_word(self, start, end):
530 if start.has_tag(self.no_spell_check):
531 return
532 for tag in self.ignored_tags:
533 if start.has_tag(tag):
534 return
535 word = self._buffer.get_text(start, end, False).strip()
536 if len(self._filters[SpellChecker.FILTER_WORD]):
537 if self._regexes[SpellChecker.FILTER_WORD].match(word):
538 return
539 if len(self._filters[SpellChecker.FILTER_LINE]):
540 line_start = self._buffer.get_iter_at_line(start.get_line())
541 line_end = end.copy()
542 line_end.forward_to_line_end()
543 line = self._buffer.get_text(line_start, line_end, False)
544 for match in self._regexes[SpellChecker.FILTER_LINE].finditer(line):
545 if match.start() <= start.get_line_offset() <= match.end():
546 start = self._buffer.get_iter_at_line_offset(start.get_line(), match.start())
547 end = self._buffer.get_iter_at_line_offset(start.get_line(), match.end())
548 self._buffer.remove_tag(self._misspelled, start, end)
549 return
550 if len(self._filters[SpellChecker.FILTER_TEXT]):
551 text_start, text_end = self._buffer.get_bounds()
552 text = self._buffer.get_text(text_start, text_end, False)
553 for match in self._regexes[SpellChecker.FILTER_TEXT].finditer(text):
554 if match.start() <= start.get_offset() <= match.end():
555 start = self._buffer.get_iter_at_offset(match.start())
556 end = self._buffer.get_iter_at_offset(match.end())
557 self._buffer.remove_tag(self._misspelled, start, end)
558 return
559 if not self._dictionary.check(word):
560 self._buffer.apply_tag(self._misspelled, start, end)
0 # -*- coding:utf-8 -*-
1 #
2 # Copyright (C) 2012, Maximilian Köhl <linuxmaxi@googlemail.com>
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17 # Python 2/3 unicode
18 import sys
19 if sys.version_info.major == 3:
20 u = lambda x: x
21 else:
22 u = lambda x: x.decode('utf-8')
23
24 # Metadata
25 __version__ = '1.1'
26 __project__ = 'PyLocales'
27 __short_name__ = 'pylocales'
28 __authors__ = u('Maximilian Köhl & Carlos Jenkins')
29 __emails__ = u('linuxmaxi@googlemail.com & carlos@jenkins.co.cr')
30 __website__ = 'http://pygtkspellcheck.readthedocs.org/'
31 __source__ = 'https://github.com/koehlma/pygtkspellcheck/'
32 __vcs__ = 'git://github.com/koehlma/pygtkspellcheck.git'
33 __copyright__ = u('2012, Maximilian Köhl & Carlos Jenkins')
34 __desc_short__ = 'Query the ISO 639/3166 database about a country or a language.'
35 __desc_long__ = ('Query the ISO 639/3166 database about a country or a'
36 'language. The locales database contains ISO 639 languages'
37 'definitions and ISO 3166 countries definitions. This package'
38 'provides translation for countries and languages names if'
39 'iso-codes package is installed (Ubuntu/Debian).')
40
41 __metadata__ = {'__version__' : __version__,
42 '__project__' : __project__,
43 '__short_name__' : __short_name__,
44 '__authors__' : __authors__,
45 '__emails__' : __emails__,
46 '__website__' : __website__,
47 '__source__' : __source__,
48 '__vcs__' : __vcs__,
49 '__copyright__' : __copyright__,
50 '__desc_short__' : __desc_short__,
51 '__desc_long__' : __desc_long__}
52
53 # Should only import Public Objects
54 from pylocales.locales import *
Binary diff not shown
0 # -*- coding:utf-8 -*-
1 #
2 # Copyright (C) 2012, Maximilian Köhl <linuxmaxi@googlemail.com>
3 # Copyright (C) 2012, Carlos Jenkins <carlos@jenkins.co.cr>
4 #
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
17
18 """
19 Query the ISO 639/3166 database about a country or a language. The locales
20 database contains ISO 639 languages definitions and ISO 3166 countries
21 definitions. This package provides translation for countries and languages names
22 if iso-codes package is installed (Ubuntu/Debian).
23
24 @see utils/locales/build.py to know the database tables and structure.
25 """
26
27 import gettext
28 import logging
29 import os
30 import sqlite3
31
32 # Public Objects
33 __all__ = ['Country', 'Language', 'LanguageNotFound',
34 'CountryNotFound', 'code_to_name']
35
36 # Translation
37 _translator_language = gettext.translation('iso_639', fallback=True).gettext
38 _translator_country = gettext.translation('iso_3166', fallback=True).gettext
39
40 # Decides where the database is located. If an application provides an
41 # os.path.get_module_path monkey patch to determine the path where the module
42 # is located it uses this. If not it searches in the directory of this source
43 # code file.
44 __path__ = None
45 if hasattr(os.path, 'get_module_path'):
46 __path__ = os.path.get_module_path(__file__)
47 if not os.path.isfile(os.path.join(__path__, 'locales.db')):
48 __path__ = None
49 if __path__ is None:
50 __path__ = os.path.abspath(os.path.realpath(os.path.dirname(__file__)))
51
52 # Loading the Database
53 _database = sqlite3.connect(os.path.join(__path__, 'locales.db'))
54
55 logger = logging.getLogger(__name__)
56
57 # Exceptions
58 class LanguageNotFound(Exception):
59 """
60 The specified language wasn't found in the database.
61 """
62
63 class CountryNotFound(Exception):
64 """
65 The specified country wasn't found in the database.
66 """
67
68 class Country(object):
69 def __init__(self, rowid):
70 country = _database.execute('SELECT * FROM countries WHERE rowid == ?', (rowid,)).fetchone()
71 self.name = country[0]
72 self.official_name = country[1]
73 self.alpha_2 = country[2]
74 self.alpha_3 = country[3]
75 self.numeric = country[4]
76 self.translation = _translator_country(self.name)
77
78 @classmethod
79 def get_country(cls, code, codec):
80 country = _database.execute('SELECT rowid FROM countries WHERE %s == ?' % (codec), (code,)).fetchone()
81 if country:
82 return cls(country[0])
83 raise CountryNotFound('code: %s, codec: %s' % (code, codec))
84
85 @classmethod
86 def by_alpha_2(cls, code):
87 return Country.get_country(code, 'alpha_2')
88
89 @classmethod
90 def by_alpha_3(cls, code):
91 return Country.get_country(code, 'alpha_3')
92
93 @classmethod
94 def by_numeric(cls, code):
95 return Country.get_country(code, 'numeric')
96
97 class Language(object):
98 def __init__(self, rowid):
99 language = _database.execute('SELECT * FROM languages WHERE rowid == ?', (rowid,)).fetchone()
100 self.name = language[0]
101 self.iso_639_2B = language[1]
102 self.iso_639_2T = language[2]
103 self.iso_639_1 = language[3]
104 self.translation = _translator_language(self.name)
105
106 @classmethod
107 def get_language(cls, code, codec):
108 language = _database.execute('SELECT rowid FROM languages WHERE %s == ?' % (codec), (code,)).fetchone()
109 if language:
110 return cls(language[0])
111 raise LanguageNotFound('code: %s, codec: %s' % (code, codec))
112
113 @classmethod
114 def by_iso_639_2B(cls, code):
115 return Language.get_language(code, 'iso_639_2B')
116
117 @classmethod
118 def by_iso_639_2T(cls, code):
119 return Language.get_language(code, 'iso_639_2T')
120
121 @classmethod
122 def by_iso_639_1(cls, code):
123 return Language.get_language(code, 'iso_639_1')
124
125
126 def code_to_name(code, separator='_'):
127 """
128 Get the natural name of a language based on it's code.
129 """
130 logger.debug('requesting name for code "{}"'.format(code))
131 code = code.split(separator)
132 if len(code) > 1:
133 lang = Language.by_iso_639_1(code[0]).translation
134 country = Country.by_alpha_2(code[1]).translation
135 return '{lang} ({country})'.format(lang=lang, country=country)
136 else:
137 return Language.by_iso_639_1(code[0]).translation