├── .github
└── workflows
│ └── pipeline.yml
├── .gitignore
├── .readthedocs.yml
├── .vscode
└── settings.json
├── CHANGELOG
├── LICENSE
├── README.md
├── docs
├── Makefile
├── index.rst
├── insert_metadata.py
├── make.bat
├── metadata
│ ├── documentation.rst
│ ├── metadata.py
│ ├── pypi.rst
│ ├── readme.md
│ ├── screenshot.png
│ └── website.md
├── pypi
│ ├── index.html
│ └── page.rst
├── screenshots
│ └── screenshot.png
└── source
│ ├── conf.py
│ └── index.md
├── examples
├── collapsed_gtk3.py
├── collapsed_gtk4.py
├── expanded_gtk3.py
└── expanded_gtk4.py
├── locale
├── de
│ ├── pygtkspellcheck.mo
│ └── pygtkspellcheck.po
├── en
│ ├── pygtkspellcheck.mo
│ └── pygtkspellcheck.po
├── es
│ ├── pygtkspellcheck.mo
│ └── pygtkspellcheck.po
└── nl
│ ├── pygtkspellcheck.mo
│ └── pygtkspellcheck.po
├── placeholders
├── README.md
├── gtkspellcheck
│ ├── README.md
│ ├── gtkspellcheck
│ │ └── __init__.py
│ └── pyproject.toml
└── pylocales
│ ├── README.md
│ ├── pylocales
│ └── __init__.py
│ └── pyproject.toml
├── poetry.toml
├── pyproject.toml
├── setup.cfg
├── src
└── gtkspellcheck
│ ├── __init__.py
│ ├── _oxt_extract.py
│ ├── _pylocales
│ ├── __init__.py
│ ├── locales.db
│ └── locales.py
│ └── spellcheck.py
└── utils
├── locales
├── build.py
└── databases
│ ├── iso3166.xml
│ └── iso639.xml
└── oxt_extract_dictionaries.py
/.github/workflows/pipeline.yml:
--------------------------------------------------------------------------------
1 | name: Pipeline
2 |
3 | on: [push, pull_request, workflow_dispatch]
4 |
5 | jobs:
6 | lint_black:
7 | name: Lint (black)
8 | runs-on: ubuntu-latest
9 | steps:
10 | - uses: actions/checkout@v2
11 | - name: Set up Python 3.8
12 | uses: actions/setup-python@v2
13 | with:
14 | python-version: 3.8
15 | - name: Install Black
16 | run: |
17 | pip install black
18 | - name: Run Black
19 | run: |
20 | black --check --diff .
21 |
22 | lint_flake8:
23 | name: Lint (flake8)
24 | runs-on: ubuntu-latest
25 | steps:
26 | - uses: actions/checkout@v2
27 | - name: Set up Python 3.8
28 | uses: actions/setup-python@v2
29 | with:
30 | python-version: 3.8
31 | - name: Install Flake8
32 | run: |
33 | pip install flake8 flake8-bugbear pep8-naming
34 | - name: Run Flake8
35 | run: |
36 | flake8 src/gtkspellcheck
37 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | doc/build/
2 | l10n/mo
3 | build/
4 | MANIFEST
5 |
6 | # Python
7 | *.pyc
8 | dist
9 | __pycache__
10 |
11 | # IDE
12 | .project
13 | .pydevproject
14 | .settings
15 | .directory
16 | .idea
17 |
18 | # Virtual Environment
19 | .venv
20 |
21 | # Poetry Lock (This is a library. Hence, versions should not be pinned.)
22 | poetry.lock
23 |
24 | # Debian
25 | dist/*.tar.gz
26 | dist/debian/build
27 | dist/debian/*.deb
28 |
29 | # Archlinux
30 | dist/archlinux/python2/pkg
31 | dist/archlinux/python2/src
32 | dist/archlinux/python2/v*
33 | dist/archlinux/python2/*.pkg.tar.xz
34 | dist/archlinux/python2/*.src.tar.gz
35 |
36 | dist/archlinux/python3/pkg
37 | dist/archlinux/python3/src
38 | dist/archlinux/python3/v*
39 | dist/archlinux/python3/*.pkg.tar.xz
40 | dist/archlinux/python3/*.src.tar.gz
41 |
--------------------------------------------------------------------------------
/.readthedocs.yml:
--------------------------------------------------------------------------------
1 | version: 2
2 |
3 | build:
4 | os: ubuntu-20.04
5 | tools:
6 | python: "3.9"
7 | apt_packages:
8 | - libgirepository1.0-dev
9 |
10 | sphinx:
11 | builder: html
12 | configuration: docs/source/conf.py
13 |
14 | python:
15 | install:
16 | - method: pip
17 | path: .
18 | extra_requirements:
19 | - docs
20 |
21 |
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "python.formatting.provider": "black",
3 | "cSpell.words": [
4 | "maintainership"
5 | ]
6 | }
--------------------------------------------------------------------------------
/CHANGELOG:
--------------------------------------------------------------------------------
1 | == 4.0.5 ==
2 | - add support for PyInstaller (issue #30)
3 | - deprecate oxt_extract and pylocales functionality
4 |
5 | == 4.0 ==
6 | - caused by: API incompatible changes in `oxt_extract`
7 | - SpellChecker API remains compatible to version 3
8 |
9 | == 5.0 ==
10 | - removed `oxt_extract` and `pylocales` API
11 | - removed support for Python 2 and GTK 2
12 | - add support for GTK 4
13 | - add support for extra word characters
14 | - add support for batch rechecking of large buffers
15 |
16 | == 5.0.1 ==
17 | - minor bug fixes
18 |
19 | == 5.0.2 ==
20 | - feature: add `move_click_mark` and `populate_menu` to public API
21 |
22 | == 5.0.3 ==
23 | - fix: fix issue with Gedit based translation
24 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Python GTK Spellcheck
2 |
3 | [](https://pypi.python.org/pypi/pygtkspellcheck)
4 | [](https://pygtkspellcheck.readthedocs.org/en/latest/)
5 |
6 | Python GTK Spellcheck is a simple but quite powerful spellchecking library for GTK written in pure Python. It's spellchecking component is based on [Enchant](http://www.abisource.com/projects/enchant/) and it supports both GTK 3 and 4 via [PyGObject](https://live.gnome.org/PyGObject/).
7 |
8 | **⚡️ News:** Thanks to [@cheywood](https://github.com/cheywood), Python GTK Spellcheck now supports GTK 4! 🎉
9 |
10 | **🟢 Status:** This project is mature, actively maintained, and open to contributions and co-maintainership.
11 |
12 |
13 | ## ✨ Features
14 |
15 | - **spellchecking** based on [Enchant](http://www.abisource.com/projects/enchant/) for `GtkTextView`
16 | - support for word, line, and multiline **ignore regular expressions**
17 | - support for both **GTK 3 and 4** via [PyGObject](https://live.gnome.org/PyGObject/) for Python 3
18 | - configurable extra word characters such as `'`
19 | - localized names of the available languages based on [ISO-Codes](http://pkg-isocodes.alioth.debian.org/)
20 | - support for custom ignore tags and hot swap of `GtkTextBuffer`
21 | - support for Hunspell (LibreOffice) and Aspell (GNU) dictionaries
22 |
23 |
24 |
25 |
26 |
27 |
28 | ## 🚀 Getting Started
29 |
30 | Python GTK Spellcheck is available from the [Python Package Index](https://pypi.python.org/pypi/pygtkspellcheck):
31 | ```sh
32 | pip install pygtkspellcheck
33 | ```
34 | Depending on your distribution, you may also find Python GTK Spellcheck in your package manager.
35 | For instance, on Debian you may want to install the [`python3-gtkspellcheck`](https://packages.debian.org/bullseye/python3-gtkspellcheck) package.
36 |
37 |
38 | ## 🥳 Showcase
39 |
40 | Over time, several projects have used Python GTK Spellcheck or are still using it. Among those are:
41 |
42 | - [Nested Editor](http://nestededitor.sourceforge.net/about.html): “Specialized editor for structured documents.”
43 | - [Cherry Tree](http://www.giuspen.com/cherrytree/): “A hierarchical note taking application, […].”
44 | - [Zim](http://zim-wiki.org/): “Zim is a graphical text editor used to maintain a collection of wiki pages.”
45 | - [REMARKABLE](http://remarkableapp.github.io/): “The best markdown editor for Linux and Windows.”
46 | - [RedNotebook](http://rednotebook.sourceforge.net/): “RedNotebook is a modern journal.”
47 | - [Reportbug](https://packages.debian.org/stretch/reportbug): “Reports bugs in the Debian distribution.”
48 | - [UberWriter](http://uberwriter.wolfvollprecht.de/): “UberWriter is a writing application for markdown.”
49 | - [Gourmet](https://github.com/thinkle/gourmet): “Gourmet Recipe Manager is a manager, editor, and organizer for recipes.“
50 |
51 |
52 | ## 🔖 Versions
53 |
54 | Version numbers follow [Semantic Versioning](http://semver.org/). However, the update from 3 to 4 pertains only API incompatible changes in `oxt_extract` and not the spellchecking component. The update from 4 to 5 removed support for Python 2, GTK 2, `pylocales`, and the `oxt_extract` API. Otherwise, the API is still compatible with version 3.
55 |
56 |
57 | ## 📚 Documentation
58 |
59 | The documentation is available at [Read the Docs](http://pygtkspellcheck.readthedocs.org/).
60 |
61 |
62 | ## 🏗 Contributing
63 |
64 | We welcome all kinds of contributions! ❤️
65 |
66 | For minor changes and bug fixes feel free to simply open a pull request. For major changes impacting the overall design of Python GTK Spellcheck, please first [start a discussion](https://github.com/koehlma/pygtkspellcheck/discussions/new?category=ideas) outlining your idea.
67 |
68 | By submitting a PR, you agree to license your contributions under “GPLv3 or later”.
69 |
--------------------------------------------------------------------------------
/docs/Makefile:
--------------------------------------------------------------------------------
1 | # Makefile for Sphinx documentation
2 | #
3 |
4 | # You can set these variables from the command line.
5 | SPHINXOPTS =
6 | SPHINXBUILD = sphinx-build
7 | PAPER =
8 | BUILDDIR = build
9 |
10 | # Internal variables.
11 | PAPEROPT_a4 = -D latex_paper_size=a4
12 | PAPEROPT_letter = -D latex_paper_size=letter
13 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
14 | # the i18n builder cannot share the environment and doctrees with the others
15 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
16 |
17 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
18 |
19 | help:
20 | @echo "Please use \`make ' where is one of"
21 | @echo " html to make standalone HTML files"
22 | @echo " dirhtml to make HTML files named index.html in directories"
23 | @echo " singlehtml to make a single large HTML file"
24 | @echo " pickle to make pickle files"
25 | @echo " json to make JSON files"
26 | @echo " htmlhelp to make HTML files and a HTML help project"
27 | @echo " qthelp to make HTML files and a qthelp project"
28 | @echo " devhelp to make HTML files and a Devhelp project"
29 | @echo " epub to make an epub"
30 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
31 | @echo " latexpdf to make LaTeX files and run them through pdflatex"
32 | @echo " text to make text files"
33 | @echo " man to make manual pages"
34 | @echo " texinfo to make Texinfo files"
35 | @echo " info to make Texinfo files and run them through makeinfo"
36 | @echo " gettext to make PO message catalogs"
37 | @echo " changes to make an overview of all changed/added/deprecated items"
38 | @echo " linkcheck to check all external links for integrity"
39 | @echo " doctest to run all doctests embedded in the documentation (if enabled)"
40 |
41 | clean:
42 | -rm -rf $(BUILDDIR)/*
43 |
44 | html:
45 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
46 | @echo
47 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
48 |
49 | dirhtml:
50 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
51 | @echo
52 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
53 |
54 | singlehtml:
55 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
56 | @echo
57 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
58 |
59 | pickle:
60 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
61 | @echo
62 | @echo "Build finished; now you can process the pickle files."
63 |
64 | json:
65 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
66 | @echo
67 | @echo "Build finished; now you can process the JSON files."
68 |
69 | htmlhelp:
70 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
71 | @echo
72 | @echo "Build finished; now you can run HTML Help Workshop with the" \
73 | ".hhp project file in $(BUILDDIR)/htmlhelp."
74 |
75 | qthelp:
76 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
77 | @echo
78 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \
79 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
80 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/PythonGTKSpellchecker.qhcp"
81 | @echo "To view the help file:"
82 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/PythonGTKSpellchecker.qhc"
83 |
84 | devhelp:
85 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
86 | @echo
87 | @echo "Build finished."
88 | @echo "To view the help file:"
89 | @echo "# mkdir -p $$HOME/.local/share/devhelp/PythonGTKSpellchecker"
90 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/PythonGTKSpellchecker"
91 | @echo "# devhelp"
92 |
93 | epub:
94 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
95 | @echo
96 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub."
97 |
98 | latex:
99 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
100 | @echo
101 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
102 | @echo "Run \`make' in that directory to run these through (pdf)latex" \
103 | "(use \`make latexpdf' here to do that automatically)."
104 |
105 | latexpdf:
106 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
107 | @echo "Running LaTeX files through pdflatex..."
108 | $(MAKE) -C $(BUILDDIR)/latex all-pdf
109 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
110 |
111 | text:
112 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
113 | @echo
114 | @echo "Build finished. The text files are in $(BUILDDIR)/text."
115 |
116 | man:
117 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
118 | @echo
119 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man."
120 |
121 | texinfo:
122 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
123 | @echo
124 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
125 | @echo "Run \`make' in that directory to run these through makeinfo" \
126 | "(use \`make info' here to do that automatically)."
127 |
128 | info:
129 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
130 | @echo "Running Texinfo files through makeinfo..."
131 | make -C $(BUILDDIR)/texinfo info
132 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
133 |
134 | gettext:
135 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
136 | @echo
137 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
138 |
139 | changes:
140 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
141 | @echo
142 | @echo "The overview file is in $(BUILDDIR)/changes."
143 |
144 | linkcheck:
145 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
146 | @echo
147 | @echo "Link check complete; look for any errors in the above output " \
148 | "or in $(BUILDDIR)/linkcheck/output.txt."
149 |
150 | doctest:
151 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
152 | @echo "Testing of doctests in the sources finished, look at the " \
153 | "results in $(BUILDDIR)/doctest/output.txt."
154 |
--------------------------------------------------------------------------------
/docs/index.rst:
--------------------------------------------------------------------------------
1 | Python GTK Spellcheck
2 | =====================
3 |
4 | Python GTK Spellcheck is a simple but quite powerful spellchecking library for GTK written in pure Python. It's spellchecking component is based on Enchant_ and it supports both GTK 3 and 4 via PyGObject_.
5 |
6 | .. _Enchant: http://www.abisource.com/projects/enchant/
7 | .. _PyGObject: https://live.gnome.org/PyGObject/
8 | .. _ISO-Codes: http://pkg-isocodes.alioth.debian.org/
9 |
10 | Features
11 | --------
12 | - **spellchecking** based on Enchant_ for `GtkTextViews`
13 | - support for word, line and multiple line **ignore regular expressions**
14 | - support for both **GTK 3 or 4** via PyGObject_ for Python 3
15 | - localized names of the available languages based on ISO-Codes_
16 | - support for custom ignore tags and hot swap of `GtkTextBuffers`
17 | - enable and disable of spellchecking with preferences memory
18 | - support for Hunspell (LibreOffice) and Aspell (GNU) dictionaries
19 | - supports extraction of dictionaries out of LibreOffice extension files
20 |
21 |
22 | Automatic Version Detection
23 | ---------------------------
24 |
25 | Python GTK Spellcheck will automatically detect the version of GKT (3 or 4) used by your project. To this end, you have to import GTK before importing `gtkspellcheck`. For example:
26 |
27 |
28 | .. code-block:: python
29 |
30 | import gi
31 |
32 | gi.require_version("Gtk", "4.0")
33 | from gi.repository import Gtk
34 |
35 | from gtkspellcheck import SpellChecker
36 |
37 |
38 | Python GTK Spellcheck will configure itself to use GTK 4 for the example above.
39 |
40 |
41 | API Reference
42 | -------------
43 | ```{eval-rst}
44 | .. autoclass:: gtkspellcheck.spellcheck.SpellChecker
45 | :members:
46 |
47 | .. autoclass:: gtkspellcheck.spellcheck.NoDictionariesFound
48 | ```
49 |
50 |
51 |
52 | Development
53 | -----------
54 | Development happens at `GitHub`_.
55 |
56 | .. _GitHub: https://github.com/koehlma/pygtkspellcheck
57 |
58 | ``git clone git://github.com/koehlma/pygtkspellcheck.git``
59 |
60 | Download last sources in a `ZIP`_ or `Tarball`_ file.
61 |
62 | .. _ZIP: https://github.com/koehlma/pygtkspellcheck/zipball/master
63 | .. _Tarball: https://github.com/koehlma/pygtkspellcheck/tarball/master
64 |
65 |
66 | Examples
67 | --------
68 | - `PyGObject Simple Example`_
69 | - `PyGtk Simple Example`_
70 |
71 | .. _PyGObject Simple Example: https://github.com/koehlma/pygtkspellcheck/blob/master/examples/simple_pygobject.py
72 | .. _PyGtk Simple Example: https://github.com/koehlma/pygtkspellcheck/blob/master/examples/simple_pygtk.py
73 |
74 |
75 | License
76 | -------
77 | PyGtkSpellcheck is released under `GPLv3`_ or at your opinion any later version.
78 |
79 | .. _GPLv3: https://www.gnu.org/licenses/gpl-3.0.html
80 |
--------------------------------------------------------------------------------
/docs/insert_metadata.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding:utf-8 -*-
3 | #
4 | # Copyright (C) 2012, Maximilian Köhl
5 | # Copyright (C) 2012, Carlos Jenkins
6 | #
7 | # This program is free software: you can redistribute it and/or modify
8 | # it under the terms of the GNU General Public License as published by
9 | # the Free Software Foundation, either version 3 of the License, or
10 | # (at your option) any later version.
11 | #
12 | # This program is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | # GNU General Public License for more details.
16 | #
17 | # You should have received a copy of the GNU General Public License
18 | # along with this program. If not, see .
19 |
20 | ENCODING = "UTF-8"
21 |
22 | import sys
23 | import argparse
24 |
25 | # Python 2/3 unicode
26 | import sys
27 |
28 | if sys.version_info.major == 3:
29 | io_in = lambda x: x
30 | io_out = io_in
31 | else:
32 | io_in = lambda x: x.decode(ENCODING)
33 | io_out = lambda x: x.encode(ENCODING)
34 |
35 | # Pipes Python enconding nightmare
36 | if sys.stdout.encoding is None:
37 | import codecs
38 |
39 | sys.stdout = codecs.getwriter(ENCODING)(sys.stdout)
40 |
41 | # Find metadata dict
42 | from os.path import join, dirname
43 |
44 | sys.path.append(join(dirname(__file__), "../src/"))
45 | from gtkspellcheck import __metadata__
46 |
47 | # Parse command line
48 | parser = argparse.ArgumentParser(description="Insert metadata into plain text files.")
49 | parser.add_argument(
50 | "infile",
51 | type=argparse.FileType("r"),
52 | help="path to the template file or stdin pipe.",
53 | )
54 | parser.add_argument(
55 | "-w",
56 | "--writeback",
57 | action="store_true",
58 | help="write the output back to the input file.",
59 | )
60 | args = parser.parse_args()
61 |
62 | # Read content
63 | out_content = io_in(args.infile.read())
64 | args.infile.close()
65 |
66 | # Replace variables
67 | # FIXME: Stop wasting memory like crazy!
68 | for key, value in __metadata__.items():
69 | out_content = out_content.replace(key, value)
70 |
71 | # Print/Write new content
72 | if args.writeback:
73 | try:
74 | with open(args.infile.name, "w") as out_handler:
75 | out_handler.write(io_out(out_content))
76 | except Exception as e:
77 | sys.stderr.write(str(e) + "\n")
78 | sys.exit(-1)
79 | else:
80 | print(out_content)
81 |
82 | sys.exit(0)
83 |
--------------------------------------------------------------------------------
/docs/make.bat:
--------------------------------------------------------------------------------
1 | @ECHO OFF
2 |
3 | REM Command file for Sphinx documentation
4 |
5 | if "%SPHINXBUILD%" == "" (
6 | set SPHINXBUILD=sphinx-build2
7 | )
8 | set BUILDDIR=build
9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% source
10 | set I18NSPHINXOPTS=%SPHINXOPTS% source
11 | if NOT "%PAPER%" == "" (
12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%
14 | )
15 |
16 | if "%1" == "" goto help
17 |
18 | if "%1" == "help" (
19 | :help
20 | echo.Please use `make ^` where ^ is one of
21 | echo. html to make standalone HTML files
22 | echo. dirhtml to make HTML files named index.html in directories
23 | echo. singlehtml to make a single large HTML file
24 | echo. pickle to make pickle files
25 | echo. json to make JSON files
26 | echo. htmlhelp to make HTML files and a HTML help project
27 | echo. qthelp to make HTML files and a qthelp project
28 | echo. devhelp to make HTML files and a Devhelp project
29 | echo. epub to make an epub
30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
31 | echo. text to make text files
32 | echo. man to make manual pages
33 | echo. texinfo to make Texinfo files
34 | echo. gettext to make PO message catalogs
35 | echo. changes to make an overview over all changed/added/deprecated items
36 | echo. linkcheck to check all external links for integrity
37 | echo. doctest to run all doctests embedded in the documentation if enabled
38 | goto end
39 | )
40 |
41 | if "%1" == "clean" (
42 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
43 | del /q /s %BUILDDIR%\*
44 | goto end
45 | )
46 |
47 | if "%1" == "html" (
48 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
49 | if errorlevel 1 exit /b 1
50 | echo.
51 | echo.Build finished. The HTML pages are in %BUILDDIR%/html.
52 | goto end
53 | )
54 |
55 | if "%1" == "dirhtml" (
56 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
57 | if errorlevel 1 exit /b 1
58 | echo.
59 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
60 | goto end
61 | )
62 |
63 | if "%1" == "singlehtml" (
64 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
65 | if errorlevel 1 exit /b 1
66 | echo.
67 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
68 | goto end
69 | )
70 |
71 | if "%1" == "pickle" (
72 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
73 | if errorlevel 1 exit /b 1
74 | echo.
75 | echo.Build finished; now you can process the pickle files.
76 | goto end
77 | )
78 |
79 | if "%1" == "json" (
80 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
81 | if errorlevel 1 exit /b 1
82 | echo.
83 | echo.Build finished; now you can process the JSON files.
84 | goto end
85 | )
86 |
87 | if "%1" == "htmlhelp" (
88 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
89 | if errorlevel 1 exit /b 1
90 | echo.
91 | echo.Build finished; now you can run HTML Help Workshop with the ^
92 | .hhp project file in %BUILDDIR%/htmlhelp.
93 | goto end
94 | )
95 |
96 | if "%1" == "qthelp" (
97 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
98 | if errorlevel 1 exit /b 1
99 | echo.
100 | echo.Build finished; now you can run "qcollectiongenerator" with the ^
101 | .qhcp project file in %BUILDDIR%/qthelp, like this:
102 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\PythonGTKSpellchecker.qhcp
103 | echo.To view the help file:
104 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\PythonGTKSpellchecker.ghc
105 | goto end
106 | )
107 |
108 | if "%1" == "devhelp" (
109 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
110 | if errorlevel 1 exit /b 1
111 | echo.
112 | echo.Build finished.
113 | goto end
114 | )
115 |
116 | if "%1" == "epub" (
117 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
118 | if errorlevel 1 exit /b 1
119 | echo.
120 | echo.Build finished. The epub file is in %BUILDDIR%/epub.
121 | goto end
122 | )
123 |
124 | if "%1" == "latex" (
125 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
126 | if errorlevel 1 exit /b 1
127 | echo.
128 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
129 | goto end
130 | )
131 |
132 | if "%1" == "text" (
133 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
134 | if errorlevel 1 exit /b 1
135 | echo.
136 | echo.Build finished. The text files are in %BUILDDIR%/text.
137 | goto end
138 | )
139 |
140 | if "%1" == "man" (
141 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
142 | if errorlevel 1 exit /b 1
143 | echo.
144 | echo.Build finished. The manual pages are in %BUILDDIR%/man.
145 | goto end
146 | )
147 |
148 | if "%1" == "texinfo" (
149 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo
150 | if errorlevel 1 exit /b 1
151 | echo.
152 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.
153 | goto end
154 | )
155 |
156 | if "%1" == "gettext" (
157 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale
158 | if errorlevel 1 exit /b 1
159 | echo.
160 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale.
161 | goto end
162 | )
163 |
164 | if "%1" == "changes" (
165 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
166 | if errorlevel 1 exit /b 1
167 | echo.
168 | echo.The overview file is in %BUILDDIR%/changes.
169 | goto end
170 | )
171 |
172 | if "%1" == "linkcheck" (
173 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
174 | if errorlevel 1 exit /b 1
175 | echo.
176 | echo.Link check complete; look for any errors in the above output ^
177 | or in %BUILDDIR%/linkcheck/output.txt.
178 | goto end
179 | )
180 |
181 | if "%1" == "doctest" (
182 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
183 | if errorlevel 1 exit /b 1
184 | echo.
185 | echo.Testing of doctests in the sources finished, look at the ^
186 | results in %BUILDDIR%/doctest/output.txt.
187 | goto end
188 | )
189 |
190 | :end
191 |
--------------------------------------------------------------------------------
/docs/metadata/documentation.rst:
--------------------------------------------------------------------------------
1 | {% names['full'] %}
2 | {% '=' * len(names['full']) %}
3 | {% linkify(description['long'], 'rst') %}
4 |
5 | Features
6 | --------
7 | {% '- ' + '\n- '.join(features) %}
8 |
9 | API Reference
10 | -------------
11 | .. autoclass:: gtkspellcheck.spellcheck.SpellChecker
12 | :members:
13 |
14 | .. autoclass:: gtkspellcheck.spellcheck.NoDictionariesFound
15 |
16 | .. autoclass:: gtkspellcheck.spellcheck.NoGtkBindingFound
17 |
18 | .. autofunction:: pylocales.code_to_name
19 |
20 | .. autofunction:: gtkspellcheck.oxt_extract.extract
21 |
22 | .. autofunction:: gtkspellcheck.oxt_extract.batch_extract
23 |
24 | .. autoclass:: gtkspellcheck.oxt_extract.BadXml
25 |
26 | .. autoclass:: gtkspellcheck.oxt_extract.BadExtensionFile
27 |
28 | .. autoclass:: gtkspellcheck.oxt_extract.ExtractPathIsNoDirectory
29 |
30 | Development
31 | -----------
32 | Development happens at `GitHub`_.
33 |
34 | .. _GitHub: {% development %}
35 |
36 | ``git clone git://github.com/koehlma/pygtkspellcheck.git``
37 |
38 | Download last sources in a `ZIP`_ or `Tarball`_ file.
39 |
40 | .. _ZIP: https://github.com/koehlma/pygtkspellcheck/zipball/master
41 | .. _Tarball: https://github.com/koehlma/pygtkspellcheck/tarball/master
42 |
43 | Website
44 | -------
45 | Checkout the `official project website`_ for additional information.
46 |
47 | .. _official project website: {% homepage %}
48 |
49 | Examples
50 | --------
51 | - `PyGObject Simple Example`_
52 | - `PyGtk Simple Example`_
53 |
54 | .. _PyGObject Simple Example: https://github.com/koehlma/pygtkspellcheck/blob/master/examples/simple_pygobject.py
55 | .. _PyGtk Simple Example: https://github.com/koehlma/pygtkspellcheck/blob/master/examples/simple_pygtk.py
56 |
57 |
58 | License
59 | -------
60 | {% names['short'] %} is released under `GPLv3`_ or at your opinion any later version.
61 |
62 | .. _GPLv3: https://www.gnu.org/licenses/gpl-3.0.html
--------------------------------------------------------------------------------
/docs/metadata/metadata.py:
--------------------------------------------------------------------------------
1 | # -*- coding:utf-8 -*-
2 | #
3 | # Copyright (C) 2012, Maximilian Köhl
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 .
17 |
18 | import os.path
19 | import re
20 |
21 | __path__ = os.path.dirname(__file__)
22 |
23 | names = {
24 | "full": "Python GTK Spellchecker",
25 | "short": "PyGtkSpellcheck",
26 | "url": "pygtkspellcheck",
27 | }
28 |
29 | features = [
30 | "localized names of the available languages",
31 | "supports word, line and multiple line ignore regular expressions",
32 | "supports ignore custom tags on GtkTextBuffer",
33 | "enable and disable of spellchecking with preferences memory",
34 | "supports hotswap of GtkTextBuffers",
35 | "PyGObject and PyGtk compatible with automatic detection",
36 | "Python 2 and 3 support"
37 | "as Enchant, support for Hunspell (LibreOffice) and Aspell (GNU) dictionaries",
38 | "extract dictionaries out of LibreOffice extension files",
39 | "legacy API for Python GtkSpell",
40 | ]
41 |
42 | description = {
43 | "short": "a simple but quite powerful Python spell checking library for GtkTextViews based on Enchant",
44 | "long": (
45 | "A simple but quite powerful spellchecking library written "
46 | "in pure Python for Gtk based on Enchant. It supports PyGObject "
47 | "as well as PyGtk for Python 2 and 3 with automatic switching "
48 | "and binding detection. For automatic translation of the user "
49 | "interface it can use Gedit’s translation files."
50 | ),
51 | }
52 |
53 | screenshot = os.path.join(__path__, "screenshot.png")
54 |
55 | development = "https://github.com/koehlma/pygtkspellcheck"
56 |
57 | documentation = "http://pygtkspellcheck.readthedocs.org/"
58 |
59 | homepage = "http://koehlma.github.com/projects/pygtkspellcheck.html"
60 |
61 | links = {
62 | "Enchant": "http://www.abisource.com/projects/enchant/",
63 | "PyGObject": "https://live.gnome.org/PyGObject/",
64 | "PyGtk": "http://www.pygtk.org/",
65 | }
66 |
67 | with open(os.path.join(__path__, "readme.md"), "rb") as _readme:
68 | readme = _readme.read().decode("utf-8")
69 |
70 | with open(os.path.join(__path__, "pypi.rst"), "rb") as _pypi:
71 | pypi = _pypi.read().decode("utf-8")
72 |
73 | with open(os.path.join(__path__, "documentation.rst"), "rb") as _documentation:
74 | docs = _documentation.read().decode("utf-8")
75 |
76 | with open(os.path.join(__path__, "website.md"), "rb") as _website:
77 | website = _website.read().decode("utf-8")
78 |
79 | replace = re.compile("\{%\s*(.+?)\s*%\}")
80 |
81 |
82 | def linkify(text, format):
83 | if format == "markdown":
84 | for name, url in links.items():
85 | text = text.replace(name, "[{}]({})".format(name, url))
86 | elif format == "rst":
87 | for name in links:
88 | text = text.replace(name, "`{}`_".format(name))
89 | text += "\n"
90 | for name, url in links.items():
91 | if text.find(name) > -1:
92 | text += "\n.. _{}: {}".format(name, url)
93 | return text
94 |
95 |
96 | def template(match):
97 | code = match.group(1)
98 | return str(eval(code))
99 |
100 |
101 | if __name__ == "__main__":
102 | print("creating readme")
103 | with open(os.path.join(__path__, "..", "..", "README.md"), "wb") as _readme:
104 | _readme.write(replace.sub(template, readme).encode("utf-8"))
105 | print("creating pypi")
106 | with open(os.path.join(__path__, "..", "pypi", "page.rst"), "wb") as _pypi:
107 | _pypi.write(replace.sub(template, pypi).encode("utf-8"))
108 | print("creating documentation")
109 | with open(
110 | os.path.join(__path__, "..", "source", "index.rst"), "wb"
111 | ) as _documentation:
112 | _documentation.write(replace.sub(template, docs).encode("utf-8"))
113 | koehlma_github = os.path.join(__path__, "..", "..", "..", "koehlma.github.com")
114 | if os.path.exists(koehlma_github):
115 | print("creating website")
116 | with open(
117 | os.path.join(koehlma_github, "projects", "pygtkspellcheck.md"), "wb"
118 | ) as _website:
119 | _website.write(replace.sub(template, website).encode("utf-8"))
120 |
--------------------------------------------------------------------------------
/docs/metadata/pypi.rst:
--------------------------------------------------------------------------------
1 | {% names['full'] %}
2 | {% '=' * len(names['full']) %}
3 | {% linkify(description['long'], 'rst') %}
4 |
5 | Features
6 | ========
7 | {% '- ' + '\n- '.join(features) %}
8 |
9 | Documentation
10 | =============
11 | The documentation is available at `Read the Docs`_.
12 |
13 | .. _Read the Docs: {% documentation %}
14 |
15 | Distribution
16 | ============
17 | Cheeseshop
18 | ^^^^^^^^^^
19 | `PyPI package`_ is available:
20 |
21 | .. _PyPI package: http://pypi.python.org/pypi/pygtkspellcheck/
22 |
23 | ::
24 |
25 | pip install pygtkspellcheck
26 |
27 | Archlinux - AUR
28 | ^^^^^^^^^^^^^^^
29 | Python 3
30 | --------
31 |
32 | ::
33 | pacman -S python-gtkspellcheck
34 |
35 | Python 2
36 | --------
37 |
38 | ::
39 | pacman -S python2-gtkspellcheck
40 |
41 | Ubuntu / Debian
42 | ^^^^^^^^^^^^^^^
43 | Ubuntu - Repository
44 | -------------------
45 |
46 | ::
47 |
48 | sudo add-apt-repository ppa:koehlma/packages
49 | sudo apt-get update
50 |
51 | Debian - Repository
52 | -------------------
53 |
54 | ::
55 |
56 | sudo su
57 | echo "deb http://ppa.launchpad.net/koehlma/packages/ubuntu precise main" >> /etc/apt/sources.list
58 | apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 775B7DF6
59 | apt-get update
60 |
61 | Python 2
62 | --------
63 |
64 | ::
65 |
66 | sudo apt-get install python-gtkspellcheck
67 |
68 | Python 3
69 | --------
70 |
71 | ::
72 |
73 | sudo apt-get install python3-gtkspellcheck
74 |
75 | Development
76 | ^^^^^^^^^^^
77 | Development happens at `GitHub`_.
78 |
79 | .. _GitHub: {% development %}
80 |
81 | License
82 | ^^^^^^^
83 | {% names['short'] %} is released under `GPLv3`_ or at your opinion any later version.
84 |
85 | .. _GPLv3: https://www.gnu.org/licenses/gpl-3.0.html
86 |
--------------------------------------------------------------------------------
/docs/metadata/readme.md:
--------------------------------------------------------------------------------
1 | ## About
2 | {% linkify(description['long'], 'markdown') %}
3 |
4 | ## Features
5 | {% '* ' + '\n* '.join(features) %}
6 |
7 | ## Documentation
8 | The documentation is available at [Read the Docs]({% documentation %}).
9 |
10 | ## Website
11 | Checkout the [official project website]({% homepage %}).
12 |
13 | ## License
14 | This program is free software: you can redistribute it and/or modify
15 | it under the terms of the GNU General Public License as published by
16 | the Free Software Foundation, either version 3 of the License, or
17 | (at your option) any later version.
18 |
19 | This program is distributed in the hope that it will be useful,
20 | but WITHOUT ANY WARRANTY; without even the implied warranty of
21 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 | GNU General Public License for more details.
23 |
24 | You should have received a copy of the GNU General Public License
25 | along with this program. If not, see .
26 |
--------------------------------------------------------------------------------
/docs/metadata/screenshot.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/koehlma/pygtkspellcheck/f872114f4b2d588dbcacca63a48e87a7fd04548f/docs/metadata/screenshot.png
--------------------------------------------------------------------------------
/docs/metadata/website.md:
--------------------------------------------------------------------------------
1 | ---
2 | layout: default
3 | title: Python GTK Spellchecker
4 | repository: pygtkspellcheck
5 | downloads:
6 | - class: archlinux
7 | url: https://github.com/downloads/koehlma/pygtkspellcheck/python-gtkspellcheck-3.0-1-any.pkg.tar.xz
8 | text: Python 3
9 | - class: archlinux
10 | url: https://github.com/downloads/koehlma/pygtkspellcheck/python2-gtkspellcheck-3.0-1-any.pkg.tar.xz
11 | text: Python 2
12 | - class: debian
13 | url: https://github.com/downloads/koehlma/pygtkspellcheck/python3-gtkspellcheck_3.0-1_all.deb
14 | text: Python 3
15 | - class: debian
16 | url: https://github.com/downloads/koehlma/pygtkspellcheck/python-gtkspellcheck_3.0-1_all.deb
17 | text: Python 2
18 | ---
19 |
20 | {% linkify(description['long'], 'markdown') %}
21 |
22 | # Features
23 | {% '* ' + '\n* '.join(features) %}
24 |
25 | # Screenshots
26 | 
27 |
28 | ## Documentation
29 | The documentation is available at [Read the Docs]({% documentation %}).
30 |
31 | # Examples
32 | * [PyGObject Simple Example](https://github.com/koehlma/pygtkspellcheck/blob/master/examples/simple_pygobject.py)
33 | * [PyGtk Simple Example](https://github.com/koehlma/pygtkspellcheck/blob/master/examples/simple_pygtk.py)
34 |
35 | # Distribution
36 | ## Cheeseshop
37 | [PyPI package](http://pypi.python.org/pypi/pygtkspellcheck/) is available:
38 |
39 | pip install pygtkspellcheck
40 |
41 | ## Archlinux - AUR
42 | ### Python 3
43 | [AUR Package](https://aur.archlinux.org/packages.php?ID=61200)
44 |
45 | yaourt -S python-gtkspellcheck
46 |
47 | ### Python 2
48 | [AUR Package](https://aur.archlinux.org/packages.php?ID=61199)
49 |
50 | yaourt -S python2-gtkspellcheck
51 |
52 | ## Ubuntu / Debian
53 | ### Ubuntu - Repository
54 |
55 | sudo add-apt-repository ppa:koehlma/packages
56 | sudo apt-get update
57 |
58 | ### Debian - Repository
59 |
60 | sudo su
61 | echo "deb http://ppa.launchpad.net/koehlma/packages/ubuntu precise main" >> /etc/apt/sources.list
62 | apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 775B7DF6
63 | apt-get update
64 |
65 | ### Python 2
66 |
67 | sudo apt-get install python-gtkspellcheck
68 |
69 | ### Python 3
70 |
71 | sudo apt-get install python3-gtkspellcheck
72 |
--------------------------------------------------------------------------------
/docs/pypi/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | PyGtkSpellcheck - Documentation
8 |
9 |
10 |
11 |
12 | The documentation has moved to Read the Docs.
13 |
14 |
15 |
--------------------------------------------------------------------------------
/docs/pypi/page.rst:
--------------------------------------------------------------------------------
1 | Python GTK Spellchecker
2 | =======================
3 | A simple but quite powerful spellchecking library written in pure Python for Gtk based on `Enchant`_. It supports `PyGObject`_ as well as `PyGtk`_ for Python 2 and 3 with automatic switching and binding detection. For automatic translation of the user interface it can use Gedit’s translation files.
4 |
5 | .. _PyGObject: https://live.gnome.org/PyGObject/
6 | .. _Enchant: http://www.abisource.com/projects/enchant/
7 | .. _PyGtk: http://www.pygtk.org/
8 |
9 | Features
10 | ========
11 | - localized names of the available languages
12 | - supports word, line and multiple line ignore regular expressions
13 | - supports ignore custom tags on GtkTextBuffer
14 | - enable and disable of spellchecking with preferences memory
15 | - supports hotswap of GtkTextBuffers
16 | - PyGObject and PyGtk compatible with automatic detection
17 | - Python 2 and 3 supportas Enchant, support for Hunspell (LibreOffice) and Aspell (GNU) dictionaries
18 | - extract dictionaries out of LibreOffice extension files
19 | - legacy API for Python GtkSpell
20 |
21 | Documentation
22 | =============
23 | The documentation is available at `Read the Docs`_.
24 |
25 | .. _Read the Docs: http://pygtkspellcheck.readthedocs.org/
26 |
27 | Distribution
28 | ============
29 | Cheeseshop
30 | ^^^^^^^^^^
31 | `PyPI package`_ is available:
32 |
33 | .. _PyPI package: http://pypi.python.org/pypi/pygtkspellcheck/
34 |
35 | ::
36 |
37 | pip install pygtkspellcheck
38 |
39 | Archlinux - AUR
40 | ^^^^^^^^^^^^^^^
41 | Python 3
42 | --------
43 |
44 | ::
45 |
46 | pacman -S python-gtkspellcheck
47 |
48 | Python 2
49 | --------
50 |
51 | ::
52 |
53 | pacman -S python2-gtkspellcheck
54 |
55 | Ubuntu / Debian
56 | ^^^^^^^^^^^^^^^
57 | Python 2
58 | --------
59 |
60 | ::
61 |
62 | sudo apt-get install python-gtkspellcheck
63 |
64 | Python 3
65 | --------
66 |
67 | ::
68 |
69 | sudo apt-get install python3-gtkspellcheck
70 |
71 | Development
72 | ^^^^^^^^^^^
73 | Development happens at `GitHub`_.
74 |
75 | .. _GitHub: https://github.com/koehlma/pygtkspellcheck
76 |
77 | License
78 | ^^^^^^^
79 | PyGtkSpellcheck is released under `GPLv3`_ or at your opinion any later version.
80 |
81 | .. _GPLv3: https://www.gnu.org/licenses/gpl-3.0.html
82 |
--------------------------------------------------------------------------------
/docs/screenshots/screenshot.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/koehlma/pygtkspellcheck/f872114f4b2d588dbcacca63a48e87a7fd04548f/docs/screenshots/screenshot.png
--------------------------------------------------------------------------------
/docs/source/conf.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # Python GTK Spellchecker documentation build configuration file, created by
4 | # sphinx-quickstart2 on Tue Apr 10 18:57:32 2012.
5 | #
6 | # This file is execfile()d with the current directory set to its containing dir.
7 | #
8 | # Note that not all possible configuration values are present in this
9 | # autogenerated file.
10 | #
11 | # All configuration values have a default; values that are commented out
12 | # serve to show the default.
13 |
14 | import sys, os
15 |
16 | import sphinx_rtd_theme
17 |
18 | # If extensions (or modules to document with autodoc) are in another directory,
19 | # add these directories to sys.path here. If the directory is relative to the
20 | # documentation root, use os.path.abspath to make it absolute, like shown here.
21 | # sys.path.insert(0, os.path.abspath('.'))
22 |
23 | doc_directory = os.path.dirname(os.path.abspath(__file__))
24 | sys.path.append(os.path.join(doc_directory, "..", "..", "src"))
25 |
26 | import sys
27 |
28 |
29 | # Support for readthedocs.org
30 | class Mock(object):
31 | def __init__(self, *args, **kwargs):
32 | pass
33 |
34 | def __call__(self, *args, **kwargs):
35 | return Mock()
36 |
37 | @classmethod
38 | def __getattr__(self, name):
39 | if name in ("__file__", "__path__"):
40 | return "/dev/null"
41 | elif name[0] == name[0].upper():
42 | return type(name, (), {})
43 | else:
44 | return Mock()
45 |
46 |
47 | MOCK_MODULES = ["enchant"]
48 | for mod_name in MOCK_MODULES:
49 | try:
50 | __import__(mod_name)
51 | except:
52 | sys.modules[mod_name] = Mock()
53 |
54 |
55 | class GtkMock:
56 | MAJOR_VERSION = 3
57 |
58 |
59 | sys.modules["gi.repository.Gtk"] = GtkMock()
60 |
61 | import gtkspellcheck as m
62 |
63 | start_file = "index"
64 |
65 | # -- General configuration -----------------------------------------------------
66 |
67 | # If your documentation needs a minimal Sphinx version, state it here.
68 | # needs_sphinx = '1.0'
69 |
70 | # Add any Sphinx extension module names here, as strings. They can be extensions
71 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
72 | extensions = ["sphinx.ext.autodoc", "myst_parser", "sphinx_rtd_theme"]
73 |
74 | # Add any paths that contain templates here, relative to this directory.
75 | templates_path = ["_templates"]
76 |
77 | # The suffix of source filenames.
78 | source_suffix = {
79 | ".rst": "restructuredtext",
80 | ".txt": "markdown",
81 | ".md": "markdown",
82 | }
83 |
84 | # The encoding of source files.
85 | # source_encoding = 'utf-8-sig'
86 |
87 | # The master toctree document.
88 | master_doc = start_file
89 |
90 | # General information about the project.
91 | project = m.__project__
92 | copyright = m.__authors__
93 |
94 | # The version info for the project you're documenting, acts as replacement for
95 | # |version| and |release|, also used in various other places throughout the
96 | # built documents.
97 | #
98 | # The short X.Y version.
99 | version = m.__version__
100 | # The full version, including alpha/beta/rc tags.
101 | release = m.__version__
102 |
103 | # The language for content autogenerated by Sphinx. Refer to documentation
104 | # for a list of supported languages.
105 | # language = None
106 |
107 | # There are two options for replacing |today|: either, you set today to some
108 | # non-false value, then it is used:
109 | # today = ''
110 | # Else, today_fmt is used as the format for a strftime call.
111 | # today_fmt = '%B %d, %Y'
112 |
113 | # List of patterns, relative to source directory, that match files and
114 | # directories to ignore when looking for source files.
115 | exclude_patterns = []
116 |
117 | # The reST default role (used for this markup: `text`) to use for all documents.
118 | # default_role = None
119 |
120 | # If true, '()' will be appended to :func: etc. cross-reference text.
121 | # add_function_parentheses = True
122 |
123 | # If true, the current module name will be prepended to all description
124 | # unit titles (such as .. function::).
125 | # add_module_names = True
126 |
127 | # If true, sectionauthor and moduleauthor directives will be shown in the
128 | # output. They are ignored by default.
129 | # show_authors = False
130 |
131 | # The name of the Pygments (syntax highlighting) style to use.
132 | pygments_style = "sphinx"
133 |
134 | # A list of ignored prefixes for module index sorting.
135 | # modindex_common_prefix = []
136 |
137 |
138 | # -- Options for HTML output ---------------------------------------------------
139 |
140 | # The theme to use for HTML and HTML Help pages. See the documentation for
141 | # a list of builtin themes.
142 | html_theme = "sphinx_rtd_theme"
143 |
144 | # Theme options are theme-specific and customize the look and feel of a theme
145 | # further. For a list of options available for each theme, see the
146 | # documentation.
147 | # html_theme_options = {}
148 |
149 | # Add any paths that contain custom themes here, relative to this directory.
150 | # html_theme_path = []
151 |
152 | # The name for this set of Sphinx documents. If None, it defaults to
153 | # " v documentation".
154 | # html_title = None
155 |
156 | # A shorter title for the navigation bar. Default is the same as html_title.
157 | # html_short_title = None
158 |
159 | # The name of an image file (relative to this directory) to place at the top
160 | # of the sidebar.
161 | # html_logo = None
162 |
163 | # The name of an image file (within the static path) to use as favicon of the
164 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
165 | # pixels large.
166 | # html_favicon = None
167 |
168 | # Add any paths that contain custom static files (such as style sheets) here,
169 | # relative to this directory. They are copied after the builtin static files,
170 | # so a file named "default.css" will overwrite the builtin "default.css".
171 | # html_static_path = ['_static']
172 |
173 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
174 | # using the given strftime format.
175 | # html_last_updated_fmt = '%b %d, %Y'
176 |
177 | # If true, SmartyPants will be used to convert quotes and dashes to
178 | # typographically correct entities.
179 | # html_use_smartypants = True
180 |
181 | # Custom sidebar templates, maps document names to template names.
182 | # html_sidebars = {}
183 |
184 | # Additional templates that should be rendered to pages, maps page names to
185 | # template names.
186 | # html_additional_pages = {}
187 |
188 | # If false, no module index is generated.
189 | # html_domain_indices = True
190 |
191 | # If false, no index is generated.
192 | # html_use_index = True
193 |
194 | # If true, the index is split into individual pages for each letter.
195 | # html_split_index = False
196 |
197 | # If true, links to the reST sources are added to the pages.
198 | # html_show_sourcelink = True
199 |
200 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
201 | # html_show_sphinx = True
202 |
203 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
204 | # html_show_copyright = True
205 |
206 | # If true, an OpenSearch description file will be output, and all pages will
207 | # contain a tag referring to it. The value of this option must be the
208 | # base URL from which the finished HTML is served.
209 | # html_use_opensearch = ''
210 |
211 | # This is the file name suffix for HTML files (e.g. ".xhtml").
212 | # html_file_suffix = None
213 |
214 | # Output file base name for HTML help builder.
215 | htmlhelp_basename = m.__short_name__ + "doc"
216 |
217 |
218 | # -- Options for LaTeX output --------------------------------------------------
219 |
220 | latex_elements = {
221 | # The paper size ('letterpaper' or 'a4paper').
222 | #'papersize': 'letterpaper',
223 | # The font size ('10pt', '11pt' or '12pt').
224 | #'pointsize': '10pt',
225 | # Additional stuff for the LaTeX preamble.
226 | #'preamble': '',
227 | }
228 |
229 | # Grouping the document tree into LaTeX files. List of tuples
230 | # (source start file, target name, title, author, documentclass [howto/manual]).
231 | latex_documents = [
232 | (
233 | start_file,
234 | m.__short_name__ + ".tex",
235 | m.__project__ + " Documentation",
236 | m.__authors__.replace("&", r"\&"),
237 | "manual",
238 | ),
239 | ]
240 |
241 | # The name of an image file (relative to this directory) to place at the top of
242 | # the title page.
243 | # latex_logo = None
244 |
245 | # For "manual" documents, if this is true, then toplevel headings are parts,
246 | # not chapters.
247 | # latex_use_parts = False
248 |
249 | # If true, show page references after internal links.
250 | # latex_show_pagerefs = False
251 |
252 | # If true, show URL addresses after external links.
253 | # latex_show_urls = False
254 |
255 | # Documents to append as an appendix to all manuals.
256 | # latex_appendices = []
257 |
258 | # If false, no module index is generated.
259 | # latex_domain_indices = True
260 |
261 |
262 | # -- Options for manual page output --------------------------------------------
263 |
264 | # One entry per manual page. List of tuples
265 | # (source start file, name, description, authors, manual section).
266 | man_pages = [
267 | (
268 | start_file,
269 | m.__short_name__,
270 | m.__project__ + " Documentation",
271 | m.__authors__.split(" & "),
272 | 1,
273 | )
274 | ]
275 |
276 | # If true, show URL addresses after external links.
277 | # man_show_urls = False
278 |
279 |
280 | # -- Options for Texinfo output ------------------------------------------------
281 |
282 | # Grouping the document tree into Texinfo files. List of tuples
283 | # (source start file, target name, title, author,
284 | # dir menu entry, description, category)
285 | texinfo_documents = [
286 | (
287 | start_file,
288 | m.__short_name__,
289 | m.__project__ + " Documentation",
290 | m.__authors__,
291 | m.__short_name__,
292 | m.__desc_short__,
293 | "Miscellaneous",
294 | ),
295 | ]
296 |
297 | # Documents to append as an appendix to all manuals.
298 | # texinfo_appendices = []
299 |
300 | # If false, no module index is generated.
301 | # texinfo_domain_indices = True
302 |
303 | # How to display URL addresses: 'footnote', 'no', or 'inline'.
304 | # texinfo_show_urls = 'footnote'
305 |
--------------------------------------------------------------------------------
/docs/source/index.md:
--------------------------------------------------------------------------------
1 | # Python GTK Spellcheck
2 |
3 | [](https://pypi.python.org/pypi/pygtkspellcheck)
4 | [](https://pygtkspellcheck.readthedocs.org/en/latest/)
5 |
6 | Python GTK Spellcheck is a simple but quite powerful spellchecking library for GTK written in pure Python. It's spellchecking component is based on [Enchant](http://www.abisource.com/projects/enchant/) and it supports both GTK 3 and 4 via [PyGObject](https://live.gnome.org/PyGObject/).
7 |
8 |
9 | ## ✨ Features
10 |
11 | - **spellchecking** based on [Enchant](http://www.abisource.com/projects/enchant/) for `GtkTextView`
12 | - support for word, line, and multiline **ignore regular expressions**
13 | - support for both **GTK 3 and 4** via [PyGObject](https://live.gnome.org/PyGObject/) for Python 3
14 | - localized names of the available languages based on [ISO-Codes](http://pkg-isocodes.alioth.debian.org/)
15 | - support for custom ignore tags and hot swap of `GtkTextBuffer`
16 | - support for Hunspell (LibreOffice) and Aspell (GNU) dictionaries
17 |
18 |
19 |
20 |
21 |
22 |
23 | ## 🚀 Getting Started
24 |
25 | Python GTK Spellcheck is available from the [Python Package Index](https://pypi.python.org/pypi/pygtkspellcheck):
26 | ```sh
27 | pip install pygtkspellcheck
28 | ```
29 | Depending on your distribution, you may also find Python GTK Spellcheck in your package manager.
30 | For instance, on Debian you may want to install the [`python3-gtkspellcheck`](https://packages.debian.org/bullseye/python3-gtkspellcheck) package.
31 |
32 |
33 | ## 📚 Documentation
34 |
35 | ### Automatic GTK Version Detection
36 |
37 |
38 | Python GTK Spellcheck will automatically detect the version of GTK (3 or 4) used by your project. To this end, you have to import GTK before importing `gtkspellcheck`. For example:
39 |
40 |
41 | ```python
42 | import gi
43 |
44 | gi.require_version("Gtk", "4.0")
45 | from gi.repository import Gtk
46 |
47 | from gtkspellcheck import SpellChecker
48 | ```
49 |
50 | Python GTK Spellcheck will configure itself to use GTK 4 for the example above.
51 |
52 |
53 | ### API Reference
54 |
55 | ```{eval-rst}
56 | .. autoclass:: gtkspellcheck.spellcheck.SpellChecker
57 | :members:
58 |
59 | .. autoclass:: gtkspellcheck.spellcheck.NoDictionariesFound
60 | ```
61 |
62 |
63 | ### Examples
64 |
65 | We also have [examples](http://github.com/koehlma/pygtkspellcheck/examples) demonstrating various configurations and and how Python GTK Spellcheck can be used.
66 |
67 |
68 | ## 🥳 Showcase
69 |
70 | Over time, several projects have used Python GTK Spellcheck or are still using it. Among those are:
71 |
72 | - [Nested Editor](http://nestededitor.sourceforge.net/about.html): “Specialized editor for structured documents.”
73 | - [Cherry Tree](http://www.giuspen.com/cherrytree/): “A hierarchical note taking application, […].”
74 | - [Zim](http://zim-wiki.org/): “Zim is a graphical text editor used to maintain a collection of wiki pages.”
75 | - [REMARKABLE](http://remarkableapp.github.io/): “The best markdown editor for Linux and Windows.”
76 | - [RedNotebook](http://rednotebook.sourceforge.net/): “RedNotebook is a modern journal.”
77 | - [Reportbug](https://packages.debian.org/stretch/reportbug): “Reports bugs in the Debian distribution.”
78 | - [UberWriter](http://uberwriter.wolfvollprecht.de/): “UberWriter is a writing application for markdown.”
79 | - [Gourmet](https://github.com/thinkle/gourmet): “Gourmet Recipe Manager is a manager, editor, and organizer for recipes.“
80 |
81 |
82 | ## 🔖 Versions
83 |
84 | Version numbers follow [Semantic Versioning](http://semver.org/). However, the version change from 3 to 4 pertains only API incompatible changes in `oxt_extract` and not the spellchecking component. The update from 4 to 5 removed support for Python 2, GTK 2, `pylocales`, and the `oxt_extract` API.
85 |
86 |
87 | ## 🏗 Contributing
88 |
89 | We welcome all kinds of contributions! ❤️
90 |
91 | For details, checkout our [GitHub Repository](https://github.com/koehlma/pygtkspellcheck).
92 |
--------------------------------------------------------------------------------
/examples/collapsed_gtk3.py:
--------------------------------------------------------------------------------
1 | # -*- coding:utf-8 -*-
2 | #
3 | # Copyright (C) 2012, Maximilian Köhl
4 | # Copyright (C) 2012, Carlos Jenkins
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 .
18 |
19 | # Load example if running from source, ignore this
20 | import sys
21 | from os.path import join, dirname
22 |
23 | sys.path.append(join(dirname(__file__), "../src/"))
24 |
25 | import locale
26 |
27 | import gi
28 |
29 | gi.require_version("Gtk", "3.0")
30 | from gi.repository import Gtk
31 |
32 | from gtkspellcheck import SpellChecker
33 |
34 | if __name__ == "__main__":
35 |
36 | def quit(*args):
37 | Gtk.main_quit()
38 |
39 | window = Gtk.Window.new(Gtk.WindowType.TOPLEVEL)
40 | window.set_title("PyGtkSpellCheck Example")
41 | view = Gtk.TextView.new()
42 |
43 | spellchecker = SpellChecker(view, locale.getdefaultlocale()[0])
44 |
45 | for code, name in spellchecker.languages:
46 | print("code: %5s, language: %s" % (code, name))
47 |
48 | window.set_default_size(600, 400)
49 | window.add(view)
50 | window.show_all()
51 | window.connect("delete-event", quit)
52 | Gtk.main()
53 |
--------------------------------------------------------------------------------
/examples/collapsed_gtk4.py:
--------------------------------------------------------------------------------
1 | # -*- coding:utf-8 -*-
2 | #
3 | # Copyright (C) 2012, Maximilian Köhl
4 | # Copyright (C) 2012, Carlos Jenkins
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 .
18 |
19 | # Load example if running from source, ignore this
20 | import sys
21 | from os.path import join, dirname
22 |
23 | sys.path.append(join(dirname(__file__), "../src/"))
24 |
25 | import locale
26 |
27 | import gi
28 |
29 | gi.require_version("Gtk", "4.0")
30 | from gi.repository import Gtk
31 |
32 | from gtkspellcheck import SpellChecker
33 |
34 |
35 | class TestApp(Gtk.Application):
36 | def __init__(self, *args):
37 | super().__init__(*args)
38 | self.connect("activate", self.activate)
39 |
40 | def activate(self, _app: Gtk.Application):
41 | window = Gtk.Window()
42 | window.set_title("PyGtkSpellCheck GTK Example")
43 | view = Gtk.TextView()
44 |
45 | self.spellchecker = SpellChecker(view, locale.getdefaultlocale()[0])
46 | for code, name in self.spellchecker.languages:
47 | print("code: %5s, language: %s" % (code, name))
48 |
49 | self.view = view
50 | window.set_child(view)
51 | window.set_default_size(600, 400)
52 | self.add_window(window)
53 | window.present()
54 |
55 |
56 | if __name__ == "__main__":
57 | app = TestApp()
58 | app.run()
59 |
--------------------------------------------------------------------------------
/examples/expanded_gtk3.py:
--------------------------------------------------------------------------------
1 | # -*- coding:utf-8 -*-
2 | #
3 | # Copyright (C) 2012, Maximilian Köhl
4 | # Copyright (C) 2012, Carlos Jenkins
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 .
18 |
19 | # Load example if running from source, ignore this
20 | import sys
21 | from os.path import join, dirname
22 |
23 | sys.path.append(join(dirname(__file__), "../src/"))
24 |
25 | import locale
26 |
27 | import gi
28 |
29 | gi.require_version("Gtk", "3.0")
30 | from gi.repository import Gtk
31 |
32 | from gtkspellcheck import SpellChecker
33 |
34 | if __name__ == "__main__":
35 |
36 | def quit(*args):
37 | Gtk.main_quit()
38 |
39 | window = Gtk.Window.new(Gtk.WindowType.TOPLEVEL)
40 | window.set_title("PyGtkSpellCheck Example")
41 | view = Gtk.TextView.new()
42 |
43 | spellchecker = SpellChecker(view, locale.getdefaultlocale()[0], collapse=False)
44 |
45 | for code, name in spellchecker.languages:
46 | print("code: %5s, language: %s" % (code, name))
47 |
48 | window.set_default_size(600, 400)
49 | window.add(view)
50 | window.show_all()
51 | window.connect("delete-event", quit)
52 | Gtk.main()
53 |
--------------------------------------------------------------------------------
/examples/expanded_gtk4.py:
--------------------------------------------------------------------------------
1 | # -*- coding:utf-8 -*-
2 | #
3 | # Copyright (C) 2012, Maximilian Köhl
4 | # Copyright (C) 2012, Carlos Jenkins
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 .
18 |
19 | # Load example if running from source, ignore this
20 | import sys
21 | from os.path import join, dirname
22 |
23 | sys.path.append(join(dirname(__file__), "../src/"))
24 |
25 | import locale
26 |
27 | import gi
28 |
29 | gi.require_version("Gtk", "4.0")
30 | from gi.repository import Gtk
31 |
32 | from gtkspellcheck import SpellChecker
33 |
34 |
35 | class TestApp(Gtk.Application):
36 | def __init__(self, *args):
37 | super().__init__(*args)
38 | self.connect("activate", self.activate)
39 |
40 | def activate(self, _app: Gtk.Application):
41 | window = Gtk.Window()
42 | window.set_title("PyGtkSpellCheck GTK Example")
43 | view = Gtk.TextView()
44 |
45 | self.spellchecker = SpellChecker(
46 | view, locale.getdefaultlocale()[0], collapse=False
47 | )
48 | for code, name in self.spellchecker.languages:
49 | print("code: %5s, language: %s" % (code, name))
50 |
51 | self.view = view
52 | window.set_child(view)
53 | window.set_default_size(600, 400)
54 | self.add_window(window)
55 | window.present()
56 |
57 |
58 | if __name__ == "__main__":
59 | app = TestApp()
60 | app.run()
61 |
--------------------------------------------------------------------------------
/locale/de/pygtkspellcheck.mo:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/koehlma/pygtkspellcheck/f872114f4b2d588dbcacca63a48e87a7fd04548f/locale/de/pygtkspellcheck.mo
--------------------------------------------------------------------------------
/locale/de/pygtkspellcheck.po:
--------------------------------------------------------------------------------
1 | msgid ""
2 | msgstr ""
3 | "Project-Id-Version: gtkspellchecker\n"
4 | "Report-Msgid-Bugs-To: \n"
5 | "POT-Creation-Date: 2013-01-07 23:30+0100\n"
6 | "PO-Revision-Date: 2013-01-07 23:30+0100\n"
7 | "Last-Translator: Maximilian Köhl \n"
8 | "Language-Team: \n"
9 | "Language: de\n"
10 | "MIME-Version: 1.0\n"
11 | "Content-Type: text/plain; charset=UTF-8\n"
12 | "Content-Transfer-Encoding: 8bit\n"
13 | "X-Poedit-KeywordsList: _;gettext;gettext_noop\n"
14 | "X-Poedit-Basepath: /home/maximilian/Entwicklung/pygtkspellcheck/src\n"
15 | "X-Poedit-SourceCharset: UTF-8\n"
16 | "X-Poedit-SearchPath-0: ./gtkspellcheck\n"
17 |
18 | #: gtkspellcheck/spellcheck.py:98
19 | msgid "Unknown"
20 | msgstr "Unbekannt"
21 |
22 | #: gtkspellcheck/spellcheck.py:480
23 | msgid "(no suggestions)"
24 | msgstr "(keine Vorschläge)"
25 |
26 | #: gtkspellcheck/spellcheck.py:502 gtkspellcheck/spellcheck.py:505
27 | msgid "Add \"{}\" to Dictionary"
28 | msgstr "\"{}\" zum Wörterbuch hinzufügen"
29 |
30 | #: gtkspellcheck/spellcheck.py:509 gtkspellcheck/spellcheck.py:511
31 | msgid "Ignore All"
32 | msgstr "Alles ignorieren"
33 |
34 | #: gtkspellcheck/spellcheck.py:526 gtkspellcheck/spellcheck.py:528
35 | msgid "Languages"
36 | msgstr "Sprachen"
37 |
38 | #: gtkspellcheck/spellcheck.py:544 gtkspellcheck/spellcheck.py:547
39 | msgid "Suggestions"
40 | msgstr "Vorschläge"
41 |
42 | #: gtkspellcheck/oxt_extract.py:244
43 | msgid "extension \"{}\" is not a valid ZIP file"
44 | msgstr "Extension \"{}\" ist keine ZIP Datei"
45 |
46 | #: gtkspellcheck/oxt_extract.py:250
47 | msgid "extension \"{}\" has no valid XML dictionary registry"
48 | msgstr "Extension \"{}\" hat keine valide XML Registry"
49 |
50 | #: gtkspellcheck/oxt_extract.py:270
51 | msgid "unable to move extension, file with same name exists within move_path"
52 | msgstr ""
53 | "Extension kann nicht verschoben werden, es existiert bereits eine Datei mit "
54 | "gleichem Name in move_path"
55 |
56 | #: gtkspellcheck/oxt_extract.py:278
57 | msgid "unable to move extension, move_path is not a directory"
58 | msgstr "Extension kann nicht verschoben werden, move_path ist kein Verzeichnis"
59 |
--------------------------------------------------------------------------------
/locale/en/pygtkspellcheck.mo:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/koehlma/pygtkspellcheck/f872114f4b2d588dbcacca63a48e87a7fd04548f/locale/en/pygtkspellcheck.mo
--------------------------------------------------------------------------------
/locale/en/pygtkspellcheck.po:
--------------------------------------------------------------------------------
1 | # SOME DESCRIPTIVE TITLE.
2 | # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
3 | # This file is distributed under the same license as the PACKAGE package.
4 | # FIRST AUTHOR , YEAR.
5 | #
6 | msgid ""
7 | msgstr ""
8 | "Project-Id-Version: gtkspellcheck\n"
9 | "Report-Msgid-Bugs-To: \n"
10 | "POT-Creation-Date: 2013-01-07 23:31+0100\n"
11 | "PO-Revision-Date: 2013-01-07 23:31+0100\n"
12 | "Last-Translator: Maximilian Köhl \n"
13 | "Language-Team: \n"
14 | "Language: en\n"
15 | "MIME-Version: 1.0\n"
16 | "Content-Type: text/plain; charset=UTF-8\n"
17 | "Content-Transfer-Encoding: 8bit\n"
18 | "X-Poedit-Basepath: /home/maximilian/Entwicklung/pygtkspellcheck/src\n"
19 | "X-Poedit-SourceCharset: UTF-8\n"
20 | "X-Poedit-SearchPath-0: ./gtkspellcheck\n"
21 |
22 | #: gtkspellcheck/spellcheck.py:98
23 | msgid "Unknown"
24 | msgstr ""
25 |
26 | #: gtkspellcheck/spellcheck.py:480
27 | msgid "(no suggestions)"
28 | msgstr ""
29 |
30 | #: gtkspellcheck/spellcheck.py:502 gtkspellcheck/spellcheck.py:505
31 | msgid "Add \"{}\" to Dictionary"
32 | msgstr ""
33 |
34 | #: gtkspellcheck/spellcheck.py:509 gtkspellcheck/spellcheck.py:511
35 | msgid "Ignore All"
36 | msgstr ""
37 |
38 | #: gtkspellcheck/spellcheck.py:526 gtkspellcheck/spellcheck.py:528
39 | msgid "Languages"
40 | msgstr ""
41 |
42 | #: gtkspellcheck/spellcheck.py:544 gtkspellcheck/spellcheck.py:547
43 | msgid "Suggestions"
44 | msgstr ""
45 |
46 | #: gtkspellcheck/oxt_extract.py:244
47 | msgid "extension \"{}\" is not a valid ZIP file"
48 | msgstr ""
49 |
50 | #: gtkspellcheck/oxt_extract.py:250
51 | msgid "extension \"{}\" has no valid XML dictionary registry"
52 | msgstr ""
53 |
54 | #: gtkspellcheck/oxt_extract.py:270
55 | msgid "unable to move extension, file with same name exists within move_path"
56 | msgstr ""
57 |
58 | #: gtkspellcheck/oxt_extract.py:278
59 | msgid "unable to move extension, move_path is not a directory"
60 | msgstr ""
61 |
--------------------------------------------------------------------------------
/locale/es/pygtkspellcheck.mo:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/koehlma/pygtkspellcheck/f872114f4b2d588dbcacca63a48e87a7fd04548f/locale/es/pygtkspellcheck.mo
--------------------------------------------------------------------------------
/locale/es/pygtkspellcheck.po:
--------------------------------------------------------------------------------
1 | # SOME DESCRIPTIVE TITLE.
2 | # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
3 | # This file is distributed under the same license as the PACKAGE package.
4 | # FIRST AUTHOR , YEAR.
5 | #
6 | msgid ""
7 | msgstr ""
8 | "Project-Id-Version: gtkspellcheck\n"
9 | "Report-Msgid-Bugs-To: \n"
10 | "POT-Creation-Date: 2012-09-15 10:16+0100\n"
11 | "PO-Revision-Date: 2012-09-15 10:16+0100\n"
12 | "Last-Translator: Maximilian Köhl \n"
13 | "Language-Team: Carlos Jenkins \n"
14 | "Language: es\n"
15 | "MIME-Version: 1.0\n"
16 | "Content-Type: text/plain; charset=UTF-8\n"
17 | "Content-Transfer-Encoding: 8bit\n"
18 | "X-Poedit-SourceCharset: UTF-8\n"
19 | "X-Poedit-Basepath: /home/maximilian/development/pygtkspellcheck/src\n"
20 | "X-Poedit-SearchPath-0: ./gtkspellcheck\n"
21 |
22 | #: gtkspellcheck/oxt_extract.py:242
23 | msgid "extension \"{}\" is not a valid ZIP file"
24 | msgstr ""
25 |
26 | #: gtkspellcheck/oxt_extract.py:248
27 | msgid "extension \"{}\" has no valid XML dictionary registry"
28 | msgstr ""
29 |
30 | #: gtkspellcheck/oxt_extract.py:268
31 | msgid "unable to move extension, file with same name exists within move_path"
32 | msgstr ""
33 |
34 | #: gtkspellcheck/oxt_extract.py:276
35 | msgid "unable to move extension, move_path is not a directory"
36 | msgstr ""
37 |
38 | #: gtkspellcheck/spellcheck.py:467
39 | msgid "(no suggestions)"
40 | msgstr "(sin sugerencias)"
41 |
42 | #: gtkspellcheck/spellcheck.py:489 gtkspellcheck/spellcheck.py:492
43 | msgid "Add \"{}\" to Dictionary"
44 | msgstr "Agregar \"{}\" al Diccionario"
45 |
46 | #: gtkspellcheck/spellcheck.py:496 gtkspellcheck/spellcheck.py:498
47 | msgid "Ignore All"
48 | msgstr "Ignorar Todos"
49 |
50 | #: gtkspellcheck/spellcheck.py:513 gtkspellcheck/spellcheck.py:515
51 | msgid "Languages"
52 | msgstr "Idiomas"
53 |
54 | #: gtkspellcheck/spellcheck.py:527 gtkspellcheck/spellcheck.py:530
55 | msgid "Suggestions"
56 | msgstr "Sugerencias"
57 |
--------------------------------------------------------------------------------
/locale/nl/pygtkspellcheck.mo:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/koehlma/pygtkspellcheck/f872114f4b2d588dbcacca63a48e87a7fd04548f/locale/nl/pygtkspellcheck.mo
--------------------------------------------------------------------------------
/locale/nl/pygtkspellcheck.po:
--------------------------------------------------------------------------------
1 | msgid ""
2 | msgstr ""
3 | "Project-Id-Version: gtkspellchecker\n"
4 | "Report-Msgid-Bugs-To: \n"
5 | "POT-Creation-Date: 2002-01-29 15:32+0100\n"
6 | "PO-Revision-Date: 2020-01-29 15:32+0100\n"
7 | "Last-Translator: Pander\n"
8 | "Language-Team: \n"
9 | "Language: nl\n"
10 | "MIME-Version: 1.0\n"
11 | "Content-Type: text/plain; charset=UTF-8\n"
12 | "Content-Transfer-Encoding: 8bit\n"
13 | "X-Poedit-KeywordsList: _;gettext;gettext_noop\n"
14 | "X-Poedit-SourceCharset: UTF-8\n"
15 | "X-Poedit-SearchPath-0: ./gtkspellcheck\n"
16 |
17 | #: gtkspellcheck/spellcheck.py:98
18 | msgid "Unknown"
19 | msgstr "Onbekend"
20 |
21 | #: gtkspellcheck/spellcheck.py:480
22 | msgid "(no suggestions)"
23 | msgstr "(geen suggesties)"
24 |
25 | #: gtkspellcheck/spellcheck.py:502 gtkspellcheck/spellcheck.py:505
26 | msgid "Add \"{}\" to Dictionary"
27 | msgstr "Voeg \"{}\" toe aan woordenboek"
28 |
29 | #: gtkspellcheck/spellcheck.py:509 gtkspellcheck/spellcheck.py:511
30 | msgid "Ignore All"
31 | msgstr "Alles negeren"
32 |
33 | #: gtkspellcheck/spellcheck.py:526 gtkspellcheck/spellcheck.py:528
34 | msgid "Languages"
35 | msgstr "Talen"
36 |
37 | #: gtkspellcheck/spellcheck.py:544 gtkspellcheck/spellcheck.py:547
38 | msgid "Suggestions"
39 | msgstr "Suggesties"
40 |
41 | #: gtkspellcheck/oxt_extract.py:244
42 | msgid "extension \"{}\" is not a valid ZIP file"
43 | msgstr "extensie \"{}\" is geen ZIP-bestand"
44 |
45 | #: gtkspellcheck/oxt_extract.py:250
46 | msgid "extension \"{}\" has no valid XML dictionary registry"
47 | msgstr "extensie \"{}\" heeft gen geldige XML-woordenboekregister"
48 |
49 | #: gtkspellcheck/oxt_extract.py:270
50 | msgid "unable to move extension, file with same name exists within move_path"
51 | msgstr ""
52 | "niet mogelijk om extensie te verplaatsen, bestand met dezelfde naam als "
53 | "move_path bestaat al"
54 |
55 | #: gtkspellcheck/oxt_extract.py:278
56 | msgid "unable to move extension, move_path is not a directory"
57 | msgstr "niet mogelijk om extensie te verplaatsen, move_path is geen map"
58 |
--------------------------------------------------------------------------------
/placeholders/README.md:
--------------------------------------------------------------------------------
1 | # Placeholder Packages
2 |
3 | Python GTK Spellcheck is imported as `gtkspellcheck` and used to ship a package `pylocales`. Having different names for the PyPi package and the actual import is confusing for users can can be a security risk if someone publishes a package under one of the names. Hence, we reserve the packages `gtkspellcheck` and `pylocales` on PyPi.
--------------------------------------------------------------------------------
/placeholders/gtkspellcheck/README.md:
--------------------------------------------------------------------------------
1 | This package exists just to reserve the name `gtkspellcheck`. [Python GTK Spellcheck](https://pypi.org/project/pygtkspellcheck/) provides a package with this name.
--------------------------------------------------------------------------------
/placeholders/gtkspellcheck/gtkspellcheck/__init__.py:
--------------------------------------------------------------------------------
1 | raise ImportError("This is a placeholder module and should not be imported!")
2 |
--------------------------------------------------------------------------------
/placeholders/gtkspellcheck/pyproject.toml:
--------------------------------------------------------------------------------
1 | [tool.poetry]
2 | name = "gtkspellcheck"
3 | version = "0.0.0"
4 | description = "A placeholder for `pygtkspellcheck` which is imported as `gtkspellcheck`."
5 | authors = [
6 | "Maximilian Köhl "
7 | ]
8 | license = "GPL-3.0-or-later"
9 | readme = "README.md"
10 | repository = "https://github.com/koehlma/pygtkspellcheck.git"
11 | homepage = "https://github.com/koehlma/pygtkspellcheck"
12 |
13 | [tool.poetry.dependencies]
14 | python = "^3.7"
15 |
16 | [build-system]
17 | requires = ["poetry_core>=1.0.0"]
18 | build-backend = "poetry.core.masonry.api"
--------------------------------------------------------------------------------
/placeholders/pylocales/README.md:
--------------------------------------------------------------------------------
1 | This package exists just to reserve the name `pylocales`. [Python GTK Spellcheck](https://pypi.org/project/pygtkspellcheck/) used to provide a package with this name.
2 |
--------------------------------------------------------------------------------
/placeholders/pylocales/pylocales/__init__.py:
--------------------------------------------------------------------------------
1 | raise ImportError("This is a placeholder module and should not be imported!")
2 |
--------------------------------------------------------------------------------
/placeholders/pylocales/pyproject.toml:
--------------------------------------------------------------------------------
1 | [tool.poetry]
2 | name = "pylocales"
3 | version = "0.0.0"
4 | description = "A placeholder for `pylocales` which has been provided by `pygtkspellcheck`."
5 | authors = [
6 | "Maximilian Köhl "
7 | ]
8 | license = "GPL-3.0-or-later"
9 | readme = "README.md"
10 | repository = "https://github.com/koehlma/pygtkspellcheck.git"
11 | homepage = "https://github.com/koehlma/pygtkspellcheck"
12 |
13 | [tool.poetry.dependencies]
14 | python = "^3.7"
15 |
16 | [build-system]
17 | requires = ["poetry_core>=1.0.0"]
18 | build-backend = "poetry.core.masonry.api"
--------------------------------------------------------------------------------
/poetry.toml:
--------------------------------------------------------------------------------
1 | [virtualenvs]
2 | in-project = true
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [tool.poetry]
2 | name = "pygtkspellcheck"
3 | version = "5.0.3"
4 | description = "A simple but quite powerful spellchecking library for GTK written in pure Python."
5 | authors = ["Maximilian Köhl "]
6 | license = "GPL-3.0-or-later"
7 | readme = "README.md"
8 | repository = "https://github.com/koehlma/pygtkspellcheck.git"
9 | homepage = "https://github.com/koehlma/pygtkspellcheck"
10 | classifiers = [
11 | "Development Status :: 5 - Production/Stable",
12 | "Environment :: X11 Applications :: Gnome",
13 | "Environment :: X11 Applications :: GTK",
14 | "Intended Audience :: Developers",
15 | "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)",
16 | "Operating System :: MacOS",
17 | "Operating System :: Microsoft :: Windows",
18 | "Operating System :: POSIX",
19 | "Programming Language :: Python :: 3",
20 | "Topic :: Software Development :: Localization"
21 | ]
22 | packages = [
23 | { include = "gtkspellcheck", from = "src" }
24 | ]
25 |
26 | [tool.poetry.dependencies]
27 | python = "^3.7"
28 | pyenchant = "^3.0"
29 | PyGObject = "^3.42.1"
30 | sphinx = { version = "^4.5.0", optional = true }
31 | myst-parser = { version = "^0.18.0", optional = true }
32 |
33 | [tool.poetry.dev-dependencies]
34 | black = "^22.3.0"
35 | flake8 = "*"
36 | flake8-bugbear = "*"
37 | pep8-naming = "*"
38 | mypy = "*"
39 | sphinx-rtd-theme = "^1.0.0"
40 |
41 | [tool.poetry.extras]
42 | docs = ["sphinx", "myst-parser"]
43 |
44 | [build-system]
45 | requires = ["poetry_core>=1.0.0"]
46 | build-backend = "poetry.core.masonry.api"
47 |
--------------------------------------------------------------------------------
/setup.cfg:
--------------------------------------------------------------------------------
1 | [flake8]
2 | max-line-length = 99
3 | extend-ignore = E203,F811,E231
4 |
--------------------------------------------------------------------------------
/src/gtkspellcheck/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding:utf-8 -*-
2 | #
3 | # Copyright (C) 2012, Maximilian Köhl
4 | # Copyright (C) 2012, Carlos Jenkins
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 .
18 |
19 | from __future__ import unicode_literals
20 |
21 | __version__ = "4.0.5"
22 | __project__ = "Python GTK Spellcheck"
23 | __short_name__ = "pygtkspellcheck"
24 | __authors__ = "The Python GTK Spellcheck Authors"
25 | __emails__ = "linuxmaxi@googlemail.com & carlos@jenkins.co.cr"
26 | __website__ = "http://koehlma.github.com/projects/pygtkspellcheck.html"
27 | __download_url__ = "https://github.com/koehlma/pygtkspellcheck/tarball/master"
28 | __source__ = "https://github.com/koehlma/pygtkspellcheck/"
29 | __vcs__ = "git://github.com/koehlma/pygtkspellcheck.git"
30 | __copyright__ = "2012-2022, The Python GTK Spellcheck Authors"
31 | __desc_short__ = """
32 | A Python spell-checking library for GtkTextViews based on Enchant
33 | """
34 | __desc_long__ = """
35 | A simple but quite powerful spellchecking library written in pure Python for
36 | Gtk based on Enchant. It supports PyGObject as well as PyGtk for Python 2 and
37 | 3 with automatic switching and binding detection. For automatic translation of
38 | the user interface it can use Gedit’s translation files.
39 | """
40 | __metadata__ = {
41 | "__version__": __version__,
42 | "__project__": __project__,
43 | "__short_name__": __short_name__,
44 | "__authors__": __authors__,
45 | "__emails__": __emails__,
46 | "__website__": __website__,
47 | "__download_url__": __download_url__,
48 | "__source__": __source__,
49 | "__vcs__": __vcs__,
50 | "__copyright__": __copyright__,
51 | "__desc_short__": __desc_short__,
52 | "__desc_long__": __desc_long__,
53 | }
54 |
55 | from gtkspellcheck.spellcheck import (
56 | SpellChecker,
57 | NoDictionariesFound,
58 | )
59 |
60 | __all__ = ["SpellChecker", "NoDictionariesFound"]
61 |
--------------------------------------------------------------------------------
/src/gtkspellcheck/_oxt_extract.py:
--------------------------------------------------------------------------------
1 | # -*- coding:utf-8 -*-
2 | #
3 | # Copyright (C) 2012, Carlos Jenkins
4 | # Copyright (C) 2012-2016, Maximilian Köhl
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 .
18 |
19 | """
20 | This module extracts the .dic and .aff (Hunspell) dictionaries from any given
21 | .oxt extension.
22 |
23 | Extensions could be found at:
24 |
25 | http://extensions.services.openoffice.org/dictionary
26 | """
27 |
28 | import functools
29 | import gettext
30 | import logging
31 | import os
32 | import shutil
33 | import sys
34 | import warnings
35 | import xml.dom.minidom
36 | import xml.parsers.expat
37 | import zipfile
38 |
39 | # enable deprecation warnings
40 | warnings.simplefilter("always", DeprecationWarning)
41 |
42 | # public objects
43 | __all__ = [
44 | "extract",
45 | "batch_extract",
46 | "BadXml",
47 | "BadExtensionFile",
48 | "ExtractPathIsNoDirectory",
49 | "BATCH_SUCCESS",
50 | "BATCH_ERROR",
51 | "BATCH_WARNING",
52 | ]
53 |
54 | # logger
55 | logger = logging.getLogger(__name__)
56 |
57 | # translation
58 | locale_name = "py{}gtkspellcheck".format(sys.version_info.major)
59 | _ = gettext.translation(locale_name, fallback=True).gettext
60 |
61 |
62 | class BadXml(Exception):
63 | """
64 | The XML dictionary registry is not valid XML.
65 | """
66 |
67 |
68 | class BadExtensionFile(Exception):
69 | """
70 | The extension has a wrong file format, should be a ZIP file.
71 | """
72 |
73 |
74 | class ExtractPathIsNoDirectory(Exception):
75 | """
76 | The given `extract_path` is no directory.
77 | """
78 |
79 |
80 | def find_dictionaries(registry):
81 | def oor_name(name, element):
82 | return element.attributes["oor:name"].value.lower() == name
83 |
84 | def get_property(name, properties):
85 | property = list(filter(functools.partial(oor_name, name), properties))
86 | if property:
87 | return property[0].getElementsByTagName("value")[0]
88 |
89 | result = []
90 |
91 | # find all "node" elements which have "dictionaries" as "oor:name" attribute
92 | for dictionaries in filter(
93 | functools.partial(oor_name, "dictionaries"),
94 | registry.getElementsByTagName("node"),
95 | ):
96 | # for all "node" elements in this dictionary nodes
97 | for dictionary in dictionaries.getElementsByTagName("node"):
98 | # get all "prop" elements
99 | properties = dictionary.getElementsByTagName("prop")
100 | # get the format property as text
101 | format = get_property("format", properties).firstChild.data.strip()
102 | if format and format == "DICT_SPELL":
103 | # find the locations property
104 | locations = get_property("locations", properties)
105 | # if the location property is text:
106 | # %origin%/dictionary.aff %origin%/dictionary.dic
107 | if locations.firstChild.nodeType == xml.dom.Node.TEXT_NODE:
108 | locations = locations.firstChild.data
109 | locations = locations.replace("%origin%/", "").strip()
110 | result.append(locations.split())
111 | # otherwise:
112 | # %origin%/dictionary.aff%origin%/dictionary.dic
113 | else:
114 | locations = [
115 | item.firshChild.data.replace("%origin%/", "").strip()
116 | for item in locations.getElementsByTagName("it")
117 | ]
118 | result.append(locations)
119 |
120 | return result
121 |
122 |
123 | def extract(filename, target, override=False):
124 | """
125 | Extract Hunspell dictionaries out of LibreOffice ``.oxt`` extensions.
126 |
127 | :param filename: path to the ``.oxt`` extension
128 | :param target: path to extract Hunspell dictionaries to
129 | :param override: override existing files in the target directory
130 | :rtype: list of the extracted dictionaries
131 |
132 | This function extracts the Hunspell dictionaries (``.dic`` and ``.aff``
133 | files) from the given ``.oxt`` extension found to ``target``.
134 |
135 | Extensions could be found at:
136 |
137 | http://extensions.services.openoffice.org/dictionary
138 | """
139 | # TODO 5.0: remove this function
140 | warnings.warn(
141 | (
142 | 'call to deprecated function "{}", '
143 | 'moved to separate package "oxt_extract", '
144 | "will be removed in pygtkspellcheck 5.0"
145 | ).format(extract.__name__),
146 | stacklevel=2,
147 | category=DeprecationWarning,
148 | )
149 | try:
150 | with zipfile.ZipFile(filename, "r") as extension:
151 | files = extension.namelist()
152 |
153 | registry = "dictionaries.xcu"
154 | if registry not in files:
155 | for filename in files:
156 | if filename.lower().endswith(registry):
157 | registry = filename
158 |
159 | if registry in files:
160 | registry = xml.dom.minidom.parse(extension.open(registry))
161 | dictionaries = find_dictionaries(registry)
162 | extracted = []
163 | for dictionary in dictionaries:
164 | for filename in dictionary:
165 | dict_file = os.path.join(target, os.path.basename(filename))
166 | if not os.path.exists(dict_file) or (
167 | override and os.path.isfile(dict_file)
168 | ):
169 | if filename in files:
170 | with open(dict_file, "wb") as _target:
171 | with extension.open(filename, "r") as _source:
172 | extracted.append(os.path.basename(filename))
173 | _target.write(_source.read())
174 | else:
175 | logger.warning(
176 | "dictionary exists in registry "
177 | "but not in the extension zip"
178 | )
179 | else:
180 | logging.warning(
181 | (
182 | 'dictionary file "{}" already exists '
183 | "and not overriding it"
184 | ).format(dict_file)
185 | )
186 | return extracted
187 | except zipfile.BadZipfile:
188 | raise BadExtensionFile("extension is not a valid ZIP file")
189 | except xml.parsers.expat.ExpatError:
190 | raise BadXml("dictionary registry is not valid XML")
191 |
192 |
193 | BATCH_SUCCESS = "success"
194 | BATCH_ERROR = "error"
195 | BATCH_WARNING = "warning"
196 |
197 |
198 | def batch_extract(oxt_path, extract_path, override=False, move_path=None):
199 | """
200 | Uncompress, read and install LibreOffice ``.oxt`` dictionaries extensions.
201 |
202 | :param oxt_path: path to a directory containing the ``.oxt`` extensions
203 | :param extract_path: path to extract Hunspell dictionaries files to
204 | :param override: override already existing files
205 | :param move_path: optional path to move the ``.oxt`` files after processing
206 | :rtype: generator over all extensions, yielding result, extension name,
207 | error, extracted dictionaries and translated error message - result
208 | would be :const:`BATCH_SUCCESS` for success, :const:`BATCH_ERROR` if
209 | some error happened or :const:`BATCH_WARNING` which contain some warning
210 | messages instead of errors
211 |
212 | This function extracts the Hunspell dictionaries (``.dic`` and ``.aff``
213 | files) from all the ``.oxt`` extensions found on ``oxt_path`` directory to
214 | the ``extract_path`` directory.
215 |
216 | Extensions could be found at:
217 |
218 | http://extensions.services.openoffice.org/dictionary
219 |
220 | In detail, this functions does the following:
221 |
222 | 1. find all the ``.oxt`` extension files within ``oxt_path``
223 | 2. open (unzip) each extension
224 | 3. find the dictionary definition file within (*dictionaries.xcu*)
225 | 4. parse the dictionary definition file and locate the dictionaries files
226 | 5. uncompress those files to ``extract_path``
227 |
228 |
229 | By default file overriding is disabled, set ``override`` parameter to True
230 | if you want to enable it. As additional option, each processed extension can
231 | be moved to ``move_path``.
232 |
233 | Example::
234 |
235 | for result, name, error, dictionaries, message in oxt_extract.batch_extract(...):
236 | if result == oxt_extract.BATCH_SUCCESS:
237 | print('successfully extracted extension "{}"'.format(name))
238 | elif result == oxt_extract.BATCH_ERROR:
239 | print('could not extract extension "{}"'.format(name))
240 | print(message)
241 | print('error {}'.format(error))
242 | elif result == oxt_extract.BATCH_WARNING:
243 | print('warning during processing extension "{}"'.format(name))
244 | print(message)
245 | print(error)
246 |
247 | """
248 |
249 | # TODO 5.0: remove this function
250 | warnings.warn(
251 | (
252 | 'call to deprecated function "{}", '
253 | 'moved to separate package "oxt_extract", '
254 | "will be removed in pygtkspellcheck 5.0"
255 | ).format(extract.__name__),
256 | stacklevel=2,
257 | category=DeprecationWarning,
258 | )
259 |
260 | # get the real, absolute and normalized path
261 | oxt_path = os.path.normpath(os.path.abspath(os.path.realpath(oxt_path)))
262 |
263 | # check that the input directory exists
264 | if not os.path.isdir(oxt_path):
265 | return
266 |
267 | # create extract directory if not exists
268 | if not os.path.exists(extract_path):
269 | os.makedirs(extract_path)
270 |
271 | # check that the extract path is a directory
272 | if not os.path.isdir(extract_path):
273 | raise ExtractPathIsNoDirectory("extract path is not a valid directory")
274 |
275 | # get all .oxt extension at given path
276 | oxt_files = [
277 | extension
278 | for extension in os.listdir(oxt_path)
279 | if extension.lower().endswith(".oxt")
280 | ]
281 |
282 | for extension_name in oxt_files:
283 | extension_path = os.path.join(oxt_path, extension_name)
284 |
285 | try:
286 | dictionaries = extract(extension_path, extract_path, override)
287 | yield BATCH_SUCCESS, extension_name, None, dictionaries, ""
288 | except BadExtensionFile as error:
289 | logger.error(
290 | ('extension "{}" is not a valid ZIP file').format(extension_name)
291 | )
292 | yield (
293 | BATCH_ERROR,
294 | extension_name,
295 | error,
296 | [],
297 | _('extension "{}" is not a valid ZIP file').format(extension_name),
298 | )
299 | except BadXml as error:
300 | logger.error(
301 | ('extension "{}" has no valid XML dictionary registry').format(
302 | extension_name
303 | )
304 | )
305 | yield (
306 | BATCH_ERROR,
307 | extension_name,
308 | error,
309 | [],
310 | _('extension "{}" has no valid XML dictionary registry').format(
311 | extension_name
312 | ),
313 | )
314 |
315 | # move the extension after processing if user requires it
316 | if move_path is not None:
317 | # create move path if it doesn't exists
318 | if not os.path.exists(move_path):
319 | os.makedirs(move_path)
320 | # move to the given path only if it is a directory and target
321 | # doesn't exists
322 | if os.path.isdir(move_path):
323 | if (
324 | not os.path.exists(os.path.join(move_path, extension_name))
325 | or override
326 | ):
327 | shutil.move(extension_path, move_path)
328 | else:
329 | logger.warning(
330 | (
331 | "unable to move extension, file with same "
332 | "name exists within move_path"
333 | )
334 | )
335 | yield (
336 | BATCH_WARNING,
337 | extension_name,
338 | (
339 | "unable to move extension, file with same name "
340 | "exists within move_path"
341 | ),
342 | [],
343 | _(
344 | "unable to move extension, file with same name "
345 | "exists within move_path"
346 | ),
347 | )
348 | else:
349 | logger.warning(
350 | ("unable to move extension, move_path is not a " "directory")
351 | )
352 | yield (
353 | BATCH_WARNING,
354 | extension_name,
355 | ("unable to move extension, move_path is not a " "directory"),
356 | [],
357 | _("unable to move extension, move_path is not a " "directory"),
358 | )
359 |
--------------------------------------------------------------------------------
/src/gtkspellcheck/_pylocales/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding:utf-8 -*-
2 | #
3 | # Copyright (C) 2012, Maximilian Köhl
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 .
17 |
18 | from __future__ import unicode_literals
19 |
20 | __version__ = "1.2"
21 | __project__ = "Python Locales"
22 | __short_name__ = "pylocales"
23 | __authors__ = "Maximilian Köhl"
24 | __emails__ = "linuxmaxi@googlemail.com"
25 | __website__ = "http://koehlma.github.com/projects/pygtkspellcheck.html"
26 | __source__ = "https://github.com/koehlma/pygtkspellcheck/"
27 | __vcs__ = "git://github.com/koehlma/pygtkspellcheck.git"
28 | __copyright__ = "2012, Maximilian Köhl"
29 | __desc_short__ = "query the ISO 639/3166 database about a country or a language."
30 | __desc_long__ = (
31 | "Query the ISO 639/3166 database about a country or a"
32 | "language. The locales database contains ISO 639 language"
33 | "definitions and ISO 3166 country definitions. This package"
34 | "provides translation for country and language names if"
35 | "the iso-code messages are installed on your system."
36 | )
37 |
38 | __metadata__ = {
39 | "__version__": __version__,
40 | "__project__": __project__,
41 | "__short_name__": __short_name__,
42 | "__authors__": __authors__,
43 | "__emails__": __emails__,
44 | "__website__": __website__,
45 | "__source__": __source__,
46 | "__vcs__": __vcs__,
47 | "__copyright__": __copyright__,
48 | "__desc_short__": __desc_short__,
49 | "__desc_long__": __desc_long__,
50 | }
51 |
52 | from .locales import (
53 | Country,
54 | Language,
55 | LanguageNotFound,
56 | CountryNotFound,
57 | code_to_name,
58 | )
59 |
60 | __all__ = ["Country", "Language", "LanguageNotFound", "CountryNotFound", "code_to_name"]
61 |
--------------------------------------------------------------------------------
/src/gtkspellcheck/_pylocales/locales.db:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/koehlma/pygtkspellcheck/f872114f4b2d588dbcacca63a48e87a7fd04548f/src/gtkspellcheck/_pylocales/locales.db
--------------------------------------------------------------------------------
/src/gtkspellcheck/_pylocales/locales.py:
--------------------------------------------------------------------------------
1 | # -*- coding:utf-8 -*-
2 | #
3 | # Copyright (C) 2012, Maximilian Köhl
4 | # Copyright (C) 2012, Carlos Jenkins
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 .
18 |
19 | """
20 | Query the ISO 639/3166 database about a country or a language. The locales
21 | database contains ISO 639 language definitions and ISO 3166 country definitions.
22 | This package provides translation for country and language names if the
23 | iso-code messages are installed on your system.
24 | """
25 |
26 | import gettext
27 | import logging
28 | import os
29 | import sqlite3
30 | import sys
31 |
32 | # public objects
33 | __all__ = ["Country", "Language", "LanguageNotFound", "CountryNotFound", "code_to_name"]
34 |
35 | # translation
36 | _translator_language = gettext.translation("iso_639", fallback=True).gettext
37 | _translator_country = gettext.translation("iso_3166", fallback=True).gettext
38 |
39 | # Decides where the database is located. If an application provides an
40 | # os.path.get_module_path monkey patch to determine the path where the module
41 | # is located it uses this. If not it searches in the directory of this source
42 | # code file.
43 | __path__ = None
44 | if hasattr(os.path, "get_module_path"):
45 | __path__ = os.path.get_module_path(__file__)
46 | if not os.path.isfile(os.path.join(__path__, "locales.db")):
47 | __path__ = None
48 | if __path__ is None:
49 | frozen = getattr(sys, "frozen", None)
50 | if frozen in ("dll", "console_exe", "windows_exe"):
51 | __path__ = os.path.abspath(os.path.dirname(sys.executable))
52 | elif frozen == "macosx_app":
53 | __path__ = os.path.abspath(os.environ["RESOURCEPATH"])
54 | elif frozen is True:
55 | # Handle executables produced by PyInstaller.
56 | __path__ = sys._MEIPASS
57 | else:
58 | __path__ = os.path.abspath(os.path.realpath(os.path.dirname(__file__)))
59 |
60 |
61 | # loading the database
62 | _database = sqlite3.connect(os.path.join(__path__, "locales.db"))
63 |
64 | logger = logging.getLogger(__name__)
65 |
66 |
67 | class LanguageNotFound(Exception):
68 | """
69 | The specified language wasn't found in the database.
70 | """
71 |
72 |
73 | class CountryNotFound(Exception):
74 | """
75 | The specified country wasn't found in the database.
76 | """
77 |
78 |
79 | class Country(object):
80 | def __init__(self, rowid):
81 | country = _database.execute(
82 | "SELECT * FROM countries WHERE rowid == ?", (rowid,)
83 | ).fetchone()
84 | self.name = country[0]
85 | self.official_name = country[1]
86 | self.alpha_2 = country[2]
87 | self.alpha_3 = country[3]
88 | self.numeric = country[4]
89 | self.translation = _translator_country(self.name)
90 |
91 | @classmethod
92 | def get_country(cls, code, codec):
93 | country = _database.execute(
94 | "SELECT rowid FROM countries WHERE %s == ?" % (codec), (code,)
95 | ).fetchone()
96 | if country:
97 | return cls(country[0])
98 | raise CountryNotFound("code: %s, codec: %s" % (code, codec))
99 |
100 | @classmethod
101 | def by_alpha_2(cls, code):
102 | return Country.get_country(code, "alpha_2")
103 |
104 | @classmethod
105 | def by_alpha_3(cls, code):
106 | return Country.get_country(code, "alpha_3")
107 |
108 | @classmethod
109 | def by_numeric(cls, code):
110 | return Country.get_country(code, "numeric")
111 |
112 |
113 | class Language(object):
114 | def __init__(self, rowid):
115 | language = _database.execute(
116 | "SELECT * FROM languages WHERE rowid == ?", (rowid,)
117 | ).fetchone()
118 | self.name = language[0]
119 | self.iso_639_2B = language[1]
120 | self.iso_639_2T = language[2]
121 | self.iso_639_1 = language[3]
122 | self.translation = _translator_language(self.name)
123 |
124 | @classmethod
125 | def get_language(cls, code, codec):
126 | language = _database.execute(
127 | "SELECT rowid FROM languages WHERE %s == ?" % (codec), (code,)
128 | ).fetchone()
129 | if language:
130 | return cls(language[0])
131 | raise LanguageNotFound("code: %s, codec: %s" % (code, codec))
132 |
133 | @classmethod
134 | def by_iso_639_2b(cls, code):
135 | return Language.get_language(code, "iso_639_2B")
136 |
137 | @classmethod
138 | def by_iso_639_2t(cls, code):
139 | return Language.get_language(code, "iso_639_2T")
140 |
141 | @classmethod
142 | def by_iso_639_1(cls, code):
143 | return Language.get_language(code, "iso_639_1")
144 |
145 |
146 | def code_to_name(code, separator="_"):
147 | """
148 | Get the human readable and translated name of a language based on it's code.
149 |
150 | :param code: the code of the language (e.g. de_DE, en_US)
151 | :param target: separator used to separate language from country
152 | :rtype: human readable and translated language name
153 | """
154 | logger.debug('requesting name for code "{}"'.format(code))
155 | code = code.split(separator)
156 | if len(code) > 1:
157 | lang = Language.by_iso_639_1(code[0]).translation
158 | country = Country.by_alpha_2(code[1]).translation
159 | return "{} ({})".format(lang, country)
160 | else:
161 | return Language.by_iso_639_1(code[0]).translation
162 |
--------------------------------------------------------------------------------
/src/gtkspellcheck/spellcheck.py:
--------------------------------------------------------------------------------
1 | # -*- coding:utf-8 -*-
2 | #
3 | # Copyright (C) 2012, Maximilian Köhl
4 | # Copyright (C) 2012, Carlos Jenkins
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 .
18 |
19 | """
20 | A simple but quite powerful spellchecking library written in pure Python for Gtk
21 | based on Enchant. It supports both GTK 3 and 4 via PyGObject with Python 3. For
22 | automatic 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 | from collections import UserList
31 |
32 | from ._pylocales import code_to_name as _code_to_name
33 | from ._pylocales import LanguageNotFound, CountryNotFound
34 |
35 | from gi.repository import Gio, GLib, GObject
36 |
37 | # find any loaded gtk binding
38 | if "gi.repository.Gtk" in sys.modules:
39 | Gtk = sys.modules["gi.repository.Gtk"]
40 | else:
41 | import gi
42 |
43 | gi.require_version("Gtk", "3.0")
44 | from gi.repository import Gtk # noqa: N813
45 |
46 | _IS_GTK3 = Gtk.MAJOR_VERSION < 4
47 |
48 | # public objects
49 | __all__ = ["SpellChecker", "NoDictionariesFound"]
50 |
51 | # logger
52 | logger = logging.getLogger(__name__)
53 |
54 |
55 | class NoDictionariesFound(Exception):
56 | """
57 | There aren't any dictionaries installed on the current system so
58 | spellchecking could not work in any way.
59 | """
60 |
61 |
62 | # map between Gedit's translation and PyGtkSpellcheck's
63 | _GEDIT_MAP = {
64 | "Languages": "Languages",
65 | "Ignore All": "Ignore _All",
66 | "Suggestions": "Suggestions",
67 | "(no suggestions)": "(no suggested words)",
68 | "Add to Dictionary": "Add w_ord",
69 | "Unknown": "Unknown",
70 | }
71 |
72 | _BATCHING_THRESHOLD_CHARS = 1500
73 | _BATCH_SIZE_CHARS = 1000
74 |
75 | # translation
76 | if gettext.find("gedit"):
77 | _gedit = gettext.translation("gedit", fallback=True).gettext
78 |
79 | def _(message):
80 | return _gedit(_GEDIT_MAP[message]).replace("_", "")
81 |
82 | else:
83 | locale_name = "py{}gtkspellcheck".format(sys.version_info.major)
84 | _ = gettext.translation(locale_name, fallback=True).gettext
85 |
86 |
87 | def code_to_name(code, separator="_"):
88 | try:
89 | return _code_to_name(code, separator)
90 | except (LanguageNotFound, CountryNotFound):
91 | return "{} ({})".format(_("Unknown"), code)
92 |
93 |
94 | class SpellChecker(GObject.Object):
95 | """
96 | Main spellchecking class, everything important happens here.
97 |
98 | :param view: GtkTextView the SpellChecker should be attached to.
99 | :param language: The language which should be used for spellchecking.
100 | Use a combination of two letter lower-case ISO 639 language code with a
101 | two letter upper-case ISO 3166 country code, for example en_US or de_DE.
102 | :param prefix: A prefix for some internal GtkTextMarks.
103 | :param collapse: Enclose suggestions in its own menu.
104 | :param params: Dictionary with Enchant broker parameters that should be set
105 | e.g. `enchant.myspell.dictionary.path`.
106 |
107 | .. attribute:: languages
108 |
109 | A list of supported languages.
110 |
111 | .. function:: exists(language)
112 |
113 | Checks if a language exists.
114 |
115 | :param language: language to check
116 | """
117 |
118 | FILTER_WORD = "word"
119 | FILTER_LINE = "line"
120 | FILTER_TEXT = "text"
121 |
122 | DEFAULT_FILTERS = {
123 | FILTER_WORD: [r"[0-9.,]+"],
124 | FILTER_LINE: [
125 | (r"(https?|ftp|file):((//)|(\\\\))+[\w\d:" r"#@%/;$()~_?+-=\\.&]+"),
126 | r"[\w\d]+@[\w\d.]+",
127 | ],
128 | FILTER_TEXT: [],
129 | }
130 |
131 | DEFAULT_EXTRA_CHARS = "'"
132 |
133 | class _LanguageList(UserList):
134 | def __init__(self, *args, **kwargs):
135 | super().__init__(*args, **kwargs)
136 | self.mapping = dict(self)
137 |
138 | @classmethod
139 | def from_broker(cls, broker):
140 | return cls(
141 | sorted(
142 | [
143 | (language, code_to_name(language))
144 | for language in broker.list_languages()
145 | ],
146 | key=lambda language: language[1],
147 | )
148 | )
149 |
150 | def exists(self, language):
151 | return language in self.mapping
152 |
153 | class _Mark:
154 | def __init__(self, buffer, name, start, iter_worker):
155 | self._buffer = buffer
156 | self._name = name
157 | self._mark = self._buffer.create_mark(self._name, start, True)
158 | self._iter_worker = iter_worker
159 |
160 | @property
161 | def iter(self):
162 | return self._buffer.get_iter_at_mark(self._mark)
163 |
164 | @property
165 | def inside_word(self):
166 | return self._iter_worker.inside_word(self.iter)
167 |
168 | @property
169 | def word(self):
170 | start = self.iter
171 | if not self._iter_worker.starts_word(start):
172 | self._iter_worker.backward_word_start(start)
173 | end = self.iter
174 | if self._iter_worker.inside_word(end):
175 | self._iter_worker.forward_word_end(end)
176 | return start, end
177 |
178 | def move(self, location):
179 | self._buffer.move_mark(self._mark, location)
180 |
181 | class _IterWorker:
182 | def __init__(self, extra_word_chars):
183 | self._extra_word_chars = extra_word_chars
184 |
185 | def is_extra_word_char(self, loc):
186 | # Language extra chararacters should also be processed once Enchant's
187 | # enchant_dict_get_extra_word_characters is exposed in PyEnchant
188 |
189 | char = loc.get_char()
190 | return char != "" and char in self._extra_word_chars
191 |
192 | def inside_word(self, loc):
193 | if loc.inside_word():
194 | return True
195 | elif self.starts_word(loc):
196 | return True
197 | elif loc.ends_word() and not self.ends_word(loc):
198 | return True
199 | else:
200 | return False
201 |
202 | def starts_word(self, loc):
203 | if loc.starts_word():
204 | if loc.is_start():
205 | return True
206 | else:
207 | tmp = loc.copy()
208 | tmp.backward_char()
209 | return not self.is_extra_word_char(tmp)
210 | else:
211 | return False
212 |
213 | def ends_word(self, loc):
214 | if loc.ends_word():
215 | if loc.is_end():
216 | return True
217 | else:
218 | tmp = loc.copy()
219 | tmp.forward_char()
220 | return not self.is_extra_word_char(tmp)
221 | else:
222 | return False
223 |
224 | def forward_word_end(self, loc):
225 | def move_through_extra_chars():
226 | moved = False
227 | while self.is_extra_word_char(loc):
228 | if not loc.forward_char():
229 | break
230 | moved = True
231 | return moved
232 |
233 | tmp = loc.copy()
234 | tmp.backward_char()
235 | loc.forward_word_end()
236 | while move_through_extra_chars():
237 | if loc.is_end() or not loc.inside_word() or not loc.forward_word_end():
238 | break
239 |
240 | def backward_word_start(self, loc):
241 | def move_through_extra_chars():
242 | tmp = loc.copy()
243 | tmp.backward_char()
244 | moved = False
245 | while self.is_extra_word_char(tmp):
246 | moved = True
247 | loc.assign(tmp)
248 | if not tmp.backward_char():
249 | break
250 | return moved
251 |
252 | loc.backward_word_start()
253 | while move_through_extra_chars():
254 | tmp = loc.copy()
255 | tmp.backward_char()
256 | if (
257 | loc.is_start()
258 | or not tmp.inside_word()
259 | or not loc.backward_word_start()
260 | ):
261 | break
262 |
263 | def sync_extra_chars(self, obj, value):
264 | self._extra_word_chars = obj.extra_chars
265 |
266 | def __init__(
267 | self, view, language="en", prefix="gtkspellchecker", collapse=True, params=None
268 | ):
269 | super().__init__()
270 | self._view = view
271 | self.collapse = collapse
272 | # GTK 3-only signals. GTK 4 uses actions, below.
273 | if _IS_GTK3:
274 | self._view.connect(
275 | "populate-popup", lambda entry, menu: self.populate_menu(menu)
276 | )
277 | self._view.connect("popup-menu", self._click_move_popup)
278 | self._view.connect("button-press-event", self._click_move_button)
279 | self._prefix = prefix
280 | self._broker = enchant.Broker()
281 | if params is not None:
282 | for param, value in params.items():
283 | self._broker.set_param(param, value)
284 | self.languages = SpellChecker._LanguageList.from_broker(self._broker)
285 | if self.languages.exists(language):
286 | self._language = language
287 | elif self.languages.exists("en"):
288 | logger.warning(
289 | (
290 | 'no installed dictionary for language "{}", '
291 | "fallback to english".format(language)
292 | )
293 | )
294 | self._language = "en"
295 | else:
296 | if self.languages:
297 | self._language = self.languages[0][0]
298 | logger.warning(
299 | (
300 | 'no installed dictionary for language "{}" '
301 | "and english, fallback to first language in"
302 | 'language list ("{}")'
303 | ).format(language, self._language)
304 | )
305 | else:
306 | logger.critical("no dictionaries found")
307 | raise NoDictionariesFound()
308 | self._dictionary = self._broker.request_dict(self._language)
309 | self._deferred_check = False
310 | self._filters = dict(SpellChecker.DEFAULT_FILTERS)
311 | self._regexes = {
312 | SpellChecker.FILTER_WORD: re.compile(
313 | "|".join(self._filters[SpellChecker.FILTER_WORD])
314 | ),
315 | SpellChecker.FILTER_LINE: re.compile(
316 | "|".join(self._filters[SpellChecker.FILTER_LINE])
317 | ),
318 | SpellChecker.FILTER_TEXT: re.compile(
319 | "|".join(self._filters[SpellChecker.FILTER_TEXT]), re.MULTILINE
320 | ),
321 | }
322 |
323 | self._extra_chars = SpellChecker.DEFAULT_EXTRA_CHARS
324 | self._iter_worker = SpellChecker._IterWorker(self._extra_chars)
325 | self.connect("notify::extra-chars", self._iter_worker.sync_extra_chars)
326 |
327 | self._batched_rechecking = False
328 |
329 | self._languages_menu = None
330 | # GTK 4-only extra menu population, gesture creation and action setup. GTK 3
331 | # uses signals, above.
332 | if not _IS_GTK3:
333 | extra_menu = self._view.get_extra_menu()
334 | if extra_menu is None:
335 | extra_menu = Gio.Menu()
336 | self._view.set_extra_menu(extra_menu)
337 | self._spelling_menu = Gio.Menu()
338 | extra_menu.append_section(None, self._spelling_menu)
339 |
340 | controller = Gtk.GestureClick()
341 | controller.set_button(0)
342 | controller.connect("pressed", self._gtk4_on_textview_click)
343 | self._view.add_controller(controller)
344 |
345 | self._gtk4_setup_actions()
346 |
347 | self._enabled = True
348 | self.buffer_initialize()
349 |
350 | @GObject.Property(type=str, default="")
351 | def language(self):
352 | """
353 | The language used for spellchecking.
354 | """
355 | return self._language
356 |
357 | @language.setter
358 | def language(self, language):
359 | if language != self._language and self.languages.exists(language):
360 | self._language = language
361 | self._dictionary = self._broker.request_dict(language)
362 | self.recheck()
363 |
364 | @GObject.Property(type=bool, default=False)
365 | def enabled(self):
366 | """
367 | Enable or disable spellchecking.
368 | """
369 | return self._enabled
370 |
371 | @enabled.setter
372 | def enabled(self, enabled):
373 | if enabled and not self._enabled:
374 | self.enable()
375 | elif not enabled and self._enabled:
376 | self.disable()
377 |
378 | @GObject.Property(type=bool, default=False)
379 | def batched_rechecking(self):
380 | """
381 | Whether to enable batched rechecking of large buffers.
382 | """
383 | return self._batched_rechecking
384 |
385 | @batched_rechecking.setter
386 | def batched_rechecking(self, val):
387 | self._batched_rechecking = val
388 |
389 | @GObject.Property(type=str, default=",")
390 | def extra_chars(self):
391 | """
392 | Fetch the list of extra characters beyond which words are extended.
393 | """
394 | return self._extra_chars
395 |
396 | @extra_chars.setter
397 | def extra_chars(self, chars):
398 | """
399 | Set the list of extra characters beyond which words are extended.
400 |
401 | :param val: String containing list of characters
402 | """
403 | self._extra_chars = chars
404 |
405 | def buffer_initialize(self):
406 | """
407 | Initialize the GtkTextBuffer associated with the GtkTextView. If you
408 | have associated a new GtkTextBuffer with the GtkTextView call this
409 | method.
410 | """
411 | self._misspelled = Gtk.TextTag.new("{}-misspelled".format(self._prefix))
412 | self._misspelled.set_property("underline", 4)
413 | self._buffer = self._view.get_buffer()
414 | self._buffer.connect("insert-text", self._before_text_insert)
415 | self._buffer.connect_after("insert-text", self._after_text_insert)
416 | self._buffer.connect_after("delete-range", self._range_delete)
417 | self._buffer.connect_after("mark-set", self._mark_set)
418 | start = self._buffer.get_bounds()[0]
419 | self._marks = {
420 | "insert-start": SpellChecker._Mark(
421 | self._buffer,
422 | "{}-insert-start".format(self._prefix),
423 | start,
424 | self._iter_worker,
425 | ),
426 | "insert-end": SpellChecker._Mark(
427 | self._buffer,
428 | "{}-insert-end".format(self._prefix),
429 | start,
430 | self._iter_worker,
431 | ),
432 | "click": SpellChecker._Mark(
433 | self._buffer, "{}-click".format(self._prefix), start, self._iter_worker
434 | ),
435 | }
436 | self._table = self._buffer.get_tag_table()
437 | self._table.add(self._misspelled)
438 | self.ignored_tags = []
439 |
440 | def tag_added(tag, *args):
441 | if hasattr(tag, "spell_check") and not tag.spell_check:
442 | self.ignored_tags.append(tag)
443 |
444 | def tag_removed(tag, *args):
445 | if tag in self.ignored_tags:
446 | self.ignored_tags.remove(tag)
447 |
448 | self._table.connect("tag-added", tag_added)
449 | self._table.connect("tag-removed", tag_removed)
450 | self._table.foreach(tag_added, None)
451 | self.no_spell_check = self._table.lookup("no-spell-check")
452 | if not self.no_spell_check:
453 | self.no_spell_check = Gtk.TextTag.new("no-spell-check")
454 | self._table.add(self.no_spell_check)
455 | self.recheck()
456 |
457 | def recheck(self):
458 | """
459 | Rechecks the spelling of the whole text.
460 | """
461 | start, end = self._buffer.get_bounds()
462 |
463 | if self._batched_rechecking and end.get_offset() > _BATCHING_THRESHOLD_CHARS:
464 | start_mark = self._buffer.create_mark(None, start)
465 | self._continue_batched_recheck(start_mark)
466 | else:
467 | self.check_range(start, end, True)
468 |
469 | def disable(self):
470 | """
471 | Disable spellchecking.
472 | """
473 | self._enabled = False
474 | start, end = self._buffer.get_bounds()
475 | self._buffer.remove_tag(self._misspelled, start, end)
476 |
477 | def enable(self):
478 | """
479 | Enable spellchecking.
480 | """
481 | self._enabled = True
482 | self.recheck()
483 |
484 | def append_filter(self, regex, filter_type):
485 | """
486 | Append a new filter to the filter list. Filters are useful to ignore
487 | some misspelled words based on regular expressions.
488 |
489 | :param regex: The regex used for filtering.
490 | :param filter_type: The type of the filter.
491 |
492 | Filter Types:
493 |
494 | :const:`SpellChecker.FILTER_WORD`: The regex must match the whole word
495 | you want to filter. The word separation is done by Pango's word
496 | separation algorithm so, for example, urls won't work here because
497 | they are split in many words.
498 |
499 | :const:`SpellChecker.FILTER_LINE`: If the expression you want to match
500 | is a single line expression use this type. It should not be an open
501 | end expression because then the rest of the line with the text you
502 | want to filter will become correct.
503 |
504 | :const:`SpellChecker.FILTER_TEXT`: Use this if you want to filter
505 | multiline expressions. The regex will be compiled with the
506 | `re.MULTILINE` flag. Same with open end expressions apply here.
507 | """
508 | self._filters[filter_type].append(regex)
509 | if filter_type == SpellChecker.FILTER_TEXT:
510 | self._regexes[filter_type] = re.compile(
511 | "|".join(self._filters[filter_type]), re.MULTILINE
512 | )
513 | else:
514 | self._regexes[filter_type] = re.compile(
515 | "|".join(self._filters[filter_type])
516 | )
517 |
518 | def remove_filter(self, regex, filter_type):
519 | """
520 | Remove a filter from the filter list.
521 |
522 | :param regex: The regex which used for filtering.
523 | :param filter_type: The type of the filter.
524 | """
525 | self._filters[filter_type].remove(regex)
526 | if filter_type == SpellChecker.FILTER_TEXT:
527 | self._regexes[filter_type] = re.compile(
528 | "|".join(self._filters[filter_type]), re.MULTILINE
529 | )
530 | else:
531 | self._regexes[filter_type] = re.compile(
532 | "|".join(self._filters[filter_type])
533 | )
534 |
535 | def append_ignore_tag(self, tag):
536 | """
537 | Appends a tag to the list of ignored tags. A string will be automatic
538 | resolved into a tag object.
539 |
540 | :param tag: Tag object or tag name.
541 | """
542 | if isinstance(tag, str):
543 | tag = self._table.lookup(tag)
544 | self.ignored_tags.append(tag)
545 |
546 | def remove_ignore_tag(self, tag):
547 | """
548 | Removes a tag from the list of ignored tags. A string will be automatic
549 | resolved into a tag object.
550 |
551 | :param tag: Tag object or tag name.
552 | """
553 | if isinstance(tag, str):
554 | tag = self._table.lookup(tag)
555 | self.ignored_tags.remove(tag)
556 |
557 | def add_to_dictionary(self, word):
558 | """
559 | Adds a word to user's dictionary.
560 |
561 | :param word: The word to add.
562 | """
563 | self._dictionary.add_to_pwl(word)
564 | self.recheck()
565 |
566 | def ignore_all(self, word):
567 | """
568 | Ignores a word for the current session.
569 |
570 | :param word: The word to ignore.
571 | """
572 | self._dictionary.add_to_session(word)
573 | self.recheck()
574 |
575 | def check_range(self, start, end, force_all=False):
576 | """
577 | Checks a specified range between two GtkTextIters.
578 |
579 | :param start: Start iter - checking starts here.
580 | :param end: End iter - checking ends here.
581 | """
582 | logger.debug(
583 | "Check range called with range %d:%d to %d:%d and force all set to %s.",
584 | start.get_line(),
585 | start.get_line_offset(),
586 | end.get_line(),
587 | end.get_line_offset(),
588 | force_all,
589 | )
590 | if not self._enabled:
591 | return
592 | start = start.copy()
593 | end = end.copy()
594 | if self._iter_worker.inside_word(end):
595 | self._iter_worker.forward_word_end(end)
596 | if self._iter_worker.inside_word(start) or self._iter_worker.ends_word(start):
597 | self._iter_worker.backward_word_start(start)
598 | if not self._iter_worker.starts_word(start):
599 | self._iter_worker.forward_word_end(start)
600 | self._iter_worker.backward_word_start(start)
601 | self._buffer.remove_tag(self._misspelled, start, end)
602 | cursor = self._buffer.get_iter_at_mark(self._buffer.get_insert())
603 | precursor = cursor.copy()
604 | precursor.backward_char()
605 | highlight = cursor.has_tag(self._misspelled) or precursor.has_tag(
606 | self._misspelled
607 | )
608 | word_start = start.copy()
609 | while word_start.compare(end) < 0:
610 | word_end = word_start.copy()
611 | self._iter_worker.forward_word_end(word_end)
612 | in_word = (word_start.compare(cursor) < 0) and (
613 | cursor.compare(word_end) <= 0
614 | )
615 | if in_word and not force_all:
616 | if highlight:
617 | self._check_word(word_start, word_end)
618 | else:
619 | self._deferred_check = True
620 | else:
621 | self._check_word(word_start, word_end)
622 | self._deferred_check = False
623 | self._iter_worker.forward_word_end(word_end)
624 | self._iter_worker.backward_word_start(word_end)
625 | if word_start.equal(word_end):
626 | break
627 | word_start = word_end.copy()
628 |
629 | def populate_menu(self, menu):
630 | """
631 | Populate the provided menu with spelling items.
632 |
633 | :param menu: The menu to populate.
634 | """
635 | # In GTK 4 our existing menu needs to be cleared, providing for disabling
636 | if not _IS_GTK3:
637 | menu.remove_all()
638 |
639 | if not self._enabled:
640 | return
641 |
642 | if _IS_GTK3:
643 | separator = Gtk.SeparatorMenuItem.new()
644 | separator.show()
645 | menu.prepend(separator)
646 | languages = Gtk.MenuItem.new_with_label(_("Languages"))
647 | languages.set_submenu(self._get_languages_menu())
648 | languages.show_all()
649 | menu.prepend(languages)
650 | else:
651 | menu.append_item(self._get_languages_menu())
652 |
653 | if self._marks["click"].inside_word:
654 | start, end = self._marks["click"].word
655 | if start.has_tag(self._misspelled):
656 | word = self._buffer.get_text(start, end, False)
657 | items = self._suggestion_menu(word)
658 | if self.collapse:
659 | menu_label = _("Suggestions")
660 | if _IS_GTK3:
661 | suggestions = Gtk.MenuItem.new_with_label(menu_label)
662 | submenu = Gtk.Menu.new()
663 | else:
664 | suggestions = Gio.MenuItem.new(menu_label, None)
665 | submenu = Gio.Menu.new()
666 | for item in items:
667 | if _IS_GTK3:
668 | submenu.append(item)
669 | else:
670 | submenu.append_item(item)
671 | suggestions.set_submenu(submenu)
672 | if _IS_GTK3:
673 | suggestions.show_all()
674 | menu.prepend(suggestions)
675 | else:
676 | menu.prepend_item(suggestions)
677 | else:
678 | items.reverse()
679 | for item in items:
680 | if _IS_GTK3:
681 | menu.prepend(item)
682 | menu.show_all()
683 | else:
684 | menu.prepend_item(item)
685 |
686 | def move_click_mark(self, iter):
687 | """
688 | Move the "click" mark, used to determine the word being checked.
689 |
690 | :param iter: TextIter for the new location
691 | """
692 | self._marks["click"].move(iter)
693 |
694 | def _gtk4_setup_actions(self) -> None:
695 | action_group = Gio.SimpleActionGroup.new()
696 |
697 | action = Gio.SimpleAction.new("ignore-all", GLib.VariantType("s"))
698 | action.connect(
699 | "activate", lambda _action, word: self.ignore_all(word.get_string())
700 | )
701 | action_group.add_action(action)
702 |
703 | action = Gio.SimpleAction.new("add-to-dictionary", GLib.VariantType("s"))
704 | action.connect(
705 | "activate", lambda _action, word: self.add_to_dictionary(word.get_string())
706 | )
707 | action_group.add_action(action)
708 |
709 | action = Gio.SimpleAction.new("replace-word", GLib.VariantType("s"))
710 | action.connect(
711 | "activate",
712 | lambda _action, suggestion: self._replace_word(suggestion.get_string()),
713 | )
714 | action_group.add_action(action)
715 |
716 | language = Gio.PropertyAction.new("language", self, "language")
717 | action_group.add_action(language)
718 |
719 | self._view.insert_action_group("spelling", action_group)
720 |
721 | def _get_languages_menu(self):
722 | if _IS_GTK3:
723 | return self._build_languages_menu()
724 | else:
725 | if self._languages_menu is None:
726 | self._languages_menu = self._build_languages_menu()
727 | return self._languages_menu
728 |
729 | def _build_languages_menu(self):
730 | if _IS_GTK3:
731 |
732 | def _set_language(item, code):
733 | self.language = code
734 |
735 | menu = Gtk.Menu.new()
736 | group = []
737 | connect = []
738 | else:
739 | menu = Gio.Menu.new()
740 |
741 | for code, name in self.languages:
742 | if _IS_GTK3:
743 | item = Gtk.RadioMenuItem.new_with_label(group, name)
744 | group.append(item)
745 | if code == self.language:
746 | item.set_active(True)
747 | connect.append((item, code))
748 | menu.append(item)
749 | else:
750 | item = Gio.MenuItem.new(name, None)
751 | item.set_action_and_target_value(
752 | "spelling.language", GLib.Variant.new_string(code)
753 | )
754 | menu.append_item(item)
755 | if _IS_GTK3:
756 | for item, code in connect:
757 | item.connect("activate", _set_language, code)
758 | return menu
759 | else:
760 | return Gio.MenuItem.new_submenu(_("Languages"), menu)
761 |
762 | def _suggestion_menu(self, word):
763 | menu = []
764 | suggestions = self._dictionary.suggest(word)
765 | if not suggestions:
766 | # Show GTK 3 no suggestions item (removed for GTK 4)
767 | if _IS_GTK3:
768 | item = Gtk.MenuItem.new()
769 | label = Gtk.Label.new("")
770 | try:
771 | label.set_halign(Gtk.Align.LEFT)
772 | except AttributeError:
773 | label.set_alignment(0.0, 0.5)
774 | label.set_markup("{text}".format(text=_("(no suggestions)")))
775 | item.add(label)
776 | menu.append(item)
777 | else:
778 | for suggestion in suggestions:
779 | if _IS_GTK3:
780 | item = Gtk.MenuItem.new()
781 | label = Gtk.Label.new("")
782 | label.set_markup("{text}".format(text=suggestion))
783 | try:
784 | label.set_halign(Gtk.Align.LEFT)
785 | except AttributeError:
786 | label.set_alignment(0.0, 0.5)
787 | item.add(label)
788 |
789 | def _make_on_activate(word):
790 | return lambda *args: self._replace_word(word)
791 |
792 | item.connect("activate", _make_on_activate(word))
793 | else:
794 | escaped = suggestion.replace("'", "\\'")
795 | item = Gio.MenuItem.new(
796 | suggestion, f"spelling.replace-word('{escaped}')"
797 | )
798 | menu.append(item)
799 | add_to_dict_menu_label = _("Add to Dictionary")
800 | word_escaped = word.replace("'", "\\'")
801 | if _IS_GTK3:
802 | menu.append(Gtk.SeparatorMenuItem.new())
803 | item = Gtk.MenuItem.new_with_label(add_to_dict_menu_label)
804 | item.connect("activate", lambda *args: self.add_to_dictionary(word))
805 | else:
806 | item = Gio.MenuItem.new(
807 | add_to_dict_menu_label, f"spelling.add-to-dictionary('{word_escaped}')"
808 | )
809 | menu.append(item)
810 | ignore_menu_label = _("Ignore All")
811 | if _IS_GTK3:
812 | item = Gtk.MenuItem.new_with_label(ignore_menu_label)
813 | item.connect("activate", lambda *args: self.ignore_all(word))
814 | else:
815 | item = Gio.MenuItem.new(
816 | ignore_menu_label, f"spelling.ignore-all('{word_escaped}')"
817 | )
818 | menu.append(item)
819 | return menu
820 |
821 | def _click_move_popup(self, *args):
822 | self.move_click_mark(self._buffer.get_iter_at_mark(self._buffer.get_insert()))
823 | return False
824 |
825 | def _click_move_button(self, widget, event):
826 | if event.button == 3:
827 | self._move_mark_for_input(event.x, event.y)
828 | return False
829 |
830 | def _move_mark_for_input(self, input_x, input_y):
831 | if self._deferred_check:
832 | self._check_deferred_range(True)
833 | x, y = self._view.window_to_buffer_coords(2, int(input_x), int(input_y))
834 | iter = self._view.get_iter_at_location(x, y)
835 | if isinstance(iter, tuple):
836 | iter = iter[1]
837 | self.move_click_mark(iter)
838 |
839 | def _gtk4_on_textview_click(self, click, n_press, x, y) -> None:
840 | if n_press != 1 or click.get_current_button() != 3:
841 | return
842 |
843 | self._move_mark_for_input(x, y)
844 | self.populate_menu(self._spelling_menu)
845 |
846 | def _before_text_insert(self, textbuffer, location, text, length):
847 | self._marks["insert-start"].move(location)
848 |
849 | def _after_text_insert(self, textbuffer, location, text, length):
850 | start = self._marks["insert-start"].iter
851 | self.check_range(start, location)
852 | self._marks["insert-end"].move(location)
853 |
854 | def _range_delete(self, textbuffer, start, end):
855 | self.check_range(start, end)
856 |
857 | def _mark_set(self, textbuffer, location, mark):
858 | if mark == self._buffer.get_insert() and self._deferred_check:
859 | self._check_deferred_range(False)
860 |
861 | def _replace_word(self, new_word):
862 | start, end = self._marks["click"].word
863 | old_word = start.get_text(end)
864 | offset = start.get_offset()
865 | self._buffer.begin_user_action()
866 | self._buffer.delete(start, end)
867 | self._buffer.insert(self._buffer.get_iter_at_offset(offset), new_word)
868 | self._buffer.end_user_action()
869 | self._dictionary.store_replacement(old_word, new_word)
870 |
871 | def _check_deferred_range(self, force_all):
872 | start = self._marks["insert-start"].iter
873 | end = self._marks["insert-end"].iter
874 | self.check_range(start, end, force_all)
875 |
876 | def _check_word(self, start, end):
877 | if start.has_tag(self.no_spell_check):
878 | return
879 | for tag in self.ignored_tags:
880 | if start.has_tag(tag):
881 | return
882 | word = self._buffer.get_text(start, end, False).strip()
883 | logger.debug(
884 | "Checking word %s in range %d:%d to %d:%d.",
885 | word,
886 | start.get_line(),
887 | start.get_line_offset(),
888 | end.get_line(),
889 | end.get_line_offset(),
890 | )
891 | if not word:
892 | return
893 | if len(self._filters[SpellChecker.FILTER_WORD]):
894 | if self._regexes[SpellChecker.FILTER_WORD].match(word):
895 | return
896 | if len(self._filters[SpellChecker.FILTER_LINE]):
897 | if _IS_GTK3:
898 | line_start = self._buffer.get_iter_at_line(start.get_line())
899 | else:
900 | _success, line_start = self._buffer.get_iter_at_line(start.get_line())
901 | line_end = end.copy()
902 | line_end.forward_to_line_end()
903 | line = self._buffer.get_text(line_start, line_end, False)
904 | for match in self._regexes[SpellChecker.FILTER_LINE].finditer(line):
905 | if match.start() <= start.get_line_offset() <= match.end():
906 | if _IS_GTK3:
907 | start = self._buffer.get_iter_at_line_offset(
908 | start.get_line(), match.start()
909 | )
910 | end = self._buffer.get_iter_at_line_offset(
911 | start.get_line(), match.end()
912 | )
913 | else:
914 | # Success is not verified here as the locations come directly
915 | # from the buffer
916 | _success, start = self._buffer.get_iter_at_line_offset(
917 | start.get_line(), match.start()
918 | )
919 | _success, end = self._buffer.get_iter_at_line_offset(
920 | start.get_line(), match.end()
921 | )
922 | self._buffer.remove_tag(self._misspelled, start, end)
923 | return
924 | if len(self._filters[SpellChecker.FILTER_TEXT]):
925 | text_start, text_end = self._buffer.get_bounds()
926 | text = self._buffer.get_text(text_start, text_end, False)
927 | for match in self._regexes[SpellChecker.FILTER_TEXT].finditer(text):
928 | if match.start() <= start.get_offset() <= match.end():
929 | start = self._buffer.get_iter_at_offset(match.start())
930 | end = self._buffer.get_iter_at_offset(match.end())
931 | self._buffer.remove_tag(self._misspelled, start, end)
932 | return
933 | if not self._dictionary.check(word):
934 | self._buffer.apply_tag(self._misspelled, start, end)
935 |
936 | def _continue_batched_recheck(self, start_mark):
937 | if start_mark.get_buffer() != self._buffer:
938 | return
939 | start = self._buffer.get_iter_at_mark(start_mark)
940 | self._buffer.delete_mark(start_mark)
941 |
942 | if not self._enabled:
943 | return
944 |
945 | end = start.copy()
946 | end.forward_chars(_BATCH_SIZE_CHARS)
947 | self._iter_worker.forward_word_end(end)
948 |
949 | self.check_range(start, end, True)
950 |
951 | if not end.is_end():
952 | end.forward_char()
953 | start_mark = self._buffer.create_mark(None, end)
954 | GLib.idle_add(self._continue_batched_recheck, start_mark)
955 |
--------------------------------------------------------------------------------
/utils/locales/build.py:
--------------------------------------------------------------------------------
1 | # -*- coding:utf-8 -*-
2 | #
3 | # Copyright (C) 2012, Maximilian Köhl
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 .
17 |
18 | import os.path
19 | import sqlite3
20 | from xml.etree import ElementTree as etree
21 |
22 |
23 | def build():
24 | databases = os.path.join(os.path.dirname(__file__), "databases")
25 | locales = os.path.join(os.path.dirname(__file__), "locales")
26 | languages = etree.parse(os.path.join(databases, "iso639.xml")).findall(
27 | "iso_639_entry"
28 | )
29 | countries = etree.parse(os.path.join(databases, "iso3166.xml")).findall(
30 | "iso_3166_entry"
31 | )
32 | database = sqlite3.connect(os.path.join(os.path.dirname(__file__), "locales.db"))
33 | database.execute(
34 | "CREATE TABLE countries (name, official_name, alpha_2, alpha_3, numeric)"
35 | )
36 | database.execute("CREATE TABLE languages (name, iso_639_2B, iso_639_2T, iso_639_1)")
37 | for country in countries:
38 | database.execute(
39 | "INSERT INTO countries VALUES (?, ?, ?, ?, ?)",
40 | (
41 | country.get("name"),
42 | country.get("official_name"),
43 | country.get("alpha_2_code"),
44 | country.get("alpha_3_code"),
45 | country.get("numeric_code"),
46 | ),
47 | )
48 |
49 | for language in languages:
50 | database.execute(
51 | "INSERT INTO languages VALUES (?, ?, ?, ?)",
52 | (
53 | language.get("name"),
54 | language.get("iso_639_2B_code"),
55 | language.get("iso_639_2T_code"),
56 | language.get("iso_639_1_code"),
57 | ),
58 | )
59 |
60 | database.commit()
61 | database.close()
62 |
63 |
64 | if __name__ == "__main__":
65 | build()
66 |
--------------------------------------------------------------------------------
/utils/oxt_extract_dictionaries.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding:utf-8 -*-
3 | #
4 | # Copyright (C) 2012, Maximilian Köhl
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 .
18 |
19 | import sys
20 | import argparse
21 |
22 | sys.modules["gtk"] = None
23 | import gtkspellcheck._oxt_extract
24 |
25 | if __name__ == "__main__":
26 | parser = argparse.ArgumentParser()
27 | parser.add_argument("extension", nargs="+", help="extension to extract")
28 | parser.add_argument("target", help="target directory")
29 |
30 | arguments = parser.parse_args()
31 | for extension in arguments.extension:
32 | try:
33 | gtkspellcheck._oxt_extract.extract(extension, arguments.target)
34 | except gtkspellcheck._oxt_extract.BadXml:
35 | print(
36 | gtkspellcheck._oxt_extract._(
37 | 'extension "{}" has no valid XML ' "dictionary registry"
38 | ).format(extension)
39 | )
40 | except gtkspellcheck._oxt_extract.BadExtensionFile:
41 | print(
42 | gtkspellcheck._oxt_extract._(
43 | 'extension "{}" is not a valid ' "ZIP file"
44 | ).format(extension)
45 | )
46 |
--------------------------------------------------------------------------------