├── .github
└── workflows
│ └── c-compile.yml
├── .gitignore
├── LICENSE
├── Makefile
├── README.org
├── dictzip.c
├── dictzip.h
├── elisp.c
├── format.c
├── format.h
├── gdcv.c
├── gdcv.el
├── index.c
├── index.h
├── utfproc
├── utf8proc.c
├── utf8proc.h
└── utf8proc_data.c
├── utils.c
├── utils.h
└── video
├── cli.gif
├── emacs.gif
└── ivy.gif
/.github/workflows/c-compile.yml:
--------------------------------------------------------------------------------
1 | name: C Build Test
2 |
3 | on:
4 | push:
5 | branches: [ "master"]
6 | pull_request:
7 | branches: [ "master" ]
8 |
9 | jobs:
10 | build:
11 |
12 | runs-on: ubuntu-latest
13 |
14 | steps:
15 | - uses: actions/checkout@v3
16 | - name: compile
17 | run: make gdcv
18 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /.ccls-cache/
2 | /gdcv
3 | /gdcv.org
4 | *.so
5 | /index
6 | /gdcv_debug
7 | /gmon.out
8 | /analysis.txt
9 | *.elc
10 | /Huge/
11 | /prof_output
12 | tests/Huge_Index
13 | tests/testsuite
14 | *.log
15 |
--------------------------------------------------------------------------------
/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 | .
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | CC=gcc
2 | #clang
3 | EMACS = emacs
4 | CFLAGS=$(pkg-config --cflags zlib) -Wall -Wextra -pedantic
5 | OPTIMISATIONS= -O2 -march=native
6 | LDLIBS=$(shell pkg-config --libs zlib)
7 | DEBUG=-fsanitize=address -O0 -g3 -ggdb -static-libasan
8 |
9 | .PHONY : test
10 |
11 | gdcv: gdcv.c dictzip.c utils.c format.c index.c utfproc/utf8proc.c
12 | $(CC) -o $@ $^ $(CFLAGS) $(LDLIBS) $(OPTIMISATIONS)
13 |
14 | emacs-module: gdcv-elisp.so gdcv.elc
15 |
16 | gdcv-elisp.so: elisp.c dictzip.c utils.c format.c index.c utfproc/utf8proc.c
17 | $(CC) -shared -o $@ -fPIC $^ $(CFLAGS) $(LDLIBS) $(OPTIMISATIONS)
18 |
19 | gdcv_debug: gdcv.c dictzip.c utils.c format.c index.c utfproc/utf8proc.c
20 | $(CC) -o $@ $^ $(CFLAGS) $(LDLIBS) $(DEBUG)
21 |
22 | clean:
23 | rm -f gdcv gdcv-elisp.so gdcv_debug gdcv.elc
24 |
25 | .SUFFIXES: .el .elc
26 | .el.elc:
27 | $(EMACS) -batch -Q -L . -f batch-byte-compile $<
28 |
--------------------------------------------------------------------------------
/README.org:
--------------------------------------------------------------------------------
1 | #+TITLE: gdcv - GoldenDict console version and emacs module
2 |
3 | * Description
4 | gdcv is a command-line interface for searching [[https://github.com/goldendict/goldendict][GoldenDict]] dictionaries(*.dsl.dz). The program is a very rudimentary workaround to allow searching until an official command-line interface is available.
5 |
6 | As an example of a similar interface, [[https://github.com/goldendict/goldendict][GoldenDict]] has [[https://github.com/dohliam/gdcl][gdcl]] (Command-line interface for Goldendict), but for my dictionary collection(10 GB) it works really slow due to no pre-made index for faster searching.
7 |
8 | [[http://code.google.com/p/stardict-3/][StarDict]] has [[http://sdcv.sourceforge.net/][sdcv]] (StarDict Console Version), but it can only handle dictionaries in the StarDict format. For users of GoldenDict who have large collections of dictionaries in DSL format, converting and maintaining two parallel sets of dictionaries is not a practical solution.
9 |
10 | gdcv does not require an installation of GoldenDict and does not use GoldenDict's pre-made index files, it creates new one.
11 |
12 | The main catch is that gdcv is written in C by a person who has never programmed anything before. It seems the program does not leak memory, but the software architecture is horrible.
13 |
14 | Please [[https://github.com/goldendict/goldendict/issues/37][vote]] for official command-line interface for GoldenDict.
15 |
16 | * Features
17 | + Search a word in a dictionary
18 | + Find words that contain a substring
19 | + Syntax highlighting
20 | + Extracting media files
21 | + Emacs dynamic module, if necessary
22 |
23 |
24 | * Installation
25 | ** Requirements
26 | 1. gcc or clang
27 | 2. zlib
28 | 3. unzip (in order to unpack resources in zip files)
29 | For Ubuntu:
30 | #+BEGIN_SRC sh
31 | sudo apt install zlib1g-dev unzip
32 | #+END_SRC
33 | ** Compilation
34 | #+BEGIN_SRC sh
35 | git clone https://github.com/konstare/gdcv
36 | cd gdcv
37 | make gdcv
38 | #+END_SRC
39 |
40 | Put gdcv into a directory from the $PATH.
41 |
42 | ** Configuration
43 | *** Convert dictionaries from UTF-16 to UTF-8
44 |
45 | Sometimes GoldenDict dictionaries (DSL) comes in UTF-16. It is above my pay-grade to deal with it, all dictionaries should be converted to UTF-8. It is not the problem for GoldenDict as it supports both UTF-16 and UTF-8. Moreover dictionaries in UTF-8 take 20% less space
46 |
47 | To convert dictionaries dos2unix is needed.
48 |
49 | In the GoldenDict directory:
50 | #+BEGIN_SRC sh
51 | find . -name '*.dsl.dz' -exec gunzip -S .dz {} \;
52 | find . -name '*.dsl' -exec dos2unix --add-bom -f {} \;
53 | find . -name '*.dsl' -exec gdcv -z {} \;
54 | find . -name '*.ann' -exec dos2unix --add-bom -f {} \;
55 | #+END_SRC
56 |
57 | *** Create Index
58 |
59 | #+BEGIN_SRC sh
60 | gdcv -i /path/to/directory/in/DSL/format /path/to/second/directory/in/DSL/format
61 | #+END_SRC
62 |
63 | Two index files will be saved in the directory:
64 | =$XDG_CONFIG_HOME/gdcv/= or =$HOME/.config/gdcv/= if =XDG_CONFIG_HOME= is not defined.
65 |
66 |
67 | * Usage
68 | To look up a word "cat"
69 | #+BEGIN_SRC sh
70 | gdcv cat
71 | #+END_SRC
72 |
73 | [[./video/cli.gif]]
74 |
75 | To search words containing "cat"
76 | #+BEGIN_SRC sh
77 | gdcv *cat
78 | #+END_SRC
79 |
80 |
81 | Put all additional media files to directory =/tmp=
82 | #+BEGIN_SRC sh
83 | gdcv cat --unzip=/tmp/
84 | #+END_SRC
85 |
86 | ** Create dictionary
87 |
88 | It is easy to create a dictionary in GoldenDict format. Essentially the format is specified [[http://lingvo.helpmax.net/en/troubleshooting/dsl-compiler/your-first-dsl-dictionary/][here]], except that @ tag is not supported. One can use typical dictionary in [[https://github.com/Tvangeste/SampleDSL][DSL format]].
89 | The dsl file has to be compressed in [[https://linux.die.net/man/1/dictzip][dictzip format]] and moved to GoldenDict directory.
90 |
91 | #+BEGIN_SRC sh
92 | gdcv -z dictionary.dsl
93 | #+END_SRC
94 |
95 | Note, that the result dsl.dz file can be uncompressed back with gzip:
96 |
97 | #+BEGIN_SRC sh
98 | gunzip -S .dz dictionary.dsl.dz
99 | #+END_SRC
100 |
101 |
102 | * Emacs module
103 | For many years I have successfully used sdcv-mode and [[http://sdcv.sourceforge.net/][sdcv]] in my work flow. Turn out all modern dictionaries are formatted in GoldenDict format (DSL). I tried to convert DSL to StarDict format with [[https://github.com/ilius/pyglossary][pyglossary]] but the result was mediocre. There is [[https://github.com/stardiviner/goldendict.el][goldendict-el]] for Emacs but I wanted something similar to sdcv-mode.
104 |
105 | ** To install gdcv-mode
106 | **** compile and create index files.
107 |
108 | #+BEGIN_SRC sh
109 | make gdcv emacs-module
110 | gdcv -i /path/to/directory/in/DSL/format
111 | #+END_SRC
112 |
113 | **** copy gdcv-elisp.so and gdcv.el to load-path. For example:
114 | #+BEGIN_SRC sh
115 | cp gdcv-elisp.so ~/.emacs.d/site-lisp/
116 | cp gdcv.el ~/.emacs.d/site-lisp/
117 | #+END_SRC
118 | ** Configuration
119 | Add to the init file
120 | #+BEGIN_SRC elisp
121 | (use-package gdcv
122 | :load-path "~/.emacs.d/site-lisp"
123 | :bind (("C-c d" . gdcv-search-word)))
124 | #+END_SRC
125 |
126 | If the index file is not saved in default directory, add:
127 | #+BEGIN_SRC elisp
128 | (setq gdcv-index-path "path/to/index/file")
129 | #+END_SRC
130 |
131 | To show the selected dictionary first, modify =gdcv-default-dictionary-list=
132 | #+BEGIN_SRC elisp
133 | (setq gdcv-default-dictionary-list '("OxfordDictionary (En-En)" "Merriam-Webster's Advanced Learner's Dictionary (En-En)"))
134 | #+END_SRC
135 |
136 | All media files for the translated word are unpacked to =gdcv-media-temp-directory= and are played by =gdcv-play-media= function (by default it is just wrapper around xdg-open).
137 |
138 | #+BEGIN_SRC elisp
139 | (setq gdcv-media-temp-directory "/tmp/gdcv/"
140 | gdcv-play-media (lambda (file)
141 | (let ((process-connection-type nil))
142 | (start-process "" nil "xdg-open" file))))
143 | #+END_SRC
144 |
145 |
146 |
147 | ** Usage
148 | =C-c d= to translate word (or text selection) under the cursor.
149 |
150 | [[./video/emacs.gif]]
151 |
152 |
153 | The gdcv-mode goes with simple ivy interface *ivy-gdcv*, which can be used to search a word. By default, the prefix search is used, for example for "cat", one can get: "cat","catamaran", "cater"... For the substring search one can type "*cat" and get: "cat","muscatel",...
154 |
155 |
156 |
157 | [[./video/ivy.gif]]
158 |
159 |
160 | * Useful links
161 | **** Examples of dictionaries in DSL
162 | + [[http://dadako.narod.ru/paperpoe.htm][DaDaKo]] Dictionaries for all languages (the website interface is in Russian)
163 | + [[https://github.com/konstare/Dictionaries][ Webster and WordNet]] English-English
164 | + [[https://github.com/open-dsl-dict/wiktionary-dict][Bilingual dictionaries from Wiktionary]]
165 |
166 | **** DSL format specification:
167 | http://lingvo.helpmax.net/en/troubleshooting/dsl-compiler/your-first-dsl-dictionary/
168 | **** Typical dictionary in DSL format
169 | https://github.com/Tvangeste/SampleDSL
170 | **** Tools for creating DSL-format dictionaries
171 | https://github.com/dohliam/dsl-tools
172 | **** Command-line interface for Goldendict dictionaries written in ruby
173 | https://github.com/dohliam/gdcl
174 | **** Lingvo dictionaries decompiler
175 | + https://github.com/nongeneric/lsd2dsl C++ implementation
176 | + https://github.com/sv99/lsdreader python implementation
177 | **** A tool for converting dictionary files aka glossaries with various formats for different dictionary applications
178 | https://github.com/ilius/pyglossary
179 |
180 |
--------------------------------------------------------------------------------
/dictzip.c:
--------------------------------------------------------------------------------
1 | /* Made up from data.c and other supplementary files of dictd-1.0.11 for the
2 | * GoldenDict program.
3 | */
4 |
5 | /* data.c --
6 | * Created: Tue Jul 16 12:45:41 1996 by faith@dict.org
7 | * Revised: Sat Mar 30 10:46:06 2002 by faith@dict.org
8 | * Copyright 1996, 1997, 1998, 2000, 2002 Rickard E. Faith (faith@dict.org)
9 | *
10 | * This program is free software; you can redistribute it and/or modify it
11 | * under the terms of the GNU General Public License as published by the
12 | * Free Software Foundation; either version 1, or (at your option) any
13 | * later version.
14 | *
15 | * This program is distributed in the hope that it will be useful, but
16 | * WITHOUT ANY WARRANTY; without even the implied warranty of
17 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 | * General Public License for more details.
19 | *
20 | * You should have received a copy of the GNU General Public License along
21 | * with this program; if not, write to the Free Software Foundation, Inc.,
22 | * 675 Mass Ave, Cambridge, MA 02139, USA.
23 | */
24 |
25 | #include
26 | #include "dictzip.h"
27 | #include
28 | #include
29 | #include
30 | #include
31 | #include
32 | #include
33 |
34 |
35 | #define UNUSED(x) (void)(x)
36 |
37 | #define BUFFERSIZE 10240
38 |
39 | #define OUT_BUFFER_SIZE 0xffffL
40 |
41 | #define IN_BUFFER_SIZE ((unsigned long)((double)(OUT_BUFFER_SIZE - 12) * 0.89))
42 |
43 | /* For gzip-compatible header, as defined in RFC 1952 */
44 |
45 | /* Magic for GZIP (rfc1952) */
46 | #define GZ_MAGIC1 0x1f /* First magic byte */
47 | #define GZ_MAGIC2 0x8b /* Second magic byte */
48 |
49 | /* FLaGs (bitmapped), from rfc1952 */
50 | #define GZ_FTEXT 0x01 /* Set for ASCII text */
51 | #define GZ_FHCRC 0x02 /* Header CRC16 */
52 | #define GZ_FEXTRA 0x04 /* Optional field (random access index) */
53 | #define GZ_FNAME 0x08 /* Original name */
54 | #define GZ_COMMENT 0x10 /* Zero-terminated, human-readable comment */
55 | #define GZ_MAX 2 /* Maximum compression */
56 | #define GZ_FAST 4 /* Fasted compression */
57 |
58 | /* These are from rfc1952 */
59 | #define GZ_OS_FAT 0 /* FAT filesystem (MS-DOS, OS/2, NT/Win32) */
60 | #define GZ_OS_AMIGA 1 /* Amiga */
61 | #define GZ_OS_VMS 2 /* VMS (or OpenVMS) */
62 | #define GZ_OS_UNIX 3 /* Unix */
63 | #define GZ_OS_VMCMS 4 /* VM/CMS */
64 | #define GZ_OS_ATARI 5 /* Atari TOS */
65 | #define GZ_OS_HPFS 6 /* HPFS filesystem (OS/2, NT) */
66 | #define GZ_OS_MAC 7 /* Macintosh */
67 | #define GZ_OS_Z 8 /* Z-System */
68 | #define GZ_OS_CPM 9 /* CP/M */
69 | #define GZ_OS_TOPS20 10 /* TOPS-20 */
70 | #define GZ_OS_NTFS 11 /* NTFS filesystem (NT) */
71 | #define GZ_OS_QDOS 12 /* QDOS */
72 | #define GZ_OS_ACORN 13 /* Acorn RISCOS */
73 | #define GZ_OS_UNKNOWN 255 /* unknown */
74 |
75 | #define GZ_RND_S1 'R' /* First magic for random access format */
76 | #define GZ_RND_S2 'A' /* Second magic for random access format */
77 |
78 | #define GZ_ID1 0 /* GZ_MAGIC1 */
79 | #define GZ_ID2 1 /* GZ_MAGIC2 */
80 | #define GZ_CM 2 /* Compression Method (Z_DEFALTED) */
81 | #define GZ_FLG 3 /* FLaGs (see above) */
82 | #define GZ_MTIME 4 /* Modification TIME */
83 | #define GZ_XFL 8 /* eXtra FLags (GZ_MAX or GZ_FAST) */
84 | #define GZ_OS 9 /* Operating System */
85 | #define GZ_XLEN 10 /* eXtra LENgth (16bit) */
86 | #define GZ_FEXTRA_START 12 /* Start of extra fields */
87 | #define GZ_SI1 12 /* Subfield ID1 */
88 | #define GZ_SI2 13 /* Subfield ID2 */
89 | #define GZ_SUBLEN 14 /* Subfield length (16bit) */
90 | #define GZ_VERSION 16 /* Version for subfield format */
91 | #define GZ_CHUNKLEN 18 /* Chunk length (16bit) */
92 | #define GZ_CHUNKCNT 20 /* Number of chunks (16bit) */
93 | #define GZ_RNDDATA 22 /* Random access data (16bit) */
94 |
95 |
96 | #define DBG_VERBOSE (0<<30|1<< 0) /* Verbose */
97 | #define DBG_ZIP (0<<30|1<< 1) /* Zip */
98 | #define DBG_UNZIP (0<<30|1<< 2) /* Unzip */
99 | #define DBG_SEARCH (0<<30|1<< 3) /* Search */
100 | #define DBG_SCAN (0<<30|1<< 4) /* Config file scan */
101 | #define DBG_PARSE (0<<30|1<< 5) /* Config file parse */
102 | #define DBG_INIT (0<<30|1<< 6) /* Database initialization */
103 | #define DBG_PORT (0<<30|1<< 7) /* Log port number for connections */
104 | #define DBG_LEV (0<<30|1<< 8) /* Levenshtein matching */
105 | #define DBG_AUTH (0<<30|1<< 9) /* Debug authentication */
106 | #define DBG_NODETACH (0<<30|1<<10) /* Don't detach as a background proc. */
107 | #define DBG_NOFORK (0<<30|1<<11) /* Don't fork (single threaded) */
108 | #define DBG_ALT (0<<30|1<<12) /* altcompare() */
109 |
110 | #define LOG_SERVER (0<<30|1<< 0) /* Log server diagnostics */
111 | #define LOG_CONNECT (0<<30|1<< 1) /* Log connection information */
112 | #define LOG_STATS (0<<30|1<< 2) /* Log termination information */
113 | #define LOG_COMMAND (0<<30|1<< 3) /* Log commands */
114 | #define LOG_FOUND (0<<30|1<< 4) /* Log words found */
115 | #define LOG_NOTFOUND (0<<30|1<< 5) /* Log words not found */
116 | #define LOG_CLIENT (0<<30|1<< 6) /* Log client */
117 | #define LOG_HOST (0<<30|1<< 7) /* Log remote host name */
118 | #define LOG_TIMESTAMP (0<<30|1<< 8) /* Log with timestamps */
119 | #define LOG_MIN (0<<30|1<< 9) /* Log a few minimal things */
120 | #define LOG_AUTH (0<<30|1<<10) /* Log authentication denials */
121 |
122 | #define DICT_LOG_TERM 0
123 | #define DICT_LOG_DEFINE 1
124 | #define DICT_LOG_MATCH 2
125 | #define DICT_LOG_NOMATCH 3
126 | #define DICT_LOG_CLIENT 4
127 | #define DICT_LOG_TRACE 5
128 | #define DICT_LOG_COMMAND 6
129 | #define DICT_LOG_AUTH 7
130 | #define DICT_LOG_CONNECT 8
131 |
132 | #define DICT_UNKNOWN 0
133 | #define DICT_TEXT 1
134 | #define DICT_GZIP 2
135 | #define DICT_DZIP 3
136 |
137 | #include
138 | #include
139 | #include
140 |
141 | #include
142 |
143 | #define USE_CACHE 1
144 |
145 | #define dict_data_filter( ... )
146 | #define PRINTF( ... )
147 |
148 | #define xmalloc malloc
149 | #define xfree free
150 |
151 | static const char * _err_programName = "GoldenDict";
152 |
153 | #define log_error( ... )
154 | #define log_error_va( ... )
155 |
156 | static void err_fatal( const char *routine, const char *format, ... )
157 | {
158 | va_list ap;
159 |
160 | fflush( stdout );
161 | if (_err_programName) {
162 | if (routine)
163 | fprintf( stderr, "%s (%s): ", _err_programName, routine );
164 | else
165 | fprintf( stderr, "%s: ", _err_programName );
166 | } else {
167 | if (routine) fprintf( stderr, "%s: ", routine );
168 | }
169 |
170 | va_start( ap, format );
171 | vfprintf( stderr, format, ap );
172 | log_error_va( routine, format, ap );
173 | va_end( ap );
174 |
175 | fflush( stderr );
176 | fflush( stdout );
177 | }
178 |
179 | /* \doc |err_fatal_errno| flushes "stdout", prints a fatal error report on
180 | "stderr", prints the system error corresponding to |errno|, flushes
181 | "stderr" and "stdout", and calls |exit|. |routine| is the name of the
182 | routine in which the error took place. */
183 |
184 | static void err_fatal_errno( const char *routine, const char *format, ... )
185 | {
186 | va_list ap;
187 | int errorno = errno;
188 |
189 | fflush( stdout );
190 | if (_err_programName) {
191 | if (routine)
192 | fprintf( stderr, "%s (%s): ", _err_programName, routine );
193 | else
194 | fprintf( stderr, "%s: ", _err_programName );
195 | } else {
196 | if (routine) fprintf( stderr, "%s: ", routine );
197 | }
198 |
199 | va_start( ap, format );
200 | vfprintf( stderr, format, ap );
201 | log_error_va( routine, format, ap );
202 | va_end( ap );
203 |
204 | #if HAVE_STRERROR
205 | fprintf( stderr, "%s: %s\n", routine, strerror( errorno ) );
206 | log_error( routine, "%s: %s\n", routine, strerror( errorno ) );
207 | #else
208 | errno = errorno;
209 | perror( routine );
210 | log_error( routine, "%s: errno = %d\n", routine, errorno );
211 | #endif
212 |
213 | fflush( stderr );
214 | fflush( stdout );
215 | }
216 |
217 | /* \doc |err_internal| flushes "stdout", prints the fatal error message,
218 | flushes "stderr" and "stdout", and calls |abort| so that a core dump is
219 | generated. */
220 |
221 | static void err_internal( const char *routine, const char *format, ... )
222 | {
223 | va_list ap;
224 |
225 | fflush( stdout );
226 | if (_err_programName) {
227 | if (routine)
228 | fprintf( stderr, "%s (%s): Internal error\n ",
229 | _err_programName, routine );
230 | else
231 | fprintf( stderr, "%s: Internal error\n ", _err_programName );
232 | } else {
233 | if (routine) fprintf( stderr, "%s: Internal error\n ", routine );
234 | else fprintf( stderr, "Internal error\n " );
235 | }
236 |
237 | va_start( ap, format );
238 | vfprintf( stderr, format, ap );
239 | log_error( routine, format, ap );
240 | va_end( ap );
241 |
242 | if (_err_programName)
243 | fprintf( stderr, "Aborting %s...\n", _err_programName );
244 | else
245 | fprintf( stderr, "Aborting...\n" );
246 | fflush( stderr );
247 | fflush( stdout );
248 | }
249 |
250 | #ifndef __func__
251 | # ifdef __FUNCTION__
252 | # define __func__ __FUNCTION__
253 | # else
254 | # define __func__ __FILE__
255 | # endif
256 | #endif
257 |
258 | static int dict_read_header( const char *filename,
259 | dictData *header, int computeCRC )
260 | {
261 | FILE *str;
262 | int id1, id2, si1, si2;
263 | char buffer[BUFFERSIZE];
264 | int extraLength, subLength;
265 | int i;
266 | char *pt;
267 | int c;
268 | struct stat sb;
269 | unsigned long crc = crc32( 0L, Z_NULL, 0 );
270 | int count;
271 | unsigned long offset;
272 |
273 | if (!(str = fopen( filename, "rb" )))
274 | {
275 | printf("Cannot open data file \"%s\" for read\n", filename );
276 | return 12;
277 | }
278 |
279 | header->filename = NULL;//str_find( filename );
280 | header->headerLength = GZ_XLEN - 1;
281 | header->type = DICT_UNKNOWN;
282 |
283 | id1 = getc( str );
284 | id2 = getc( str );
285 |
286 | if (id1 != GZ_MAGIC1 || id2 != GZ_MAGIC2) {
287 | header->type = DICT_TEXT;
288 | fstat( fileno( str ), &sb );
289 | header->compressedLength = header->length = sb.st_size;
290 | header->origFilename = NULL;//str_find( filename );
291 | header->mtime = sb.st_mtime;
292 | if (computeCRC) {
293 | rewind( str );
294 | while (!feof( str )) {
295 | if ((count = fread( buffer, 1, BUFFERSIZE, str ))) {
296 | crc = crc32( crc, (Bytef *)buffer, count );
297 | }
298 | }
299 | }
300 | header->crc = crc;
301 | fclose( str );
302 | return 0;
303 | }
304 | header->type = DICT_GZIP;
305 |
306 | header->method = getc( str );
307 | header->flags = getc( str );
308 | header->mtime = getc( str ) << 0;
309 | header->mtime |= getc( str ) << 8;
310 | header->mtime |= getc( str ) << 16;
311 | header->mtime |= getc( str ) << 24;
312 | header->extraFlags = getc( str );
313 | header->os = getc( str );
314 |
315 | if (header->flags & GZ_FEXTRA) {
316 | extraLength = getc( str ) << 0;
317 | extraLength |= getc( str ) << 8;
318 | header->headerLength += extraLength + 2;
319 | si1 = getc( str );
320 | si2 = getc( str );
321 |
322 | if (si1 == GZ_RND_S1 && si2 == GZ_RND_S2) {
323 | subLength = getc( str ) << 0;
324 | subLength |= getc( str ) << 8;
325 | header->version = getc( str ) << 0;
326 | header->version |= getc( str ) << 8;
327 |
328 | if (header->version != 1)
329 | {
330 | err_internal( __func__,
331 | "dzip header version %d not supported\n",
332 | header->version );
333 | fclose( str );
334 | return 6;
335 | }
336 |
337 | header->chunkLength = getc( str ) << 0;
338 | header->chunkLength |= getc( str ) << 8;
339 | header->chunkCount = getc( str ) << 0;
340 | header->chunkCount |= getc( str ) << 8;
341 |
342 | if (header->chunkCount <= 0) {
343 | fclose( str );
344 | return 5;
345 | }
346 | header->chunks = xmalloc( sizeof( header->chunks[0] )
347 | * header->chunkCount );
348 | if( header->chunks == 0 ) {
349 | return 7;
350 | }
351 |
352 | for (i = 0; i < header->chunkCount; i++) {
353 | header->chunks[i] = getc( str ) << 0;
354 | header->chunks[i] |= getc( str ) << 8;
355 | }
356 | header->type = DICT_DZIP;
357 | } else {
358 | fseek( str, header->headerLength, SEEK_SET );
359 | }
360 | }
361 |
362 | if (header->flags & GZ_FNAME) { /* FIXME! Add checking against header len */
363 | pt = buffer;
364 | while ((c = getc( str )) && c != EOF){
365 | *pt++ = c;
366 |
367 | if (pt == buffer + sizeof (buffer)){
368 | err_fatal (
369 | __func__,
370 | "too long FNAME field in dzip file \"%s\"\n", filename);
371 | fclose( str );
372 | if( header->chunks )
373 | free( header->chunks );
374 | return 8;
375 | }
376 | }
377 |
378 | *pt = '\0';
379 | header->origFilename = NULL;//str_find( buffer );
380 | header->headerLength += strlen( buffer ) + 1;
381 | } else {
382 | header->origFilename = NULL;
383 | }
384 |
385 | if (header->flags & GZ_COMMENT) { /* FIXME! Add checking for header len */
386 | pt = buffer;
387 | while ((c = getc( str )) && c != EOF){
388 | *pt++ = c;
389 |
390 | if (pt == buffer + sizeof (buffer)){
391 | err_fatal (
392 | __func__,
393 | "too long COMMENT field in dzip file \"%s\"\n", filename);
394 | fclose( str );
395 | if( header->chunks )
396 | free( header->chunks );
397 | return 9;
398 | }
399 | }
400 |
401 | *pt = '\0';
402 | header->comment = NULL;//str_find( buffer );
403 | header->headerLength += strlen( buffer ) + 1;
404 | } else {
405 | header->comment = NULL;
406 | }
407 |
408 | if (header->flags & GZ_FHCRC) {
409 | getc( str );
410 | getc( str );
411 | header->headerLength += 2;
412 | }
413 |
414 | if (ftell( str ) != header->headerLength + 1)
415 | {
416 | err_internal( __func__,
417 | "File position (%lu) != header length + 1 (%d)\n",
418 | ftell( str ), header->headerLength + 1 );
419 | fclose( str );
420 | if( header->chunks )
421 | free( header->chunks );
422 | return 10;
423 | }
424 |
425 | fseek( str, -8, SEEK_END );
426 | header->crc = getc( str ) << 0;
427 | header->crc |= getc( str ) << 8;
428 | header->crc |= getc( str ) << 16;
429 | header->crc |= getc( str ) << 24;
430 | header->length = getc( str ) << 0;
431 | header->length |= getc( str ) << 8;
432 | header->length |= getc( str ) << 16;
433 | header->length |= getc( str ) << 24;
434 | header->compressedLength = ftell( str );
435 |
436 | /* Compute offsets */
437 | header->offsets = xmalloc( sizeof( header->offsets[0] )
438 | * header->chunkCount );
439 | if( header->offsets == 0 ) {
440 | fclose( str );
441 | if( header->chunks )
442 | free( header->chunks );
443 | return 11;
444 | }
445 |
446 | for (offset = header->headerLength + 1, i = 0;
447 | i < header->chunkCount;
448 | i++)
449 | {
450 | header->offsets[i] = offset;
451 | offset += header->chunks[i];
452 | }
453 |
454 | fclose( str );
455 | return 0;
456 | }
457 |
458 |
459 | static void xfwrite(
460 | const void *ptr, size_t size, size_t nmemb,
461 | FILE * stream)
462 | {
463 | size_t ret = fwrite(ptr, size, nmemb, stream);
464 | if (ret < nmemb){
465 | perror("fwrite(3) failed");
466 | exit ( 1 );
467 | }
468 | }
469 |
470 | static void xfclose(FILE *stream)
471 | {
472 | if (fclose(stream) != 0){
473 | perror("fclose(3) failed");
474 | exit ( 1 );
475 | }
476 | }
477 |
478 |
479 | int dict_data_zip( FILE *inStr, const char *outFilename)
480 | {
481 | char inBuffer[IN_BUFFER_SIZE];
482 | char outBuffer[OUT_BUFFER_SIZE];
483 | int count;
484 | unsigned long inputCRC = crc32( 0L, Z_NULL, 0 );
485 | z_stream zStream;
486 | FILE *outStr;
487 | int len;
488 | struct stat st;
489 | char *header;
490 | int headerLength;
491 | int dataLength;
492 | int extraLength;
493 | int chunkLength;
494 | unsigned long chunks;
495 | unsigned long chunk = 0;
496 | unsigned long total = 0;
497 | int i;
498 | char tail[8];
499 | char origFilename[]="gdcv_index_values";
500 |
501 | /* Open files */
502 |
503 | if (!(outStr = fopen( outFilename, "w" )))
504 | err_fatal_errno( __func__,
505 | "Cannot open \"%s\"for write\n", outFilename );
506 |
507 |
508 | /* Initialize compression engine */
509 | zStream.zalloc = NULL;
510 | zStream.zfree = NULL;
511 | zStream.opaque = NULL;
512 | zStream.next_in = NULL;
513 | zStream.avail_in = 0;
514 | zStream.next_out = NULL;
515 | zStream.avail_out = 0;
516 | if (deflateInit2( &zStream,
517 | Z_BEST_COMPRESSION,
518 | Z_DEFLATED,
519 | -15, /* Suppress zlib header */
520 | Z_BEST_COMPRESSION,
521 | Z_DEFAULT_STRATEGY ) != Z_OK)
522 | err_internal( __func__,
523 | "Cannot initialize deflation engine: %s\n", zStream.msg );
524 |
525 | /* Write initial header information */
526 | chunkLength = IN_BUFFER_SIZE;
527 | fstat( fileno( inStr ), &st );
528 | chunks = st.st_size / chunkLength;
529 | if (st.st_size % chunkLength) ++chunks;
530 | PRINTF(DBG_VERBOSE,("%lu chunks * %u per chunk = %lu (filesize = %lu)\n",
531 | chunks, chunkLength, chunks * chunkLength,
532 | (unsigned long) st.st_size ));
533 | dataLength = chunks * 2;
534 | extraLength = 10 + dataLength;
535 | headerLength = GZ_FEXTRA_START
536 | + extraLength /* FEXTRA */
537 | + strlen( origFilename ) + 1; /* FNAME */
538 | PRINTF(DBG_VERBOSE,("(data = %d, extra = %d, header = %d)\n",
539 | dataLength, extraLength, headerLength ));
540 | header = xmalloc( headerLength );
541 | for (i = 0; i < headerLength; i++) header[i] = 0;
542 | header[GZ_ID1] = GZ_MAGIC1;
543 | header[GZ_ID2] = (char)GZ_MAGIC2;
544 | header[GZ_CM] = Z_DEFLATED;
545 | header[GZ_FLG] = GZ_FEXTRA | GZ_FNAME;
546 | header[GZ_MTIME+3] = (st.st_mtime & 0xff000000) >> 24;
547 | header[GZ_MTIME+2] = (st.st_mtime & 0x00ff0000) >> 16;
548 | header[GZ_MTIME+1] = (st.st_mtime & 0x0000ff00) >> 8;
549 | header[GZ_MTIME+0] = (st.st_mtime & 0x000000ff) >> 0;
550 | header[GZ_XFL] = GZ_MAX;
551 | header[GZ_OS] = GZ_OS_UNIX;
552 | header[GZ_XLEN+1] = (extraLength & 0xff00) >> 8;
553 | header[GZ_XLEN+0] = (extraLength & 0x00ff) >> 0;
554 | header[GZ_SI1] = GZ_RND_S1;
555 | header[GZ_SI2] = GZ_RND_S2;
556 | header[GZ_SUBLEN+1] = ((extraLength - 4) & 0xff00) >> 8;
557 | header[GZ_SUBLEN+0] = ((extraLength - 4) & 0x00ff) >> 0;
558 | header[GZ_VERSION+1] = 0;
559 | header[GZ_VERSION+0] = 1;
560 | header[GZ_CHUNKLEN+1] = (chunkLength & 0xff00) >> 8;
561 | header[GZ_CHUNKLEN+0] = (chunkLength & 0x00ff) >> 0;
562 | header[GZ_CHUNKCNT+1] = (chunks & 0xff00) >> 8;
563 | header[GZ_CHUNKCNT+0] = (chunks & 0x00ff) >> 0;
564 | strcpy( &header[GZ_FEXTRA_START + extraLength], origFilename );
565 | xfwrite( header, 1, headerLength, outStr );
566 |
567 | /* Read, compress, write */
568 | while (!feof( inStr )) {
569 | if ((count = fread( inBuffer, 1, chunkLength, inStr ))) {
570 | dict_data_filter( inBuffer, &count, IN_BUFFER_SIZE, preFilter );
571 |
572 | inputCRC = crc32( inputCRC, (const Bytef *) inBuffer, count );
573 | zStream.next_in = (Bytef *) inBuffer;
574 | zStream.avail_in = count;
575 | zStream.next_out = (Bytef *) outBuffer;
576 | zStream.avail_out = OUT_BUFFER_SIZE;
577 | if (deflate( &zStream, Z_FULL_FLUSH ) != Z_OK)
578 | err_fatal( __func__, "deflate: %s\n", zStream.msg );
579 | assert( zStream.avail_in == 0 );
580 | len = OUT_BUFFER_SIZE - zStream.avail_out;
581 | assert( len <= 0xffff );
582 |
583 | dict_data_filter( outBuffer, &len, OUT_BUFFER_SIZE, postFilter );
584 |
585 | assert( len <= 0xffff );
586 | header[GZ_RNDDATA + chunk*2 + 1] = (len & 0xff00) >> 8;
587 | header[GZ_RNDDATA + chunk*2 + 0] = (len & 0x00ff) >> 0;
588 | xfwrite( outBuffer, 1, len, outStr );
589 |
590 | ++chunk;
591 | total += count;
592 |
593 | }
594 | }
595 | PRINTF(DBG_VERBOSE,("total: %lu chunks, %lu bytes\n", chunks, (unsigned long) st.st_size));
596 |
597 | /* Write last bit */
598 | zStream.next_in = (Bytef *) inBuffer;
599 | zStream.avail_in = 0;
600 | zStream.next_out = (Bytef *) outBuffer;
601 | zStream.avail_out = OUT_BUFFER_SIZE;
602 | if (deflate( &zStream, Z_FINISH ) != Z_STREAM_END)
603 | err_fatal( __func__, "deflate: %s\n", zStream.msg );
604 | assert( zStream.avail_in == 0 );
605 | len = OUT_BUFFER_SIZE - zStream.avail_out;
606 | xfwrite( outBuffer, 1, len, outStr );
607 | PRINTF(DBG_VERBOSE,("(wrote %d bytes, final, crc = %lx)\n",
608 | len, inputCRC ));
609 |
610 | /* Write CRC and length */
611 | tail[0 + 3] = (inputCRC & 0xff000000) >> 24;
612 | tail[0 + 2] = (inputCRC & 0x00ff0000) >> 16;
613 | tail[0 + 1] = (inputCRC & 0x0000ff00) >> 8;
614 | tail[0 + 0] = (inputCRC & 0x000000ff) >> 0;
615 | tail[4 + 3] = (st.st_size & 0xff000000) >> 24;
616 | tail[4 + 2] = (st.st_size & 0x00ff0000) >> 16;
617 | tail[4 + 1] = (st.st_size & 0x0000ff00) >> 8;
618 | tail[4 + 0] = (st.st_size & 0x000000ff) >> 0;
619 | xfwrite( tail, 1, 8, outStr );
620 |
621 | /* Write final header information */
622 | rewind( outStr );
623 | xfwrite( header, 1, headerLength, outStr );
624 |
625 | /* Close files */
626 | xfclose( outStr );
627 |
628 | /* Shut down compression */
629 | if (deflateEnd( &zStream ) != Z_OK)
630 | err_fatal( __func__, "defalteEnd: %s\n", zStream.msg );
631 |
632 | xfree( header );
633 |
634 | return 0;
635 | }
636 |
637 |
638 | dictData *dict_data_open( const char *filename, int computeCRC )
639 | {
640 | dictData *h = NULL;
641 | int j;
642 |
643 | if (!filename)
644 | return NULL;
645 |
646 | h = xmalloc( sizeof( struct dictData ) );
647 | if( h == 0 )
648 | return NULL;
649 |
650 | memset( h, 0, sizeof( struct dictData ) );
651 | h->initialized = 0;
652 |
653 | if (dict_read_header( filename, h, computeCRC )) {
654 | return 0; /*
655 | err_fatal( __func__,
656 | "\"%s\" not in text or dzip format\n", filename );*/
657 | }
658 |
659 | h->fd = fopen( filename, "rb" );
660 |
661 | if ( !h->fd )
662 | {
663 | return 0;
664 | /*err_fatal_errno( __func__,
665 | "Cannot open data file \"%s\"\n", filename );*/
666 | }
667 |
668 | fseek( h->fd, 0, SEEK_END );
669 |
670 | h->size = ftell( h->fd );
671 |
672 | for (j = 0; j < DICT_CACHE_SIZE; j++) {
673 | h->cache[j].chunk = -1;
674 | h->cache[j].stamp = -1;
675 | h->cache[j].inBuffer = NULL;
676 | h->cache[j].count = 0;
677 | }
678 |
679 | return h;
680 | }
681 |
682 | void dict_data_close( dictData *header )
683 | {
684 | int i;
685 |
686 | if (!header)
687 | return;
688 |
689 | if ( header->fd )
690 | fclose( header->fd );
691 |
692 | if (header->chunks) xfree( header->chunks );
693 | if (header->offsets) xfree( header->offsets );
694 |
695 | if (header->initialized) {
696 | if (inflateEnd( &header->zStream ))
697 | err_internal( __func__,
698 | "Cannot shut down inflation engine: %s\n",
699 | header->zStream.msg );
700 | }
701 |
702 | for (i = 0; i < DICT_CACHE_SIZE; ++i){
703 | if (header -> cache [i].inBuffer)
704 | xfree (header -> cache [i].inBuffer);
705 | }
706 |
707 | memset( header, 0, sizeof( struct dictData ) );
708 | xfree( header );
709 | }
710 |
711 | char *dict_data_read_ (
712 | dictData *h, unsigned long start, unsigned long size,
713 | const char *preFilter, const char *postFilter )
714 | {
715 | char *buffer, *pt;
716 | unsigned long end;
717 | int count;
718 | char *inBuffer;
719 | char outBuffer[OUT_BUFFER_SIZE];
720 | int firstChunk, lastChunk;
721 | int firstOffset, lastOffset;
722 | int i, j;
723 | int found, target, lastStamp;
724 | static int stamp = 0;
725 |
726 | UNUSED(preFilter);
727 | UNUSED(postFilter);
728 |
729 | end = start + size;
730 |
731 | buffer = xmalloc( size + 1 );
732 |
733 | if ( !size )
734 | {
735 | *buffer = 0;
736 | return buffer;
737 | }
738 |
739 | PRINTF(DBG_UNZIP,
740 | ("dict_data_read( %p, %lu, %lu, %s, %s )\n",
741 | h, start, size, preFilter, postFilter ));
742 |
743 | assert( h != NULL);
744 | switch (h->type) {
745 | case DICT_GZIP:
746 | err_fatal( __func__,
747 | "Cannot seek on pure gzip format files.\n"
748 | "Use plain text (for performance)"
749 | " or dzip format (for space savings).\n" );
750 | break;
751 | case DICT_TEXT:
752 | {
753 | if ( fseek( h->fd, start, SEEK_SET ) != 0 ||
754 | fread( buffer, size, 1, h->fd ) != 1 )
755 | {
756 | xfree( buffer );
757 | return 0;
758 | }
759 |
760 | buffer[size] = '\0';
761 | }
762 | break;
763 | case DICT_DZIP:
764 | if (!h->initialized) {
765 | ++h->initialized;
766 | h->zStream.zalloc = NULL;
767 | h->zStream.zfree = NULL;
768 | h->zStream.opaque = NULL;
769 | h->zStream.next_in = 0;
770 | h->zStream.avail_in = 0;
771 | h->zStream.next_out = NULL;
772 | h->zStream.avail_out = 0;
773 | if (inflateInit2( &h->zStream, -15 ) != Z_OK)
774 | err_internal( __func__,
775 | "Cannot initialize inflation engine: %s\n",
776 | h->zStream.msg );
777 | }
778 | firstChunk = start / h->chunkLength;
779 | firstOffset = start - firstChunk * h->chunkLength;
780 | lastChunk = end / h->chunkLength;
781 | lastOffset = end - lastChunk * h->chunkLength;
782 | PRINTF(DBG_UNZIP,
783 | (" start = %lu, end = %lu\n"
784 | "firstChunk = %d, firstOffset = %d,"
785 | " lastChunk = %d, lastOffset = %d\n",
786 | start, end, firstChunk, firstOffset, lastChunk, lastOffset ));
787 | for (pt = buffer, i = firstChunk; i <= lastChunk; i++) {
788 |
789 | /* Access cache */
790 | found = 0;
791 | target = 0;
792 | lastStamp = INT_MAX;
793 | for (j = 0; j < DICT_CACHE_SIZE; j++) {
794 | #if USE_CACHE
795 | if (h->cache[j].chunk == i) {
796 | found = 1;
797 | target = j;
798 | break;
799 | }
800 | #endif
801 | if (h->cache[j].stamp < lastStamp) {
802 | lastStamp = h->cache[j].stamp;
803 | target = j;
804 | }
805 | }
806 |
807 | h->cache[target].stamp = ++stamp;
808 | if (found) {
809 | count = h->cache[target].count;
810 | inBuffer = h->cache[target].inBuffer;
811 | } else {
812 | h->cache[target].chunk = i;
813 | if (!h->cache[target].inBuffer)
814 | h->cache[target].inBuffer = xmalloc( IN_BUFFER_SIZE );
815 | inBuffer = h->cache[target].inBuffer;
816 |
817 | if (h->chunks[i] >= OUT_BUFFER_SIZE ) {
818 | err_internal( __func__,
819 | "h->chunks[%d] = %d >= %ld (OUT_BUFFER_SIZE)\n",
820 | i, h->chunks[i], OUT_BUFFER_SIZE );
821 | }
822 |
823 | if ( fseek( h->fd, h->offsets[ i ], SEEK_SET ) != 0 ||
824 | fread( outBuffer, h->chunks[ i ], 1, h->fd ) != 1 )
825 | {
826 | xfree( buffer );
827 | return 0;
828 | }
829 |
830 | dict_data_filter( outBuffer, &count, OUT_BUFFER_SIZE, preFilter );
831 |
832 | h->zStream.next_in = (Bytef *)outBuffer;
833 | h->zStream.avail_in = h->chunks[i];
834 | h->zStream.next_out = (Bytef *)inBuffer;
835 | h->zStream.avail_out = IN_BUFFER_SIZE;
836 | if (inflate( &h->zStream, Z_PARTIAL_FLUSH ) != Z_OK)
837 | err_fatal( __func__, "inflate: %s\n", h->zStream.msg );
838 | if (h->zStream.avail_in)
839 | err_internal( __func__,
840 | "inflate did not flush (%d pending, %d avail)\n",
841 | h->zStream.avail_in, h->zStream.avail_out );
842 |
843 | count = IN_BUFFER_SIZE - h->zStream.avail_out;
844 | dict_data_filter( inBuffer, &count, IN_BUFFER_SIZE, postFilter );
845 |
846 | h->cache[target].count = count;
847 | }
848 |
849 | if (i == firstChunk) {
850 | if (i == lastChunk) {
851 | memcpy( pt, inBuffer + firstOffset, lastOffset-firstOffset);
852 | pt += lastOffset - firstOffset;
853 | } else {
854 | if (count != h->chunkLength )
855 | err_internal( __func__,
856 | "Length = %d instead of %d\n",
857 | count, h->chunkLength );
858 | memcpy( pt, inBuffer + firstOffset,
859 | h->chunkLength - firstOffset );
860 | pt += h->chunkLength - firstOffset;
861 | }
862 | } else if (i == lastChunk) {
863 | memcpy( pt, inBuffer, lastOffset );
864 | pt += lastOffset;
865 | } else {
866 | assert( count == h->chunkLength );
867 | memcpy( pt, inBuffer, h->chunkLength );
868 | pt += h->chunkLength;
869 | }
870 | }
871 | *pt = '\0';
872 | break;
873 | case DICT_UNKNOWN:
874 | err_fatal( __func__, "Cannot read unknown file type\n" );
875 | break;
876 | }
877 |
878 | return buffer;
879 | }
880 |
--------------------------------------------------------------------------------
/dictzip.h:
--------------------------------------------------------------------------------
1 | /* Made up from data.h and other supplementary files of dictd-1.0.11 for the
2 | * GoldenDict program.
3 | */
4 |
5 | /* data.h --
6 | * Created: Sat Mar 15 18:04:25 2003 by Aleksey Cheusov
7 | * Copyright 1994-2003 Rickard E. Faith (faith@dict.org)
8 | *
9 | * This program is free software; you can redistribute it and/or modify it
10 | * under the terms of the GNU General Public License as published by the
11 | * Free Software Foundation; either version 1, or (at your option) any
12 | * later version.
13 | *
14 | * This program is distributed in the hope that it will be useful, but
15 | * WITHOUT ANY WARRANTY; without even the implied warranty of
16 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 | * General Public License for more details.
18 | *
19 | * You should have received a copy of the GNU General Public License along
20 | * with this program; if not, write to the Free Software Foundation, Inc.,
21 | * 675 Mass Ave, Cambridge, MA 02139, USA.
22 | */
23 |
24 | #ifndef _DICTZIP_H_
25 | #define _DICTZIP_H_
26 |
27 | #include
28 | #include
29 |
30 | #ifdef __WIN32
31 | #include
32 | #endif
33 |
34 | #ifdef __cplusplus
35 | extern "C"
36 | {
37 | #endif
38 |
39 |
40 | /* Excerpts from defs.h */
41 |
42 | #define DICT_CACHE_SIZE 5
43 |
44 | typedef struct dictCache {
45 | int chunk;
46 | char *inBuffer;
47 | int stamp;
48 | int count;
49 | } dictCache;
50 |
51 | typedef struct dictData {
52 |
53 | FILE * fd; /* file descriptor */
54 |
55 | unsigned long size; /* size of file */
56 |
57 | int type;
58 | const char *filename;
59 | z_stream zStream;
60 | int initialized;
61 |
62 | int headerLength;
63 | int method;
64 | int flags;
65 | time_t mtime;
66 | int extraFlags;
67 | int os;
68 | int version;
69 | int chunkLength;
70 | int chunkCount;
71 | int *chunks;
72 | unsigned long *offsets; /* Sum-scan of chunks. */
73 | const char *origFilename;
74 | const char *comment;
75 | unsigned long crc;
76 | unsigned long length;
77 | unsigned long compressedLength;
78 | dictCache cache[DICT_CACHE_SIZE];
79 | } dictData;
80 |
81 |
82 | /* initialize .data file */
83 | extern dictData *dict_data_open (
84 | const char *filename, int computeCRC);
85 | /* */
86 | extern void dict_data_close (
87 | dictData *data);
88 |
89 | extern char *dict_data_read_ (
90 | dictData *data,
91 | unsigned long start, unsigned long size,
92 | const char *preFilter,
93 | const char *postFilter );
94 |
95 | extern int dict_data_zip( FILE *inFilename, const char *outFilename);
96 |
97 | #ifdef __cplusplus
98 | } /* end extern "C" */
99 | #endif
100 |
101 | #endif /* _DICTZIP_H_ */
102 |
--------------------------------------------------------------------------------
/elisp.c:
--------------------------------------------------------------------------------
1 | int plugin_is_GPL_compatible;
2 |
3 | #include "emacs-module.h"
4 | #include
5 | #include "format.h"
6 | #include "index.h"
7 | #include "utils.h"
8 |
9 | #define FREE(p) if (p!=NULL) free(p);
10 | #define SYM(sym) env->intern(env, (sym))
11 |
12 | #define STRING(val) env->make_string(env, (val), strlen(val))
13 | #define INTEGER(val) env->make_integer(env,(val))
14 |
15 |
16 |
17 | #define NON_LOCAL_EXIT_CHECK \
18 | if (env->non_local_exit_check(env) != emacs_funcall_exit_return) { \
19 | return SYM("nil"); \
20 | }
21 |
22 |
23 | static emacs_value
24 | make_list(emacs_env *env, int n, emacs_value elts[]) {
25 | emacs_value list=env->funcall(env, SYM("list"), n, elts);
26 | NON_LOCAL_EXIT_CHECK
27 | return list;
28 | }
29 |
30 |
31 | static int
32 | extract_string_arg(emacs_env *env, emacs_value arg, char **str) {
33 | ptrdiff_t size = 0;
34 | if (!env->copy_string_contents(env, arg, NULL, &size))
35 | return 1;
36 | *str = xmalloc(size);
37 | if (!env->copy_string_contents(env, arg, *str, &size)) {
38 | if ((*str) != 0) free(*str);
39 | *str = 0;
40 | return 1;
41 | }
42 | return 0;
43 | }
44 |
45 |
46 |
47 | static void
48 | close_db(void *ptr) {
49 | struct index_mm *index=(struct index_mm *)ptr;
50 | if (index)
51 | index_mm_close(index);
52 | }
53 |
54 |
55 | static emacs_value
56 | open_database(emacs_env *env, ptrdiff_t n, emacs_value *args, void *ptr)
57 | {
58 | (void)ptr;
59 | (void)n;
60 |
61 | char *index_path;
62 |
63 | if (extract_string_arg(env, args[0], &index_path)) {
64 | return SYM("nil");
65 | }
66 |
67 | struct index_mm *index;
68 | index=index_mm_open(index_path);
69 |
70 | if(!index)
71 | {
72 | emacs_value signal = env->intern(env, "no index");
73 | emacs_value message = STRING(index_path);
74 | free(index_path);
75 | env->non_local_exit_signal(env, signal, message);
76 | }
77 |
78 | free(index_path);
79 | return env->make_user_ptr(env, close_db, (void *)index);
80 | }
81 |
82 |
83 | static emacs_value
84 | render_emacs(emacs_env *env,struct format_ *format)
85 | {
86 | char *src=format->string;
87 |
88 | struct
89 | {
90 | TAG type;
91 | size_t open; //open and close in utf8
92 | size_t close;
93 | char *property;
94 | int id;
95 | } T[format->N];
96 |
97 | size_t tags_N=0;
98 |
99 | size_t utf_opened[N_TAG]={0};
100 | TAG type;
101 |
102 | int opened=0;
103 | size_t utf_pos=0;
104 | size_t pos;
105 |
106 | for(int i=0; iN;i++)
107 | {
108 | pos=format->tag[i].pos;
109 | type=format->tag[i].type;
110 | for(size_t j=opened;jtag[i].open==1)
116 | {
117 | T[tags_N].type=type;
118 | T[tags_N].open=utf_pos;
119 | T[tags_N].close=utf_pos; //in the case tag is not closed.
120 | T[tags_N].property=format->tag[i].properties;
121 | T[tags_N].id=i;
122 | utf_opened[type]=tags_N;
123 | tags_N++;
124 | }
125 | else
126 | T[utf_opened[type]].close=utf_pos;
127 | }
128 |
129 | emacs_value *elts =xmalloc(tags_N*sizeof(emacs_value));
130 |
131 | emacs_value tag_param[4];
132 | emacs_value string_param[2];
133 |
134 |
135 | for(size_t i=0;iis_not_nil(env, args[0])) {
161 | return SYM( "nil");
162 | }
163 |
164 | struct index_mm *index=(struct index_mm *)env->get_user_ptr(env, args[0]);
165 | NON_LOCAL_EXIT_CHECK;
166 |
167 | char *Word;
168 | if (extract_string_arg(env, args[1], &Word)) {
169 | return SYM( "nil");
170 | }
171 |
172 |
173 |
174 | int art=0;
175 | int rc=0;
176 | struct article *Art=NULL;
177 | emacs_value art_param[5];
178 |
179 | if((rc=decode_articles(Word,&Art,&art,index))==0)
180 | {
181 | emacs_value *elts =xmalloc(art*sizeof(emacs_value));
182 | for(int i=0;iDic , index->N, Art[i].dic);
185 |
186 | art_param[0]=STRING(Dic->data[NAME]);
187 | art_param[1]=INTEGER(Art[i].dic);
188 | art_param[2]=INTEGER(Art[i].start);
189 | art_param[3]=INTEGER(Art[i].size);
190 | art_param[4]=Dic->data[RESOURCES] ? STRING(Dic->data[RESOURCES]) : SYM( "nil");
191 |
192 | elts[i]=make_list(env, 5,art_param);
193 | free(Art[i].word);
194 | }
195 | emacs_value result = make_list(env, art,elts);
196 | FREE(elts);
197 | free(Art);
198 | free(Word);
199 | return result;
200 | }
201 |
202 | free(Word);
203 | return SYM( "nil");
204 | }
205 |
206 |
207 | static emacs_value
208 | word_from_dictionary(emacs_env *env, ptrdiff_t n, emacs_value *args, void *ptr)
209 | {
210 | (void)ptr;
211 | (void)n;
212 | if (!env->is_not_nil(env, args[0])) {
213 | return SYM( "nil");
214 | }
215 |
216 | struct index_mm *index=(struct index_mm *)env->get_user_ptr(env, args[0]);
217 | NON_LOCAL_EXIT_CHECK;
218 |
219 | int dic = env->extract_integer(env, args[1]);
220 | NON_LOCAL_EXIT_CHECK;
221 | int start = env->extract_integer(env, args[2]);
222 | NON_LOCAL_EXIT_CHECK;
223 | int end = env->extract_integer(env, args[3]);
224 | NON_LOCAL_EXIT_CHECK;
225 |
226 | char *path_unzip;
227 | if (extract_string_arg(env, args[4], &path_unzip)) {
228 | return SYM( "nil");
229 | }
230 |
231 |
232 | struct dictionary *Dic=get_dictionary(index->Dic , index->N, dic);
233 |
234 | char *definition = word_fetch(Dic, start, end);
235 |
236 | struct format_ format;
237 | format.tag=NULL;
238 |
239 | strip_tags(definition,&format);
240 | emacs_value result=render_emacs(env,&format);
241 |
242 | if(strcmp(path_unzip,"")&&Dic->data[RESOURCES]!=NULL&&strcmp(Dic->data[RESOURCES],""))
243 | unzip_resources(&format, path_unzip, Dic->data[RESOURCES]);
244 |
245 |
246 | free_format(&format);
247 | free(path_unzip);
248 | free(definition);
249 | return result;
250 | }
251 |
252 |
253 | static emacs_value
254 | word_lookup(emacs_env *env, ptrdiff_t n, emacs_value *args, void *ptr)
255 | {
256 | (void)ptr;
257 | (void)n;
258 |
259 | if (!env->is_not_nil(env, args[0])) {
260 | return SYM( "nil");
261 | }
262 |
263 | struct index_mm *index=(struct index_mm *)env->get_user_ptr(env, args[0]);
264 | NON_LOCAL_EXIT_CHECK;
265 | char *Word;
266 | if (extract_string_arg(env, args[1], &Word)) {
267 | return SYM( "nil");
268 | }
269 |
270 | int is_prefix = env->extract_integer(env, args[2]);
271 | NON_LOCAL_EXIT_CHECK;
272 |
273 |
274 | struct article *Art=NULL;
275 | int art=0;
276 |
277 | look_for_a_word(index,Word,&art,&Art,is_prefix);
278 | free(Word);
279 | emacs_value res;
280 | if(art>0)
281 | {
282 | emacs_value *elts=xmalloc(art*sizeof(emacs_value));
283 | for(int j=0;jis_not_nil(env, args[0]))
306 | return SYM( "nil");
307 |
308 |
309 | struct index_mm *index=(struct index_mm *)env->get_user_ptr(env, args[0]);
310 |
311 | NON_LOCAL_EXIT_CHECK;
312 |
313 | if (index ) {
314 | index_mm_close(index);
315 | env->set_user_ptr(env, args[0], 0);
316 | }
317 | return SYM( "nil");
318 | }
319 |
320 |
321 |
322 | void bind_func(emacs_env *env, const char *name, ptrdiff_t min, ptrdiff_t max,
323 | emacs_value (*function) (emacs_env *env, ptrdiff_t nargs, emacs_value args[],void *) EMACS_NOEXCEPT, const char *doc)
324 | {
325 | emacs_value fset = SYM( "fset");
326 | emacs_value args[2];
327 |
328 | args[0] = SYM( name);
329 | args[1] = env->make_function(env, min, max, function, doc, 0);
330 | env->funcall(env, fset, 2, args);
331 | }
332 |
333 |
334 | int
335 | emacs_module_init(struct emacs_runtime *ert)
336 | {
337 | emacs_env *env = ert->get_environment(ert);
338 |
339 |
340 |
341 | bind_func(env,"gdcv-database-open",1,1,open_database, "Open database with index and return pointer");
342 | bind_func(env,"gdcv-database-close",1,1,close_database, "Close database with given pointer");
343 | bind_func(env,"gdcv-look-word",3,3,word_lookup, "Look for words similar to given word");
344 | bind_func(env,"gdcv-word-defs",2,2,word_defs, "List of all dictionaries with current word");
345 | bind_func(env,"gdcv-word-fetch",5,5,word_from_dictionary, "Return article from specific dictionary ");
346 |
347 | emacs_value provide = SYM( "provide");
348 | emacs_value gdcv[] = {SYM( "gdcv-elisp")};
349 | env->funcall(env, provide, 1, gdcv);
350 | return 0;
351 | }
352 |
--------------------------------------------------------------------------------
/format.c:
--------------------------------------------------------------------------------
1 | #define _GNU_SOURCE ///
2 |
3 | #include "format.h"
4 | #include
5 | #include "utils.h"
6 | #include ////asprintf
7 | #include //strdup, memcpy, strcmp, strlen sscanf strtok
8 | #include //perror printf FILENAME_MAX
9 |
10 | #define CLI_DIC_TITLE "\x1B[1m\x1B[31m"
11 | #define CLI_RESET "\x1B[0m"
12 | #define CLI_BLACK "\x1B[30m" /* Black */
13 | #define CLI_RED "\x1B[31m" /* Red */
14 | #define CLI_YELLOW "\x1B[33m" /* Green */
15 | #define CLI_GREEN "\x1B[32m" /* Green */
16 | #define CLI_BLUE "\x1B[34m" /* Blue */
17 | #define CLI_BOLD "\x1B[1m" /* Bold */
18 | #define CLI_FAINT "\x1B[2m" /* FAINT */
19 | #define CLI_UNDERLINE "\x1B[4m" /* Underline */
20 | #define CLI_ITALIC "\x1B[3m" /* Italic */
21 | #define CLI_REF "\x1B[1m\x1B[34m\x1B[4m"
22 | #define CLI_LABELS "\x1B[3m\x1B[32m"
23 |
24 |
25 |
26 | static char *color_name[139] = { "aliceblue","antiquewhite","aqua","aquamarine","azure",
27 | "beige","bisque","blanchedalmond","blue","blueviolet",
28 | "brown","burlywood","cadetblue","chartreuse","chocolate",
29 | "coral","cornflowerblue","cornsilk","crimson","cyan",
30 | "darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen",
31 | "darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid",
32 | "darkred","darksalmon","darkseagreen","darkslateblue","darkslategray",
33 | "darkturquoise","darkviolet","deeppink","deepskyblue","dimgray",
34 | "dodgerblue","firebrick","floralwhite","forestgreen","fuchsia",
35 | "gainsboro","ghostwhite","gold","goldenrod","gray",
36 | "green","greenyellow","honeydew","hotpink","indianred",
37 | "indigo","ivory","khaki","lavender","lavenderblush",
38 | "lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan",
39 | "lightgoldenrodyellow","lightgreen","lightgrey","lightpink","lightsalmon",
40 | "lightseagreen","lightskyblue","lightslategray","lightsteelblue","lightyellow",
41 | "lime","limegreen","linen","magenta","maroon",
42 | "mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen",
43 | "mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue",
44 | "mintcream","mistyrose","moccasin","navajowhite","navy",
45 | "oldlace","olive","olivedrab","orange","orangered",
46 | "orchid","palegoldenrod","palegreen","paleturquoise","palevioletred",
47 | "papayawhip","peachpuff","peru","pink","plum",
48 | "powderblue","purple","red","rosybrown","royalblue",
49 | "saddlebrown","salmon","sandybrown","seagreen","seashell",
50 | "sienna","silver","skyblue","slateblue","slategray",
51 | "snow","springgreen","steelblue","tan","teal",
52 | "thistle","tomato","turquoise","violet","wheat",
53 | "white","whitesmoke","yellow","yellowgreen"};
54 |
55 | static char *ANSI[139] = {"\x1B[38:5:189m","\x1B[38:5:189m","\x1B[38:5:51m" ,"\x1B[38:5:122m","\x1B[38:5:195m",
56 | "\x1B[38:5:188m","\x1B[38:5:223m","\x1B[38:5:224m","\x1B[38:5:21m" ,"\x1B[38:5:92m",
57 | "\x1B[38:5:124m","\x1B[38:5:180m","\x1B[38:5:73m" ,"\x1B[38:5:118m","\x1B[38:5:172m",
58 | "\x1B[38:5:209m","\x1B[38:5:68m" ,"\x1B[38:5:224m","\x1B[38:5:161m","\x1B[38:5:51m",
59 | "\x1B[38:5:18m" ,"\x1B[38:5:30m" ,"\x1B[38:5:136m","\x1B[38:5:145m","\x1B[38:5:22m",
60 | "\x1B[38:5:144m","\x1B[38:5:90m" ,"\x1B[38:5:64m" ,"\x1B[38:5:208m","\x1B[38:5:128m",
61 | "\x1B[38:5:88m" ,"\x1B[38:5:174m","\x1B[38:5:108m","\x1B[38:5:60m" ,"\x1B[38:5:23m",
62 | "\x1B[38:5:44m" ,"\x1B[38:5:92m" ,"\x1B[38:5:198m","\x1B[38:5:39m" ,"\x1B[38:5:102m",
63 | "\x1B[38:5:33m" ,"\x1B[38:5:124m","\x1B[38:5:224m","\x1B[38:5:28m" ,"\x1B[38:5:201m",
64 | "\x1B[38:5:188m","\x1B[38:5:189m","\x1B[38:5:220m","\x1B[38:5:178m","\x1B[38:5:102m",
65 | "\x1B[38:5:28m" ,"\x1B[38:5:154m","\x1B[38:5:194m","\x1B[38:5:211m","\x1B[38:5:167m",
66 | "\x1B[38:5:54m" ,"\x1B[38:5:230m","\x1B[38:5:186m","\x1B[38:5:188m","\x1B[38:5:224m",
67 | "\x1B[38:5:112m","\x1B[38:5:224m","\x1B[38:5:152m","\x1B[38:5:174m","\x1B[38:5:195m",
68 | "\x1B[38:5:188m","\x1B[38:5:114m","\x1B[38:5:188m","\x1B[38:5:217m","\x1B[38:5:216m",
69 | "\x1B[38:5:37m" ,"\x1B[38:5:116m","\x1B[38:5:103m","\x1B[38:5:146m","\x1B[38:5:230m",
70 | "\x1B[38:5:46m" ,"\x1B[38:5:40m" ,"\x1B[38:5:188m","\x1B[38:5:201m","\x1B[38:5:88m",
71 | "\x1B[38:5:115m","\x1B[38:5:20m" ,"\x1B[38:5:134m","\x1B[38:5:104m","\x1B[38:5:72m",
72 | "\x1B[38:5:104m","\x1B[38:5:43m" ,"\x1B[38:5:80m" ,"\x1B[38:5:126m","\x1B[38:5:18m",
73 | "\x1B[38:5:194m","\x1B[38:5:224m","\x1B[38:5:223m","\x1B[38:5:223m","\x1B[38:5:18m",
74 | "\x1B[38:5:188m","\x1B[38:5:100m","\x1B[38:5:100m","\x1B[38:5:214m","\x1B[38:5:202m",
75 | "\x1B[38:5:176m","\x1B[38:5:187m","\x1B[38:5:114m","\x1B[38:5:152m","\x1B[38:5:174m",
76 | "\x1B[38:5:224m","\x1B[38:5:223m","\x1B[38:5:173m","\x1B[38:5:217m","\x1B[38:5:182m",
77 | "\x1B[38:5:152m","\x1B[38:5:90m" ,"\x1B[38:5:196m","\x1B[38:5:138m","\x1B[38:5:68m",
78 | "\x1B[38:5:94m" ,"\x1B[38:5:174m","\x1B[38:5:179m","\x1B[38:5:29m" ,"\x1B[38:5:224m",
79 | "\x1B[38:5:130m","\x1B[38:5:145m","\x1B[38:5:116m","\x1B[38:5:98m" ,"\x1B[38:5:102m",
80 | "\x1B[38:5:224m","\x1B[38:5:48m" ,"\x1B[38:5:67m" ,"\x1B[38:5:180m","\x1B[38:5:30m",
81 | "\x1B[38:5:182m","\x1B[38:5:203m","\x1B[38:5:80m" ,"\x1B[38:5:176m","\x1B[38:5:187m",
82 | "\x1B[38:5:231m","\x1B[38:5:188m","\x1B[38:5:226m","\x1B[38:5:148m" };
83 |
84 | extern void render_cli(struct dictionary D,struct format_ *format,int color)
85 | {
86 | printf("\n%s%s%s\n", (color<2) ? CLI_DIC_TITLE : "", D.data[NAME], (color<2) ? CLI_RESET : "");
87 | ENTRY *found_item;
88 | ENTRY item;
89 |
90 | if(color<2)
91 | {
92 | if(hcreate(170) == 0) {
93 | printf("Error on hcreate\n");
94 | exit(EXIT_FAILURE);
95 | }
96 |
97 | for(int i=0;i<139;i++)
98 | {
99 | item.key=color_name[i];
100 | item.data=ANSI[i];
101 | hsearch(item, ENTER);
102 | }
103 | }
104 |
105 | char *src=format->string;
106 |
107 | char* CLITagNames[N_TAG] = {
108 | CLI_BOLD,
109 | CLI_ITALIC,
110 | CLI_UNDERLINE,
111 | CLI_FAINT,
112 | "", //[m0] [m1] [m2]...
113 | "",
114 | CLI_FAINT,
115 | CLI_FAINT,
116 | CLI_REF, //url
117 | CLI_FAINT,
118 | CLI_LABELS,
119 | CLI_BOLD,
120 | "", //[lang] [lang ]
121 | CLI_REF ,//[ref] [ref ]
122 | "",
123 | "",
124 | CLI_GREEN, // [c] [c gray] //The order is important. com will be find before c!
125 | CLI_REF
126 | } ;
127 |
128 | if(color==2)
129 | for(int i=0;iN;i++)
145 | {
146 | type=format->tag[i].type;
147 | open=format->tag[i].open;
148 | prop=format->tag[i].properties;
149 |
150 | if(skip<=format->tag[i].pos)
151 | {
152 | len=format->tag[i].pos-skip;
153 | printf("%.*s", len, src + skip);
154 | skip=format->tag[i].pos;
155 |
156 | opened[type]=open;
157 |
158 | // if(type==MARGIN&&open)
159 | // printf("%*s", prop[0]-48, "");
160 |
161 |
162 |
163 | if(open==0)
164 | {
165 | printf("%s",CLI_RESET);
166 | for(int j=0;jdata;
186 | }
187 | printf("%s",temp_color);
188 | }
189 | else
190 | printf("%s",CLITagNames[type] ) ;
191 |
192 |
193 | }
194 | }
195 | }
196 |
197 |
198 |
199 |
200 | if(color<2)
201 | hdestroy();
202 | }
203 |
204 |
205 |
206 |
207 | static const char *table_format="%50.50s %10s %10s %10s %20s %10s ";
208 |
209 | void show_dictionaries_tree(struct dictionary D) {
210 | enum DICTIONARY_STRUCTURE ext=NAME;
211 |
212 | if(D.to_index==0)
213 | {
214 | ext=0;
215 | while(exttag=xrealloc((*format)->tag, (N+1) * sizeof(struct tag));
238 | (*format)->tag[N].properties=NULL;
239 | (*format)->tag[N].pos=pos;
240 | (*format)->tag[N].type=type;
241 | (*format)->tag[N].open=open;
242 | }
243 |
244 |
245 | static const char* GDTagNames[] = {
246 | "b",
247 | "i",
248 | "u",
249 | "*",
250 | "m", //[m0] [m1] [m2]...
251 | "trn",
252 | "ex",
253 | "com]",
254 | "url",
255 | "!trs",
256 | "p",
257 | "'",
258 | "lang", //[lang] [lang ]
259 | "ref",//[ref] [ref ]
260 | "sub]",
261 | "sup]",
262 | "c", // [c] [c gray] //The order is important. com will be find before c!
263 | "s]"
264 | };
265 |
266 | extern void strip_tags(char *src,struct format_ *format)
267 | {
268 |
269 | int len=strlen(src)+1;
270 |
271 | format->string=xmalloc(len*sizeof(char));
272 |
273 | char *orig=src;
274 | char *temp=src;
275 |
276 | int idx=0;
277 |
278 | int open=0;
279 | int i=0;
280 | int N=0;
281 | int word=0;
282 |
283 | for( ; *orig != '\0' ;orig++)
284 | switch(*orig)
285 | {
286 | case '\t':break;
287 | case '\n':
288 | if (word==0) word=idx;
289 | format->string[idx++]=*orig;
290 | break;
291 | case '}':
292 | case '{':
293 | if(*(orig+1)=='{')
294 | while(*(++orig)!= '\0'&&*(orig-1)!='}'&&*(orig++)!='}');
295 | break;
296 | case '[':
297 | open=1;
298 | orig++;
299 | if (*orig== '/')
300 | {
301 | open=0;
302 | orig++;
303 | }
304 | i=0;
305 |
306 | while(itag[N].properties=xmalloc(2 * sizeof(char));
316 | format->tag[N].properties[0]='0';
317 | format->tag[N].properties[1]='\0';
318 | if(*orig>48&&*orig<58)
319 | {
320 | format->tag[N].properties[0]=*orig;
321 | len+=*orig-48;
322 | format->string=xrealloc(format->string, len);
323 | for(int j=0;j<*orig-48;j++)
324 | format->string[idx++]=' ';
325 | }
326 | else
327 | orig--;
328 | }
329 |
330 | if(i==COLOR&&open)
331 | {
332 | orig++;
333 | if(*orig==' ')
334 | {
335 | temp=++orig;
336 | while(*(orig+1) != '\0'&&*(orig+1)!=']')
337 | orig++;
338 | format->tag[N].properties=xmalloc((orig-temp+2) * sizeof(char));
339 | memcpy(format->tag[N].properties, temp, (orig-temp)+2);
340 | format->tag[N].properties[(orig-temp)+1]='\0';
341 | }
342 | else
343 | {
344 | N++;
345 | break;
346 | }
347 | }
348 |
349 |
350 | if(i==MEDIA&&open)
351 | {
352 | orig++;
353 | temp=++orig;
354 | while(*(orig+1) != '\0'&&*(orig+1)!='[')
355 | format->string[idx++]=*(orig++);
356 |
357 | format->string[idx++]=*orig;
358 |
359 | format->tag[N].properties=xmalloc((orig-temp+2) * sizeof(char));
360 | memcpy(format->tag[N].properties, temp, (orig-temp)+2);
361 | format->tag[N].properties[(orig-temp)+1]='\0';
362 | N++;
363 | break;
364 | }
365 |
366 |
367 | N++;
368 | }
369 | while(*orig != '\0'&&*(++orig)!=']');
370 | break;
371 | case '<':
372 | if(*(orig+1)=='<')
373 | {
374 | orig++;
375 | create_tag(&format,N,idx, REF, 1);
376 | N++;
377 | }
378 | else
379 | format->string[idx++]=*orig;
380 | break;
381 |
382 | case '>':
383 | if(*(orig+1)=='>')
384 | {
385 | orig++;
386 | create_tag(&format,N,idx, REF, 0);
387 | N++;
388 | }
389 | else
390 | format->string[idx++]=*orig;
391 | break;
392 | case '\\':
393 | orig++;
394 | format->string[idx++]=*orig;
395 | break;
396 | case '~':
397 | len+=word;
398 | format->string=xrealloc(format->string, len);
399 | temp=src;
400 | for(int j=0;jstring[idx++]=*(temp++);
402 | break;
403 | default:
404 | format->string[idx++]=*orig;
405 | break;
406 | }
407 |
408 | format->string[idx++]= '\0';
409 | format->N=N;
410 |
411 |
412 | return ;
413 | }
414 |
415 | extern void free_format(struct format_ *format){
416 | for(int i=0;iN;i++)
417 | if(format->tag[i].properties)
418 | free(format->tag[i].properties);
419 |
420 | free(format->tag);
421 | free(format->string);
422 | }
423 |
424 | extern int unzip_resources(struct format_ *format, char *path_name_, const char *zipfilename)
425 | {
426 | mkdir(path_name_, 0755);
427 | char *path_name = realpath(path_name_, NULL);
428 |
429 | char *files[512]={NULL};
430 | int fn=0;
431 | int fn_i=0;
432 | int j;
433 | files[fn_i++]="unzip";
434 | files[fn_i++]="-qqju";
435 | files[fn_i++]=(char*)zipfilename;
436 | files[fn_i++]="-d";
437 | files[fn_i++]=path_name;
438 | fn=fn_i;
439 |
440 | for(int i=0; iN;i++)
441 | if(format->tag[i].type==MEDIA&&format->tag[i].open&&format->tag[i].properties)
442 | {
443 | for(j=fn_i;jtag[i].properties, files[j]); j++);
444 |
445 | if(j==fn)
446 | files[fn++]=format->tag[i].properties;
447 | }
448 |
449 |
450 | if (fn>fn_i)
451 | {
452 | pid_t pid;
453 | pid = fork();
454 | if(pid == 0)
455 | {
456 | execvp("unzip",files);
457 | return -1;
458 | }
459 | }
460 |
461 | free(path_name);
462 | return 0;
463 | }
464 |
--------------------------------------------------------------------------------
/format.h:
--------------------------------------------------------------------------------
1 | #include "index.h"
2 |
3 | typedef enum {
4 | BOLD,
5 | ITALIC,
6 | UNDERLINE,
7 | FULL_MODE,
8 | MARGIN,
9 | TRANSLATION,
10 | EXAMPLE,
11 | COMMENT,
12 | URL,
13 | NO_INDEX,
14 | LABEL,
15 | STRESS,
16 | LANG,
17 | REF,
18 | SUB,
19 | SUP,
20 | COLOR,
21 | MEDIA,
22 | N_TAG
23 | } TAG;
24 |
25 | struct format_
26 | {
27 | struct tag
28 | {
29 | TAG type;
30 | size_t pos;
31 | int open;
32 | char *properties;
33 | } *tag;
34 | int N;
35 | char *string;
36 | };
37 |
38 | extern void render_cli(struct dictionary D,struct format_ *format,int color);
39 |
40 | extern int unzip_resources(struct format_ *format, char *path_name, const char *zipfilename);
41 |
42 | extern void show_dictionaries(struct root_ D);
43 |
44 | extern void strip_tags(char *src,struct format_ *format);
45 | extern void free_format(struct format_ *format);
46 |
--------------------------------------------------------------------------------
/gdcv.c:
--------------------------------------------------------------------------------
1 | #include //realpath
2 | #include //mkdir
3 | #include //argp
4 | #include //argp
5 | #include // strcmp
6 | #include //perror printf FILENAME_MAX
7 |
8 | #include "utils.h"
9 | #include "index.h"
10 | #include "format.h"
11 |
12 |
13 | const char *argp_program_version = "gdcv 0.1";
14 | const char *argp_program_bug_address = "";
15 |
16 | static char doc[] = "Command Line version of GoldenDict"
17 | "\noptions:"
18 | "\vTo look up a word \"cat\": gdcv cat.\n"
19 | "To search words with substring \"cat\": gdcv *cat\n"
20 | "To index directory: gdcv -i /usr/share/dict";
21 |
22 | /* A description of the arguments we accept. */
23 | static char args_doc[] = "WORD or -i PATH";
24 |
25 | static struct argp_option options[] = {
26 | {"index", 'i', 0, 0, "Index dictionary files in the chosen directory" ,0},
27 | {"color", 'c', "THEME", 0, "The color theme of the output: default, decolorized, full" ,0},
28 | {"unzip", 'u', "DIRECTORY", 0, "Unzip resource files" ,0},
29 | {"zip", 'z', 0, 0, "zip dictionary file in dsl format" ,0},
30 | { 0 }
31 | };
32 |
33 | struct arguments_
34 | {
35 | char *word;
36 | char *unzip;
37 | int to_index;
38 | char **index_path;
39 | int color;
40 | int to_zip;
41 | char **filename;
42 | };
43 |
44 |
45 | static error_t parse_opt (int key, char *arg, struct argp_state *state)
46 | {
47 | struct arguments_ *arguments = state->input;
48 | switch (key)
49 | {
50 | case 'z':
51 | arguments->to_zip = 1;
52 | break;
53 | case 'u':
54 | arguments->unzip = arg;
55 | break;
56 | case 'i':
57 | arguments->to_index = 1;
58 | break;
59 | case 'c':
60 | if(strcmp(arg, "default")==0)
61 | arguments->color = 0;
62 | else if (strcmp(arg, "full")==0)
63 | arguments->color = 1;
64 | else if (strcmp(arg, "nocolor")==0)
65 | arguments->color = 2;
66 | else
67 | {
68 | printf("Expected argument for option -c is one of {default, full, nocolor}.");
69 | arguments->color = 0;
70 | }
71 | break;
72 |
73 |
74 | case ARGP_KEY_NO_ARGS:
75 | argp_usage (state);
76 | break;
77 |
78 | case ARGP_KEY_ARG:
79 | if(arguments->to_index)
80 | {
81 | arguments->index_path = &state->argv[state->next-1];
82 | state->next = state->argc;
83 | }
84 | else if(arguments->to_zip)
85 | {
86 | arguments->filename = &state->argv[state->next-1];
87 | state->next = state->argc;
88 | }
89 | else
90 | arguments->word=arg;
91 | break;
92 |
93 | default:
94 | return ARGP_ERR_UNKNOWN;
95 | }
96 | return 0;
97 | }
98 |
99 | static struct argp argp = { options, parse_opt, args_doc, doc , 0, 0, 0 };
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 | int main(int argc, char *argv[])
109 | {
110 | struct arguments_ arguments={"","",0,NULL,0,0,NULL};
111 |
112 | argp_parse (&argp, argc, argv, 0, 0, &arguments);
113 |
114 | char *index_path=NULL;
115 |
116 | if (getenv("XDG_CONFIG_HOME") != NULL)
117 | xasprintf(&index_path, "%s/gdcv", getenv("XDG_CONFIG_HOME"));
118 | else if ( getenv("HOME") != NULL )
119 | xasprintf(&index_path, "%s/.config/gdcv", getenv("HOME"));
120 | else
121 | {
122 | printf("The variables HOME and XDG_CONFIG_HOME are not defined");
123 | exit(EXIT_FAILURE);
124 | }
125 |
126 |
127 |
128 | mkdir(index_path, 0755);
129 |
130 |
131 | if(arguments.to_index)
132 | {
133 | int N=0;
134 | char **paths=NULL;
135 |
136 | for(int i=0;arguments.index_path[i];i++)
137 | {
138 | char *temp_path=realpath(arguments.index_path[i], NULL);
139 |
140 | if(!temp_path)
141 | printf("The directory %s does not exist\n",arguments.index_path[i]);
142 | else
143 | {
144 | paths= xrealloc(paths, (N+1)*sizeof(char *));
145 | paths[N]=temp_path;
146 | N++;
147 | }
148 |
149 | }
150 | //fts_open demands the array must be terminated by a NULL pointer.
151 | paths= xrealloc(paths, (N+1)*sizeof(char *));
152 | paths[N]=NULL;
153 |
154 | struct root_ D = index_directories (paths);
155 |
156 | for(int i=0;iDic , index->N, Art[i].dic);
231 | Art[i].full_definition= word_fetch(Dic, Art[i].start, Art[i].size);
232 |
233 |
234 |
235 | struct format_ format;
236 | format.tag=NULL;
237 | strip_tags(Art[i].full_definition,&format);
238 | render_cli(*Dic, &format,arguments.color);
239 | if(strcmp(arguments.unzip,"")&&Dic->data[RESOURCES]!=NULL&&strcmp(Dic->data[RESOURCES],""))
240 | unzip_resources(&format, arguments.unzip, Dic->data[RESOURCES]);
241 |
242 | free(Art[i].full_definition);
243 | free(Art[i].word);
244 |
245 | free_format(&format);
246 |
247 | }
248 |
249 |
250 |
251 | free(Art);
252 | }
253 | else
254 | printf("The word %s is not found", arguments.word);
255 | }
256 |
257 |
258 | if(arguments.word[0]=='*')
259 | {
260 | int art=0;
261 | struct article *Art=NULL;
262 | look_for_a_word(index,&arguments.word[1],&art, &Art,0);
263 | if(art>0)
264 | printf("Similar words\n");
265 |
266 | for (int i=0; i") 'gdcv-show-entry)
202 | (define-key map (kbd "") 'gdcv-press-media)
203 | (define-key map (kbd "SPC") 'scroll-up)
204 | (define-key map (kbd "d") 'gdcv-search-word)
205 | map)
206 | "Keymap for `gdcv-mode'.")
207 |
208 |
209 | (define-derived-mode gdcv-mode nil "GDCV"
210 | "Major mode to look up word through gdcv."
211 | ;;(setq font-lock-defaults '(gdcv-mode-font-lock-keywords))
212 | (setq font-lock-mode nil)
213 | (outline-minor-mode)
214 | (outline-hide-body)
215 | (setq buffer-read-only t)
216 | )
217 |
218 |
219 | (defvar gdcv-previous-window-conf nil
220 | "Window configuration before switching to sdcv buffer.")
221 |
222 |
223 | (defun gdcv-get-buffer ()
224 | "Get the gdcv buffer. Create one if there's none."
225 | (let ((buffer (get-buffer-create gdcv-buffer)))
226 | (with-current-buffer buffer
227 | (unless (eq major-mode 'gdcv-mode)
228 | (gdcv-mode)))
229 | buffer))
230 |
231 |
232 | (defun gdcv-goto-gdcv ()
233 | "Switch to gdcv buffer in other window."
234 | (interactive)
235 | (unless (eq (current-buffer)
236 | (gdcv-get-buffer))
237 | (setq gdcv-previous-window-conf (current-window-configuration)))
238 | (let* ((buffer (gdcv-get-buffer))
239 | (window (get-buffer-window buffer)))
240 | (if (null window)
241 | (switch-to-buffer-other-window buffer)
242 | (select-window window))))
243 |
244 | (defun gdcv-return-from-gdcv ()
245 | "Bury gdcv buffer and restore the previous window configuration."
246 | (interactive)
247 | (if (window-configuration-p gdcv-previous-window-conf)
248 | (progn
249 | (set-window-configuration gdcv-previous-window-conf)
250 | (setq gdcv-previous-window-conf nil)
251 | (bury-buffer (gdcv-get-buffer)))
252 | (bury-buffer)))
253 |
254 |
255 |
256 | (setf (alist-get 'ivy-gdcv ivy-more-chars-alist) 1)
257 |
258 |
259 |
260 |
261 | (defun ivy-gdcv ()
262 | "Use ivy-read to select your search history."
263 | (interactive)
264 | (gdcv--handler)
265 |
266 | (ivy-read "Search gdcv: " #'(lambda (word )
267 | (or
268 | (ivy-more-chars)
269 | (gdcv--look-word word)
270 | ))
271 | :dynamic-collection t
272 | :action #'gdcv-choose-defs
273 | :caller 'ivy-gdcv))
274 |
275 |
276 | (defun gdcv-search-word (word)
277 | (interactive "P")
278 | (unless word
279 | (setq word (if (and transient-mark-mode mark-active)
280 | (buffer-substring-no-properties (region-beginning) (region-end))
281 | (current-word nil t)))
282 | (unless word
283 |
284 | ;;(setq word (read-string (format "Search the dictionary for: " )))
285 | (ivy-gdcv)
286 | ))
287 | (when word
288 | (gdcv-choose-defs word)))
289 |
290 | (provide 'gdcv)
291 |
--------------------------------------------------------------------------------
/index.h:
--------------------------------------------------------------------------------
1 | /* We use radix tree to build index file.
2 | * The implementation is based on the one of libkmod (interface to kernel module operations )
3 | * (https://git.kernel.org/pub/scm/utils/kernel/kmod/kmod.git)
4 | *
5 | *
6 | * Few bugs are introduced.
7 | * First, all dictionary files with *dsl.dz extension are found in the given directories.
8 | * These files are read with gzread line by line, all words are going through Unicode normalization (utf8proc library is used).
9 | * The index contains two files. index_value.db and index_key.
10 | *
11 | *
12 | *
13 | * Disk format for index_value.db:
14 | *
15 | *
16 | * char *word //null terminated
17 | * all words are grouped by their unicode normalisation form, so: dog,DOG, Dög are in one group.
18 | * To save space, if a word is equal to the key then it is skipped.
19 | *
20 | *
21 | * char * dictionary_id:start_offset:end_offset: //null terminated
22 | * start_offset and end_offset are positions of the word translation in dictionary file.
23 | * The file is compressed with dictzip.
24 | *
25 | *
26 | *
27 | *
28 | * Disk format for index_key.db:
29 | *
30 | * uint32_t magic = INDEX_MAGIC;
31 | * uint32_t version = INDEX_VERSION;
32 | *
33 | *
34 | * List of dictionaries:
35 | *
36 | * uint32_t dictionary_id;
37 | * char* basename;//null terminated
38 | * char* filename, abbreviation_file,icon,zip_file_with_resources,name,translation_from,translation_to; //null terminated
39 | *
40 | *
41 | * uint32_t root_offset;
42 | *
43 | * (node_offset & INDEX_NODE_MASK) specifies the file offset of nodes:
44 | *
45 | * char[] prefix; // nul terminated
46 | *
47 | * unsigned char N; //number of childrens
48 | * char children[N];
49 | * uint32_t grand_childrens[N]; information about chars which are in the children node and below.
50 | * If grand_childrens& (1 << (ch/32)) ), then ch is in the branch somewhere. This double search speed.
51 | * uint32_t children[N];
52 | *
53 | * unsigned char v_N; //number of values.
54 | *
55 | * uint32_t start;
56 | * uint32_t end;
57 | * start and end position for list of words similar to the key and the list of dictionaries in the file index_value.db
58 | *
59 | *
60 | * (node_offset & INDEX_NODE_FLAGS) indicates which fields are present.
61 | * Empty prefixes are omitted, leaf nodes omit the three child-related fields.
62 | *
63 | * Implementation is based on a radix tree, or "trie".
64 | * Each arc from parent to child is labelled with a character.
65 | * Each path from the root represents a string.
66 | *
67 | * == Example strings ==
68 | *
69 | * ask
70 | * ate
71 | * on
72 | * once
73 | * one
74 | *
75 | * == Key ==
76 | * + Normal node
77 | * * Marked node, representing a key and it's values.
78 | *
79 | * +
80 | * |-a-+-s-+-k-*
81 | * | |
82 | * | `-t-+-e-*
83 | * |
84 | * `-o-+-n-*-c-+-e-*
85 | * |
86 | * `-e-*
87 | *
88 | * Naive implementations tend to be very space inefficient; child pointers
89 | * are stored in arrays indexed by character, but most child pointers are null.
90 | *
91 | * Our implementation uses a scheme described by Wikipedia as a Patrica trie,
92 | *
93 | * "easiest to understand as a space-optimized trie where
94 | * each node with only one child is merged with its child"
95 | *
96 | * +
97 | * |-a-+-sk-*
98 | * | |
99 | * | `-te-*
100 | * |
101 | * `-on-*-ce-*
102 | * |
103 | * `-e-*
104 | *
105 | * We still use arrays of child pointers indexed by a single character;
106 | * the remaining characters of the label are stored as a "prefix" in the child.
107 | *
108 | * The paper describing the original Patrica trie works on individiual bits -
109 | * each node has a maximum of two children, which increases space efficiency.
110 | * However for this application it is simpler to use the ASCII character set.
111 | * Since the index file is read-only, it can be compressed by omitting null
112 | * child pointers at the start and end of arrays.
113 | */
114 |
115 | /* Format of node offsets within index file */
116 |
117 | #ifndef _INDEX_H
118 | #define _INDEX_H
119 |
120 | #include //FILE
121 | #include //uint32_t
122 | #include //stat
123 |
124 | #include "dictzip.h"
125 |
126 |
127 | struct childrens {
128 | char ch; /* path compression */
129 | struct index_node *node; /* indexed by character */
130 | unsigned char gc; //breaf information about grand childrens.
131 | };
132 |
133 | struct index_value{
134 | char *word;
135 | char *value;
136 | };
137 |
138 | struct index_node
139 | {
140 | char *prefix; /* path compression */
141 | char *key;
142 | int v_N; //Number of values,
143 | struct index_value *values;
144 | unsigned char c_N; //Number of childrens,
145 | struct childrens *childrens; //array of childrens.
146 | };
147 |
148 |
149 |
150 | enum DICTIONARY_STRUCTURE {
151 | DICTIONARY_FILE,
152 | FILE_ABRV,
153 | ICON,
154 | RESOURCES,
155 | NAME,
156 | FROM,
157 | TO,
158 | DATA
159 | };
160 |
161 | struct dictionary {
162 | char *base;
163 | int id;
164 | char *data[7]; //0 -.dls.dz// 1-_abrv.dls//2-.bmp//3-.dls.dz.zip//4-NAME//5-FROM//6-TO
165 | char *encoding;
166 | int to_index;
167 | } ;
168 |
169 | struct index_mm {
170 | void *mm;
171 | uint32_t root_offset;
172 | size_t size;
173 | int N;
174 | struct dictionary *Dic;
175 | dictData * dz;
176 | };
177 |
178 | struct root_
179 | {
180 | struct dictionary *Dic;
181 | int N;
182 | int indexed;
183 | };
184 |
185 | struct article {
186 | char *word;
187 | char *definition;
188 | char *full_definition;
189 | int dic;
190 | size_t start;
191 | size_t size;
192 | };
193 |
194 |
195 |
196 |
197 | extern struct root_ index_directories (char ** dir_list);
198 |
199 | extern struct index_node *index_create(struct root_ D);
200 |
201 | extern void index_destroy(struct index_node *node);
202 |
203 | extern void root_destroy(struct root_ D);
204 |
205 | extern void index_write(struct index_node *node, struct root_ D, char *index_path);
206 |
207 |
208 | extern struct index_mm *index_mm_open( char *index_path);
209 |
210 |
211 | extern void index_mm_close(struct index_mm *idx);
212 |
213 | extern int decode_articles(char *word,struct article **cards,int *cards_number, struct index_mm *index);
214 |
215 | extern struct dictionary * get_dictionary(struct dictionary *Dic, int N, int id);
216 |
217 | extern char * word_fetch(struct dictionary * Dic, int start, int size);
218 |
219 |
220 |
221 | extern void look_for_a_word(struct index_mm *index,char *word,int *art, struct article **Art,int is_prefix);
222 |
223 |
224 | #endif
225 |
--------------------------------------------------------------------------------
/utfproc/utf8proc.c:
--------------------------------------------------------------------------------
1 | /* -*- mode: c; c-basic-offset: 2; tab-width: 2; indent-tabs-mode: nil -*- */
2 | /*
3 | * Copyright (c) 2014-2019 Steven G. Johnson, Jiahao Chen, Peter Colberg, Tony Kelman, Scott P. Jones, and other contributors.
4 | * Copyright (c) 2009 Public Software Group e. V., Berlin, Germany
5 | *
6 | * Permission is hereby granted, free of charge, to any person obtaining a
7 | * copy of this software and associated documentation files (the "Software"),
8 | * to deal in the Software without restriction, including without limitation
9 | * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 | * and/or sell copies of the Software, and to permit persons to whom the
11 | * Software is furnished to do so, subject to the following conditions:
12 | *
13 | * The above copyright notice and this permission notice shall be included in
14 | * all copies or substantial portions of the Software.
15 | *
16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22 | * DEALINGS IN THE SOFTWARE.
23 | */
24 |
25 | /*
26 | * This library contains derived data from a modified version of the
27 | * Unicode data files.
28 | *
29 | * The original data files are available at
30 | * http://www.unicode.org/Public/UNIDATA/
31 | *
32 | * Please notice the copyright statement in the file "utf8proc_data.c".
33 | */
34 |
35 |
36 | /*
37 | * File name: utf8proc.c
38 | *
39 | * Description:
40 | * Implementation of libutf8proc.
41 | */
42 |
43 |
44 | #include "utf8proc.h"
45 |
46 | #ifndef SSIZE_MAX
47 | #define SSIZE_MAX ((size_t)SIZE_MAX/2)
48 | #endif
49 | #ifndef UINT16_MAX
50 | # define UINT16_MAX 65535U
51 | #endif
52 |
53 | #include "utf8proc_data.c"
54 |
55 |
56 | UTF8PROC_DLLEXPORT const utf8proc_int8_t utf8proc_utf8class[256] = {
57 | 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
58 | 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
59 | 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
60 | 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
61 | 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
62 | 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
63 | 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
64 | 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
65 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
66 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
67 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
68 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
69 | 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
70 | 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
71 | 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
72 | 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0 };
73 |
74 | #define UTF8PROC_HANGUL_SBASE 0xAC00
75 | #define UTF8PROC_HANGUL_LBASE 0x1100
76 | #define UTF8PROC_HANGUL_VBASE 0x1161
77 | #define UTF8PROC_HANGUL_TBASE 0x11A7
78 | #define UTF8PROC_HANGUL_LCOUNT 19
79 | #define UTF8PROC_HANGUL_VCOUNT 21
80 | #define UTF8PROC_HANGUL_TCOUNT 28
81 | #define UTF8PROC_HANGUL_NCOUNT 588
82 | #define UTF8PROC_HANGUL_SCOUNT 11172
83 | /* END is exclusive */
84 | #define UTF8PROC_HANGUL_L_START 0x1100
85 | #define UTF8PROC_HANGUL_L_END 0x115A
86 | #define UTF8PROC_HANGUL_L_FILLER 0x115F
87 | #define UTF8PROC_HANGUL_V_START 0x1160
88 | #define UTF8PROC_HANGUL_V_END 0x11A3
89 | #define UTF8PROC_HANGUL_T_START 0x11A8
90 | #define UTF8PROC_HANGUL_T_END 0x11FA
91 | #define UTF8PROC_HANGUL_S_START 0xAC00
92 | #define UTF8PROC_HANGUL_S_END 0xD7A4
93 |
94 | /* Should follow semantic-versioning rules (semver.org) based on API
95 | compatibility. (Note that the shared-library version number will
96 | be different, being based on ABI compatibility.): */
97 | #define STRINGIZEx(x) #x
98 | #define STRINGIZE(x) STRINGIZEx(x)
99 | UTF8PROC_DLLEXPORT const char *utf8proc_version(void) {
100 | return STRINGIZE(UTF8PROC_VERSION_MAJOR) "." STRINGIZE(UTF8PROC_VERSION_MINOR) "." STRINGIZE(UTF8PROC_VERSION_PATCH) "";
101 | }
102 |
103 | UTF8PROC_DLLEXPORT const char *utf8proc_unicode_version(void) {
104 | return "12.1.0";
105 | }
106 |
107 | UTF8PROC_DLLEXPORT const char *utf8proc_errmsg(utf8proc_ssize_t errcode) {
108 | switch (errcode) {
109 | case UTF8PROC_ERROR_NOMEM:
110 | return "Memory for processing UTF-8 data could not be allocated.";
111 | case UTF8PROC_ERROR_OVERFLOW:
112 | return "UTF-8 string is too long to be processed.";
113 | case UTF8PROC_ERROR_INVALIDUTF8:
114 | return "Invalid UTF-8 string";
115 | case UTF8PROC_ERROR_NOTASSIGNED:
116 | return "Unassigned Unicode code point found in UTF-8 string.";
117 | case UTF8PROC_ERROR_INVALIDOPTS:
118 | return "Invalid options for UTF-8 processing chosen.";
119 | default:
120 | return "An unknown error occurred while processing UTF-8 data.";
121 | }
122 | }
123 |
124 | #define utf_cont(ch) (((ch) & 0xc0) == 0x80)
125 | UTF8PROC_DLLEXPORT utf8proc_ssize_t utf8proc_iterate(
126 | const utf8proc_uint8_t *str, utf8proc_ssize_t strlen, utf8proc_int32_t *dst
127 | ) {
128 | utf8proc_uint32_t uc;
129 | const utf8proc_uint8_t *end;
130 |
131 | *dst = -1;
132 | if (!strlen) return 0;
133 | end = str + ((strlen < 0) ? 4 : strlen);
134 | uc = *str++;
135 | if (uc < 0x80) {
136 | *dst = uc;
137 | return 1;
138 | }
139 | // Must be between 0xc2 and 0xf4 inclusive to be valid
140 | if ((uc - 0xc2) > (0xf4-0xc2)) return UTF8PROC_ERROR_INVALIDUTF8;
141 | if (uc < 0xe0) { // 2-byte sequence
142 | // Must have valid continuation character
143 | if (str >= end || !utf_cont(*str)) return UTF8PROC_ERROR_INVALIDUTF8;
144 | *dst = ((uc & 0x1f)<<6) | (*str & 0x3f);
145 | return 2;
146 | }
147 | if (uc < 0xf0) { // 3-byte sequence
148 | if ((str + 1 >= end) || !utf_cont(*str) || !utf_cont(str[1]))
149 | return UTF8PROC_ERROR_INVALIDUTF8;
150 | // Check for surrogate chars
151 | if (uc == 0xed && *str > 0x9f)
152 | return UTF8PROC_ERROR_INVALIDUTF8;
153 | uc = ((uc & 0xf)<<12) | ((*str & 0x3f)<<6) | (str[1] & 0x3f);
154 | if (uc < 0x800)
155 | return UTF8PROC_ERROR_INVALIDUTF8;
156 | *dst = uc;
157 | return 3;
158 | }
159 | // 4-byte sequence
160 | // Must have 3 valid continuation characters
161 | if ((str + 2 >= end) || !utf_cont(*str) || !utf_cont(str[1]) || !utf_cont(str[2]))
162 | return UTF8PROC_ERROR_INVALIDUTF8;
163 | // Make sure in correct range (0x10000 - 0x10ffff)
164 | if (uc == 0xf0) {
165 | if (*str < 0x90) return UTF8PROC_ERROR_INVALIDUTF8;
166 | } else if (uc == 0xf4) {
167 | if (*str > 0x8f) return UTF8PROC_ERROR_INVALIDUTF8;
168 | }
169 | *dst = ((uc & 7)<<18) | ((*str & 0x3f)<<12) | ((str[1] & 0x3f)<<6) | (str[2] & 0x3f);
170 | return 4;
171 | }
172 |
173 | UTF8PROC_DLLEXPORT utf8proc_bool utf8proc_codepoint_valid(utf8proc_int32_t uc) {
174 | return (((utf8proc_uint32_t)uc)-0xd800 > 0x07ff) && ((utf8proc_uint32_t)uc < 0x110000);
175 | }
176 |
177 | UTF8PROC_DLLEXPORT utf8proc_ssize_t utf8proc_encode_char(utf8proc_int32_t uc, utf8proc_uint8_t *dst) {
178 | if (uc < 0x00) {
179 | return 0;
180 | } else if (uc < 0x80) {
181 | dst[0] = (utf8proc_uint8_t) uc;
182 | return 1;
183 | } else if (uc < 0x800) {
184 | dst[0] = (utf8proc_uint8_t)(0xC0 + (uc >> 6));
185 | dst[1] = (utf8proc_uint8_t)(0x80 + (uc & 0x3F));
186 | return 2;
187 | // Note: we allow encoding 0xd800-0xdfff here, so as not to change
188 | // the API, however, these are actually invalid in UTF-8
189 | } else if (uc < 0x10000) {
190 | dst[0] = (utf8proc_uint8_t)(0xE0 + (uc >> 12));
191 | dst[1] = (utf8proc_uint8_t)(0x80 + ((uc >> 6) & 0x3F));
192 | dst[2] = (utf8proc_uint8_t)(0x80 + (uc & 0x3F));
193 | return 3;
194 | } else if (uc < 0x110000) {
195 | dst[0] = (utf8proc_uint8_t)(0xF0 + (uc >> 18));
196 | dst[1] = (utf8proc_uint8_t)(0x80 + ((uc >> 12) & 0x3F));
197 | dst[2] = (utf8proc_uint8_t)(0x80 + ((uc >> 6) & 0x3F));
198 | dst[3] = (utf8proc_uint8_t)(0x80 + (uc & 0x3F));
199 | return 4;
200 | } else return 0;
201 | }
202 |
203 | /* internal version used for inserting 0xff bytes between graphemes */
204 | static utf8proc_ssize_t charbound_encode_char(utf8proc_int32_t uc, utf8proc_uint8_t *dst) {
205 | if (uc < 0x00) {
206 | if (uc == -1) { /* internal value used for grapheme breaks */
207 | dst[0] = (utf8proc_uint8_t)0xFF;
208 | return 1;
209 | }
210 | return 0;
211 | } else if (uc < 0x80) {
212 | dst[0] = (utf8proc_uint8_t)uc;
213 | return 1;
214 | } else if (uc < 0x800) {
215 | dst[0] = (utf8proc_uint8_t)(0xC0 + (uc >> 6));
216 | dst[1] = (utf8proc_uint8_t)(0x80 + (uc & 0x3F));
217 | return 2;
218 | } else if (uc < 0x10000) {
219 | dst[0] = (utf8proc_uint8_t)(0xE0 + (uc >> 12));
220 | dst[1] = (utf8proc_uint8_t)(0x80 + ((uc >> 6) & 0x3F));
221 | dst[2] = (utf8proc_uint8_t)(0x80 + (uc & 0x3F));
222 | return 3;
223 | } else if (uc < 0x110000) {
224 | dst[0] = (utf8proc_uint8_t)(0xF0 + (uc >> 18));
225 | dst[1] = (utf8proc_uint8_t)(0x80 + ((uc >> 12) & 0x3F));
226 | dst[2] = (utf8proc_uint8_t)(0x80 + ((uc >> 6) & 0x3F));
227 | dst[3] = (utf8proc_uint8_t)(0x80 + (uc & 0x3F));
228 | return 4;
229 | } else return 0;
230 | }
231 |
232 | /* internal "unsafe" version that does not check whether uc is in range */
233 | static const utf8proc_property_t *unsafe_get_property(utf8proc_int32_t uc) {
234 | /* ASSERT: uc >= 0 && uc < 0x110000 */
235 | return utf8proc_properties + (
236 | utf8proc_stage2table[
237 | utf8proc_stage1table[uc >> 8] + (uc & 0xFF)
238 | ]
239 | );
240 | }
241 |
242 | UTF8PROC_DLLEXPORT const utf8proc_property_t *utf8proc_get_property(utf8proc_int32_t uc) {
243 | return uc < 0 || uc >= 0x110000 ? utf8proc_properties : unsafe_get_property(uc);
244 | }
245 |
246 | /* return whether there is a grapheme break between boundclasses lbc and tbc
247 | (according to the definition of extended grapheme clusters)
248 |
249 | Rule numbering refers to TR29 Version 29 (Unicode 9.0.0):
250 | http://www.unicode.org/reports/tr29/tr29-29.html
251 |
252 | CAVEATS:
253 | Please note that evaluation of GB10 (grapheme breaks between emoji zwj sequences)
254 | and GB 12/13 (regional indicator code points) require knowledge of previous characters
255 | and are thus not handled by this function. This may result in an incorrect break before
256 | an E_Modifier class codepoint and an incorrectly missing break between two
257 | REGIONAL_INDICATOR class code points if such support does not exist in the caller.
258 |
259 | See the special support in grapheme_break_extended, for required bookkeeping by the caller.
260 | */
261 | static utf8proc_bool grapheme_break_simple(int lbc, int tbc) {
262 | return
263 | (lbc == UTF8PROC_BOUNDCLASS_START) ? true : // GB1
264 | (lbc == UTF8PROC_BOUNDCLASS_CR && // GB3
265 | tbc == UTF8PROC_BOUNDCLASS_LF) ? false : // ---
266 | (lbc >= UTF8PROC_BOUNDCLASS_CR && lbc <= UTF8PROC_BOUNDCLASS_CONTROL) ? true : // GB4
267 | (tbc >= UTF8PROC_BOUNDCLASS_CR && tbc <= UTF8PROC_BOUNDCLASS_CONTROL) ? true : // GB5
268 | (lbc == UTF8PROC_BOUNDCLASS_L && // GB6
269 | (tbc == UTF8PROC_BOUNDCLASS_L || // ---
270 | tbc == UTF8PROC_BOUNDCLASS_V || // ---
271 | tbc == UTF8PROC_BOUNDCLASS_LV || // ---
272 | tbc == UTF8PROC_BOUNDCLASS_LVT)) ? false : // ---
273 | ((lbc == UTF8PROC_BOUNDCLASS_LV || // GB7
274 | lbc == UTF8PROC_BOUNDCLASS_V) && // ---
275 | (tbc == UTF8PROC_BOUNDCLASS_V || // ---
276 | tbc == UTF8PROC_BOUNDCLASS_T)) ? false : // ---
277 | ((lbc == UTF8PROC_BOUNDCLASS_LVT || // GB8
278 | lbc == UTF8PROC_BOUNDCLASS_T) && // ---
279 | tbc == UTF8PROC_BOUNDCLASS_T) ? false : // ---
280 | (tbc == UTF8PROC_BOUNDCLASS_EXTEND || // GB9
281 | tbc == UTF8PROC_BOUNDCLASS_ZWJ || // ---
282 | tbc == UTF8PROC_BOUNDCLASS_SPACINGMARK || // GB9a
283 | lbc == UTF8PROC_BOUNDCLASS_PREPEND) ? false : // GB9b
284 | (lbc == UTF8PROC_BOUNDCLASS_E_ZWG && // GB11 (requires additional handling below)
285 | tbc == UTF8PROC_BOUNDCLASS_EXTENDED_PICTOGRAPHIC) ? false : // ----
286 | (lbc == UTF8PROC_BOUNDCLASS_REGIONAL_INDICATOR && // GB12/13 (requires additional handling below)
287 | tbc == UTF8PROC_BOUNDCLASS_REGIONAL_INDICATOR) ? false : // ----
288 | true; // GB999
289 | }
290 |
291 | static utf8proc_bool grapheme_break_extended(int lbc, int tbc, utf8proc_int32_t *state)
292 | {
293 | int lbc_override = ((state && *state != UTF8PROC_BOUNDCLASS_START)
294 | ? *state : lbc);
295 | utf8proc_bool break_permitted = grapheme_break_simple(lbc_override, tbc);
296 | if (state) {
297 | // Special support for GB 12/13 made possible by GB999. After two RI
298 | // class codepoints we want to force a break. Do this by resetting the
299 | // second RI's bound class to UTF8PROC_BOUNDCLASS_OTHER, to force a break
300 | // after that character according to GB999 (unless of course such a break is
301 | // forbidden by a different rule such as GB9).
302 | if (*state == tbc && tbc == UTF8PROC_BOUNDCLASS_REGIONAL_INDICATOR)
303 | *state = UTF8PROC_BOUNDCLASS_OTHER;
304 | // Special support for GB11 (emoji extend* zwj / emoji)
305 | else if (*state == UTF8PROC_BOUNDCLASS_EXTENDED_PICTOGRAPHIC) {
306 | if (tbc == UTF8PROC_BOUNDCLASS_EXTEND) // fold EXTEND codepoints into emoji
307 | *state = UTF8PROC_BOUNDCLASS_EXTENDED_PICTOGRAPHIC;
308 | else if (tbc == UTF8PROC_BOUNDCLASS_ZWJ)
309 | *state = UTF8PROC_BOUNDCLASS_E_ZWG; // state to record emoji+zwg combo
310 | else
311 | *state = tbc;
312 | }
313 | else
314 | *state = tbc;
315 | }
316 | return break_permitted;
317 | }
318 |
319 | UTF8PROC_DLLEXPORT utf8proc_bool utf8proc_grapheme_break_stateful(
320 | utf8proc_int32_t c1, utf8proc_int32_t c2, utf8proc_int32_t *state) {
321 |
322 | return grapheme_break_extended(utf8proc_get_property(c1)->boundclass,
323 | utf8proc_get_property(c2)->boundclass,
324 | state);
325 | }
326 |
327 |
328 | UTF8PROC_DLLEXPORT utf8proc_bool utf8proc_grapheme_break(
329 | utf8proc_int32_t c1, utf8proc_int32_t c2) {
330 | return utf8proc_grapheme_break_stateful(c1, c2, NULL);
331 | }
332 |
333 | static utf8proc_int32_t seqindex_decode_entry(const utf8proc_uint16_t **entry)
334 | {
335 | utf8proc_int32_t entry_cp = **entry;
336 | if ((entry_cp & 0xF800) == 0xD800) {
337 | *entry = *entry + 1;
338 | entry_cp = ((entry_cp & 0x03FF) << 10) | (**entry & 0x03FF);
339 | entry_cp += 0x10000;
340 | }
341 | return entry_cp;
342 | }
343 |
344 | static utf8proc_int32_t seqindex_decode_index(const utf8proc_uint32_t seqindex)
345 | {
346 | const utf8proc_uint16_t *entry = &utf8proc_sequences[seqindex];
347 | return seqindex_decode_entry(&entry);
348 | }
349 |
350 | static utf8proc_ssize_t seqindex_write_char_decomposed(utf8proc_uint16_t seqindex, utf8proc_int32_t *dst, utf8proc_ssize_t bufsize, utf8proc_option_t options, int *last_boundclass) {
351 | utf8proc_ssize_t written = 0;
352 | const utf8proc_uint16_t *entry = &utf8proc_sequences[seqindex & 0x1FFF];
353 | int len = seqindex >> 13;
354 | if (len >= 7) {
355 | len = *entry;
356 | entry++;
357 | }
358 | for (; len >= 0; entry++, len--) {
359 | utf8proc_int32_t entry_cp = seqindex_decode_entry(&entry);
360 |
361 | written += utf8proc_decompose_char(entry_cp, dst+written,
362 | (bufsize > written) ? (bufsize - written) : 0, options,
363 | last_boundclass);
364 | if (written < 0) return UTF8PROC_ERROR_OVERFLOW;
365 | }
366 | return written;
367 | }
368 |
369 | UTF8PROC_DLLEXPORT utf8proc_int32_t utf8proc_tolower(utf8proc_int32_t c)
370 | {
371 | utf8proc_int32_t cl = utf8proc_get_property(c)->lowercase_seqindex;
372 | return cl != UINT16_MAX ? seqindex_decode_index(cl) : c;
373 | }
374 |
375 | UTF8PROC_DLLEXPORT utf8proc_int32_t utf8proc_toupper(utf8proc_int32_t c)
376 | {
377 | utf8proc_int32_t cu = utf8proc_get_property(c)->uppercase_seqindex;
378 | return cu != UINT16_MAX ? seqindex_decode_index(cu) : c;
379 | }
380 |
381 | UTF8PROC_DLLEXPORT utf8proc_int32_t utf8proc_totitle(utf8proc_int32_t c)
382 | {
383 | utf8proc_int32_t cu = utf8proc_get_property(c)->titlecase_seqindex;
384 | return cu != UINT16_MAX ? seqindex_decode_index(cu) : c;
385 | }
386 |
387 | /* return a character width analogous to wcwidth (except portable and
388 | hopefully less buggy than most system wcwidth functions). */
389 | UTF8PROC_DLLEXPORT int utf8proc_charwidth(utf8proc_int32_t c) {
390 | return utf8proc_get_property(c)->charwidth;
391 | }
392 |
393 | UTF8PROC_DLLEXPORT utf8proc_category_t utf8proc_category(utf8proc_int32_t c) {
394 | return utf8proc_get_property(c)->category;
395 | }
396 |
397 | UTF8PROC_DLLEXPORT const char *utf8proc_category_string(utf8proc_int32_t c) {
398 | static const char s[][3] = {"Cn","Lu","Ll","Lt","Lm","Lo","Mn","Mc","Me","Nd","Nl","No","Pc","Pd","Ps","Pe","Pi","Pf","Po","Sm","Sc","Sk","So","Zs","Zl","Zp","Cc","Cf","Cs","Co"};
399 | return s[utf8proc_category(c)];
400 | }
401 |
402 | #define utf8proc_decompose_lump(replacement_uc) \
403 | return utf8proc_decompose_char((replacement_uc), dst, bufsize, \
404 | options & ~UTF8PROC_LUMP, last_boundclass)
405 |
406 | UTF8PROC_DLLEXPORT utf8proc_ssize_t utf8proc_decompose_char(utf8proc_int32_t uc, utf8proc_int32_t *dst, utf8proc_ssize_t bufsize, utf8proc_option_t options, int *last_boundclass) {
407 | const utf8proc_property_t *property;
408 | utf8proc_propval_t category;
409 | utf8proc_int32_t hangul_sindex;
410 | if (uc < 0 || uc >= 0x110000) return UTF8PROC_ERROR_NOTASSIGNED;
411 | property = unsafe_get_property(uc);
412 | category = property->category;
413 | hangul_sindex = uc - UTF8PROC_HANGUL_SBASE;
414 | if (options & (UTF8PROC_COMPOSE|UTF8PROC_DECOMPOSE)) {
415 | if (hangul_sindex >= 0 && hangul_sindex < UTF8PROC_HANGUL_SCOUNT) {
416 | utf8proc_int32_t hangul_tindex;
417 | if (bufsize >= 1) {
418 | dst[0] = UTF8PROC_HANGUL_LBASE +
419 | hangul_sindex / UTF8PROC_HANGUL_NCOUNT;
420 | if (bufsize >= 2) dst[1] = UTF8PROC_HANGUL_VBASE +
421 | (hangul_sindex % UTF8PROC_HANGUL_NCOUNT) / UTF8PROC_HANGUL_TCOUNT;
422 | }
423 | hangul_tindex = hangul_sindex % UTF8PROC_HANGUL_TCOUNT;
424 | if (!hangul_tindex) return 2;
425 | if (bufsize >= 3) dst[2] = UTF8PROC_HANGUL_TBASE + hangul_tindex;
426 | return 3;
427 | }
428 | }
429 | if (options & UTF8PROC_REJECTNA) {
430 | if (!category) return UTF8PROC_ERROR_NOTASSIGNED;
431 | }
432 | if (options & UTF8PROC_IGNORE) {
433 | if (property->ignorable) return 0;
434 | }
435 | if (options & UTF8PROC_STRIPNA) {
436 | if (!category) return 0;
437 | }
438 | if (options & UTF8PROC_LUMP) {
439 | if (category == UTF8PROC_CATEGORY_ZS) utf8proc_decompose_lump(0x0020);
440 | if (uc == 0x2018 || uc == 0x2019 || uc == 0x02BC || uc == 0x02C8)
441 | utf8proc_decompose_lump(0x0027);
442 | if (category == UTF8PROC_CATEGORY_PD || uc == 0x2212)
443 | utf8proc_decompose_lump(0x002D);
444 | if (uc == 0x2044 || uc == 0x2215) utf8proc_decompose_lump(0x002F);
445 | if (uc == 0x2236) utf8proc_decompose_lump(0x003A);
446 | if (uc == 0x2039 || uc == 0x2329 || uc == 0x3008)
447 | utf8proc_decompose_lump(0x003C);
448 | if (uc == 0x203A || uc == 0x232A || uc == 0x3009)
449 | utf8proc_decompose_lump(0x003E);
450 | if (uc == 0x2216) utf8proc_decompose_lump(0x005C);
451 | if (uc == 0x02C4 || uc == 0x02C6 || uc == 0x2038 || uc == 0x2303)
452 | utf8proc_decompose_lump(0x005E);
453 | if (category == UTF8PROC_CATEGORY_PC || uc == 0x02CD)
454 | utf8proc_decompose_lump(0x005F);
455 | if (uc == 0x02CB) utf8proc_decompose_lump(0x0060);
456 | if (uc == 0x2223) utf8proc_decompose_lump(0x007C);
457 | if (uc == 0x223C) utf8proc_decompose_lump(0x007E);
458 | if ((options & UTF8PROC_NLF2LS) && (options & UTF8PROC_NLF2PS)) {
459 | if (category == UTF8PROC_CATEGORY_ZL ||
460 | category == UTF8PROC_CATEGORY_ZP)
461 | utf8proc_decompose_lump(0x000A);
462 | }
463 | }
464 | if (options & UTF8PROC_STRIPMARK) {
465 | if (category == UTF8PROC_CATEGORY_MN ||
466 | category == UTF8PROC_CATEGORY_MC ||
467 | category == UTF8PROC_CATEGORY_ME) return 0;
468 | }
469 | if (options & UTF8PROC_CASEFOLD) {
470 | if (property->casefold_seqindex != UINT16_MAX) {
471 | return seqindex_write_char_decomposed(property->casefold_seqindex, dst, bufsize, options, last_boundclass);
472 | }
473 | }
474 | if (options & (UTF8PROC_COMPOSE|UTF8PROC_DECOMPOSE)) {
475 | if (property->decomp_seqindex != UINT16_MAX &&
476 | (!property->decomp_type || (options & UTF8PROC_COMPAT))) {
477 | return seqindex_write_char_decomposed(property->decomp_seqindex, dst, bufsize, options, last_boundclass);
478 | }
479 | }
480 | if (options & UTF8PROC_CHARBOUND) {
481 | utf8proc_bool boundary;
482 | int tbc = property->boundclass;
483 | boundary = grapheme_break_extended(*last_boundclass, tbc, last_boundclass);
484 | if (boundary) {
485 | if (bufsize >= 1) dst[0] = -1; /* sentinel value for grapheme break */
486 | if (bufsize >= 2) dst[1] = uc;
487 | return 2;
488 | }
489 | }
490 | if (bufsize >= 1) *dst = uc;
491 | return 1;
492 | }
493 |
494 | UTF8PROC_DLLEXPORT utf8proc_ssize_t utf8proc_decompose(
495 | const utf8proc_uint8_t *str, utf8proc_ssize_t strlen,
496 | utf8proc_int32_t *buffer, utf8proc_ssize_t bufsize, utf8proc_option_t options
497 | ) {
498 | return utf8proc_decompose_custom(str, strlen, buffer, bufsize, options, NULL, NULL);
499 | }
500 |
501 | UTF8PROC_DLLEXPORT utf8proc_ssize_t utf8proc_decompose_custom(
502 | const utf8proc_uint8_t *str, utf8proc_ssize_t strlen,
503 | utf8proc_int32_t *buffer, utf8proc_ssize_t bufsize, utf8proc_option_t options,
504 | utf8proc_custom_func custom_func, void *custom_data
505 | ) {
506 | /* strlen will be ignored, if UTF8PROC_NULLTERM is set in options */
507 | utf8proc_ssize_t wpos = 0;
508 | if ((options & UTF8PROC_COMPOSE) && (options & UTF8PROC_DECOMPOSE))
509 | return UTF8PROC_ERROR_INVALIDOPTS;
510 | if ((options & UTF8PROC_STRIPMARK) &&
511 | !(options & UTF8PROC_COMPOSE) && !(options & UTF8PROC_DECOMPOSE))
512 | return UTF8PROC_ERROR_INVALIDOPTS;
513 | {
514 | utf8proc_int32_t uc;
515 | utf8proc_ssize_t rpos = 0;
516 | utf8proc_ssize_t decomp_result;
517 | int boundclass = UTF8PROC_BOUNDCLASS_START;
518 | while (1) {
519 | if (options & UTF8PROC_NULLTERM) {
520 | rpos += utf8proc_iterate(str + rpos, -1, &uc);
521 | /* checking of return value is not necessary,
522 | as 'uc' is < 0 in case of error */
523 | if (uc < 0) return UTF8PROC_ERROR_INVALIDUTF8;
524 | if (rpos < 0) return UTF8PROC_ERROR_OVERFLOW;
525 | if (uc == 0) break;
526 | } else {
527 | if (rpos >= strlen) break;
528 | rpos += utf8proc_iterate(str + rpos, strlen - rpos, &uc);
529 | if (uc < 0) return UTF8PROC_ERROR_INVALIDUTF8;
530 | }
531 | if (custom_func != NULL) {
532 | uc = custom_func(uc, custom_data); /* user-specified custom mapping */
533 | }
534 | decomp_result = utf8proc_decompose_char(
535 | uc, buffer + wpos, (bufsize > wpos) ? (bufsize - wpos) : 0, options,
536 | &boundclass
537 | );
538 | if (decomp_result < 0) return decomp_result;
539 | wpos += decomp_result;
540 | /* prohibiting integer overflows due to too long strings: */
541 | if (wpos < 0 ||
542 | wpos > (utf8proc_ssize_t)(SSIZE_MAX/sizeof(utf8proc_int32_t)/2))
543 | return UTF8PROC_ERROR_OVERFLOW;
544 | }
545 | }
546 | if ((options & (UTF8PROC_COMPOSE|UTF8PROC_DECOMPOSE)) && bufsize >= wpos) {
547 | utf8proc_ssize_t pos = 0;
548 | while (pos < wpos-1) {
549 | utf8proc_int32_t uc1, uc2;
550 | const utf8proc_property_t *property1, *property2;
551 | uc1 = buffer[pos];
552 | uc2 = buffer[pos+1];
553 | property1 = unsafe_get_property(uc1);
554 | property2 = unsafe_get_property(uc2);
555 | if (property1->combining_class > property2->combining_class &&
556 | property2->combining_class > 0) {
557 | buffer[pos] = uc2;
558 | buffer[pos+1] = uc1;
559 | if (pos > 0) pos--; else pos++;
560 | } else {
561 | pos++;
562 | }
563 | }
564 | }
565 | return wpos;
566 | }
567 |
568 | UTF8PROC_DLLEXPORT utf8proc_ssize_t utf8proc_normalize_utf32(utf8proc_int32_t *buffer, utf8proc_ssize_t length, utf8proc_option_t options) {
569 | /* UTF8PROC_NULLTERM option will be ignored, 'length' is never ignored */
570 | if (options & (UTF8PROC_NLF2LS | UTF8PROC_NLF2PS | UTF8PROC_STRIPCC)) {
571 | utf8proc_ssize_t rpos;
572 | utf8proc_ssize_t wpos = 0;
573 | utf8proc_int32_t uc;
574 | for (rpos = 0; rpos < length; rpos++) {
575 | uc = buffer[rpos];
576 | if (uc == 0x000D && rpos < length-1 && buffer[rpos+1] == 0x000A) rpos++;
577 | if (uc == 0x000A || uc == 0x000D || uc == 0x0085 ||
578 | ((options & UTF8PROC_STRIPCC) && (uc == 0x000B || uc == 0x000C))) {
579 | if (options & UTF8PROC_NLF2LS) {
580 | if (options & UTF8PROC_NLF2PS) {
581 | buffer[wpos++] = 0x000A;
582 | } else {
583 | buffer[wpos++] = 0x2028;
584 | }
585 | } else {
586 | if (options & UTF8PROC_NLF2PS) {
587 | buffer[wpos++] = 0x2029;
588 | } else {
589 | buffer[wpos++] = 0x0020;
590 | }
591 | }
592 | } else if ((options & UTF8PROC_STRIPCC) &&
593 | (uc < 0x0020 || (uc >= 0x007F && uc < 0x00A0))) {
594 | if (uc == 0x0009) buffer[wpos++] = 0x0020;
595 | } else {
596 | buffer[wpos++] = uc;
597 | }
598 | }
599 | length = wpos;
600 | }
601 | if (options & UTF8PROC_COMPOSE) {
602 | utf8proc_int32_t *starter = NULL;
603 | utf8proc_int32_t current_char;
604 | const utf8proc_property_t *starter_property = NULL, *current_property;
605 | utf8proc_propval_t max_combining_class = -1;
606 | utf8proc_ssize_t rpos;
607 | utf8proc_ssize_t wpos = 0;
608 | utf8proc_int32_t composition;
609 | for (rpos = 0; rpos < length; rpos++) {
610 | current_char = buffer[rpos];
611 | current_property = unsafe_get_property(current_char);
612 | if (starter && current_property->combining_class > max_combining_class) {
613 | /* combination perhaps possible */
614 | utf8proc_int32_t hangul_lindex;
615 | utf8proc_int32_t hangul_sindex;
616 | hangul_lindex = *starter - UTF8PROC_HANGUL_LBASE;
617 | if (hangul_lindex >= 0 && hangul_lindex < UTF8PROC_HANGUL_LCOUNT) {
618 | utf8proc_int32_t hangul_vindex;
619 | hangul_vindex = current_char - UTF8PROC_HANGUL_VBASE;
620 | if (hangul_vindex >= 0 && hangul_vindex < UTF8PROC_HANGUL_VCOUNT) {
621 | *starter = UTF8PROC_HANGUL_SBASE +
622 | (hangul_lindex * UTF8PROC_HANGUL_VCOUNT + hangul_vindex) *
623 | UTF8PROC_HANGUL_TCOUNT;
624 | starter_property = NULL;
625 | continue;
626 | }
627 | }
628 | hangul_sindex = *starter - UTF8PROC_HANGUL_SBASE;
629 | if (hangul_sindex >= 0 && hangul_sindex < UTF8PROC_HANGUL_SCOUNT &&
630 | (hangul_sindex % UTF8PROC_HANGUL_TCOUNT) == 0) {
631 | utf8proc_int32_t hangul_tindex;
632 | hangul_tindex = current_char - UTF8PROC_HANGUL_TBASE;
633 | if (hangul_tindex >= 0 && hangul_tindex < UTF8PROC_HANGUL_TCOUNT) {
634 | *starter += hangul_tindex;
635 | starter_property = NULL;
636 | continue;
637 | }
638 | }
639 | if (!starter_property) {
640 | starter_property = unsafe_get_property(*starter);
641 | }
642 | if (starter_property->comb_index < 0x8000 &&
643 | current_property->comb_index != UINT16_MAX &&
644 | current_property->comb_index >= 0x8000) {
645 | int sidx = starter_property->comb_index;
646 | int idx = current_property->comb_index & 0x3FFF;
647 | if (idx >= utf8proc_combinations[sidx] && idx <= utf8proc_combinations[sidx + 1] ) {
648 | idx += sidx + 2 - utf8proc_combinations[sidx];
649 | if (current_property->comb_index & 0x4000) {
650 | composition = (utf8proc_combinations[idx] << 16) | utf8proc_combinations[idx+1];
651 | } else
652 | composition = utf8proc_combinations[idx];
653 |
654 | if (composition > 0 && (!(options & UTF8PROC_STABLE) ||
655 | !(unsafe_get_property(composition)->comp_exclusion))) {
656 | *starter = composition;
657 | starter_property = NULL;
658 | continue;
659 | }
660 | }
661 | }
662 | }
663 | buffer[wpos] = current_char;
664 | if (current_property->combining_class) {
665 | if (current_property->combining_class > max_combining_class) {
666 | max_combining_class = current_property->combining_class;
667 | }
668 | } else {
669 | starter = buffer + wpos;
670 | starter_property = NULL;
671 | max_combining_class = -1;
672 | }
673 | wpos++;
674 | }
675 | length = wpos;
676 | }
677 | return length;
678 | }
679 |
680 | UTF8PROC_DLLEXPORT utf8proc_ssize_t utf8proc_reencode(utf8proc_int32_t *buffer, utf8proc_ssize_t length, utf8proc_option_t options) {
681 | /* UTF8PROC_NULLTERM option will be ignored, 'length' is never ignored
682 | ASSERT: 'buffer' has one spare byte of free space at the end! */
683 | length = utf8proc_normalize_utf32(buffer, length, options);
684 | if (length < 0) return length;
685 | {
686 | utf8proc_ssize_t rpos, wpos = 0;
687 | utf8proc_int32_t uc;
688 | if (options & UTF8PROC_CHARBOUND) {
689 | for (rpos = 0; rpos < length; rpos++) {
690 | uc = buffer[rpos];
691 | wpos += charbound_encode_char(uc, ((utf8proc_uint8_t *)buffer) + wpos);
692 | }
693 | } else {
694 | for (rpos = 0; rpos < length; rpos++) {
695 | uc = buffer[rpos];
696 | wpos += utf8proc_encode_char(uc, ((utf8proc_uint8_t *)buffer) + wpos);
697 | }
698 | }
699 | ((utf8proc_uint8_t *)buffer)[wpos] = 0;
700 | return wpos;
701 | }
702 | }
703 |
704 | UTF8PROC_DLLEXPORT utf8proc_ssize_t utf8proc_map(
705 | const utf8proc_uint8_t *str, utf8proc_ssize_t strlen, utf8proc_uint8_t **dstptr, utf8proc_option_t options
706 | ) {
707 | return utf8proc_map_custom(str, strlen, dstptr, options, NULL, NULL);
708 | }
709 |
710 | UTF8PROC_DLLEXPORT utf8proc_ssize_t utf8proc_map_custom(
711 | const utf8proc_uint8_t *str, utf8proc_ssize_t strlen, utf8proc_uint8_t **dstptr, utf8proc_option_t options,
712 | utf8proc_custom_func custom_func, void *custom_data
713 | ) {
714 | utf8proc_int32_t *buffer;
715 | utf8proc_ssize_t result;
716 | *dstptr = NULL;
717 | result = utf8proc_decompose_custom(str, strlen, NULL, 0, options, custom_func, custom_data);
718 | if (result < 0) return result;
719 | buffer = (utf8proc_int32_t *) malloc(result * sizeof(utf8proc_int32_t) + 1);
720 | if (!buffer) return UTF8PROC_ERROR_NOMEM;
721 | result = utf8proc_decompose_custom(str, strlen, buffer, result, options, custom_func, custom_data);
722 | if (result < 0) {
723 | free(buffer);
724 | return result;
725 | }
726 | result = utf8proc_reencode(buffer, result, options);
727 | if (result < 0) {
728 | free(buffer);
729 | return result;
730 | }
731 | {
732 | utf8proc_int32_t *newptr;
733 | newptr = (utf8proc_int32_t *) realloc(buffer, (size_t)result+1);
734 | if (newptr) buffer = newptr;
735 | }
736 | *dstptr = (utf8proc_uint8_t *)buffer;
737 | return result;
738 | }
739 |
740 | UTF8PROC_DLLEXPORT utf8proc_uint8_t *utf8proc_NFD(const utf8proc_uint8_t *str) {
741 | utf8proc_uint8_t *retval;
742 | utf8proc_map(str, 0, &retval, UTF8PROC_NULLTERM | UTF8PROC_STABLE |
743 | UTF8PROC_DECOMPOSE);
744 | return retval;
745 | }
746 |
747 | UTF8PROC_DLLEXPORT utf8proc_uint8_t *utf8proc_NFC(const utf8proc_uint8_t *str) {
748 | utf8proc_uint8_t *retval;
749 | utf8proc_map(str, 0, &retval, UTF8PROC_NULLTERM | UTF8PROC_STABLE |
750 | UTF8PROC_COMPOSE);
751 | return retval;
752 | }
753 |
754 | UTF8PROC_DLLEXPORT utf8proc_uint8_t *utf8proc_NFKD(const utf8proc_uint8_t *str) {
755 | utf8proc_uint8_t *retval;
756 | utf8proc_map(str, 0, &retval, UTF8PROC_NULLTERM | UTF8PROC_STABLE |
757 | UTF8PROC_DECOMPOSE | UTF8PROC_COMPAT);
758 | return retval;
759 | }
760 |
761 | UTF8PROC_DLLEXPORT utf8proc_uint8_t *utf8proc_NFKC(const utf8proc_uint8_t *str) {
762 | utf8proc_uint8_t *retval;
763 | utf8proc_map(str, 0, &retval, UTF8PROC_NULLTERM | UTF8PROC_STABLE |
764 | UTF8PROC_COMPOSE | UTF8PROC_COMPAT);
765 | return retval;
766 | }
767 |
768 | UTF8PROC_DLLEXPORT utf8proc_uint8_t *utf8proc_NFKC_Casefold(const utf8proc_uint8_t *str) {
769 | utf8proc_uint8_t *retval;
770 | utf8proc_map(str, 0, &retval, UTF8PROC_NULLTERM | UTF8PROC_STABLE |
771 | UTF8PROC_COMPOSE | UTF8PROC_COMPAT | UTF8PROC_CASEFOLD | UTF8PROC_IGNORE);
772 | return retval;
773 | }
774 |
--------------------------------------------------------------------------------
/utfproc/utf8proc.h:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2014-2019 Steven G. Johnson, Jiahao Chen, Peter Colberg, Tony Kelman, Scott P. Jones, and other contributors.
3 | * Copyright (c) 2009 Public Software Group e. V., Berlin, Germany
4 | *
5 | * Permission is hereby granted, free of charge, to any person obtaining a
6 | * copy of this software and associated documentation files (the "Software"),
7 | * to deal in the Software without restriction, including without limitation
8 | * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9 | * and/or sell copies of the Software, and to permit persons to whom the
10 | * Software is furnished to do so, subject to the following conditions:
11 | *
12 | * The above copyright notice and this permission notice shall be included in
13 | * all copies or substantial portions of the Software.
14 | *
15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21 | * DEALINGS IN THE SOFTWARE.
22 | */
23 |
24 |
25 | /**
26 | * @mainpage
27 | *
28 | * utf8proc is a free/open-source (MIT/expat licensed) C library
29 | * providing Unicode normalization, case-folding, and other operations
30 | * for strings in the UTF-8 encoding, supporting up-to-date Unicode versions.
31 | * See the utf8proc home page (http://julialang.org/utf8proc/)
32 | * for downloads and other information, or the source code on github
33 | * (https://github.com/JuliaLang/utf8proc).
34 | *
35 | * For the utf8proc API documentation, see: @ref utf8proc.h
36 | *
37 | * The features of utf8proc include:
38 | *
39 | * - Transformation of strings (@ref utf8proc_map) to:
40 | * - decompose (@ref UTF8PROC_DECOMPOSE) or compose (@ref UTF8PROC_COMPOSE) Unicode combining characters (http://en.wikipedia.org/wiki/Combining_character)
41 | * - canonicalize Unicode compatibility characters (@ref UTF8PROC_COMPAT)
42 | * - strip "ignorable" (@ref UTF8PROC_IGNORE) characters, control characters (@ref UTF8PROC_STRIPCC), or combining characters such as accents (@ref UTF8PROC_STRIPMARK)
43 | * - case-folding (@ref UTF8PROC_CASEFOLD)
44 | * - Unicode normalization: @ref utf8proc_NFD, @ref utf8proc_NFC, @ref utf8proc_NFKD, @ref utf8proc_NFKC
45 | * - Detecting grapheme boundaries (@ref utf8proc_grapheme_break and @ref UTF8PROC_CHARBOUND)
46 | * - Character-width computation: @ref utf8proc_charwidth
47 | * - Classification of characters by Unicode category: @ref utf8proc_category and @ref utf8proc_category_string
48 | * - Encode (@ref utf8proc_encode_char) and decode (@ref utf8proc_iterate) Unicode codepoints to/from UTF-8.
49 | */
50 |
51 | /** @file */
52 |
53 | #ifndef UTF8PROC_H
54 | #define UTF8PROC_H
55 |
56 | /** @name API version
57 | *
58 | * The utf8proc API version MAJOR.MINOR.PATCH, following
59 | * semantic-versioning rules (http://semver.org) based on API
60 | * compatibility.
61 | *
62 | * This is also returned at runtime by @ref utf8proc_version; however, the
63 | * runtime version may append a string like "-dev" to the version number
64 | * for prerelease versions.
65 | *
66 | * @note The shared-library version number in the Makefile
67 | * (and CMakeLists.txt, and MANIFEST) may be different,
68 | * being based on ABI compatibility rather than API compatibility.
69 | */
70 | /** @{ */
71 | /** The MAJOR version number (increased when backwards API compatibility is broken). */
72 | #define UTF8PROC_VERSION_MAJOR 2
73 | /** The MINOR version number (increased when new functionality is added in a backwards-compatible manner). */
74 | #define UTF8PROC_VERSION_MINOR 4
75 | /** The PATCH version (increased for fixes that do not change the API). */
76 | #define UTF8PROC_VERSION_PATCH 0
77 | /** @} */
78 |
79 | #include
80 |
81 | #if defined(_MSC_VER) && _MSC_VER < 1800
82 | // MSVC prior to 2013 lacked stdbool.h and inttypes.h
83 | typedef signed char utf8proc_int8_t;
84 | typedef unsigned char utf8proc_uint8_t;
85 | typedef short utf8proc_int16_t;
86 | typedef unsigned short utf8proc_uint16_t;
87 | typedef int utf8proc_int32_t;
88 | typedef unsigned int utf8proc_uint32_t;
89 | # ifdef _WIN64
90 | typedef __int64 utf8proc_ssize_t;
91 | typedef unsigned __int64 utf8proc_size_t;
92 | # else
93 | typedef int utf8proc_ssize_t;
94 | typedef unsigned int utf8proc_size_t;
95 | # endif
96 | # ifndef __cplusplus
97 | // emulate C99 bool
98 | typedef unsigned char utf8proc_bool;
99 | # ifndef __bool_true_false_are_defined
100 | # define false 0
101 | # define true 1
102 | # define __bool_true_false_are_defined 1
103 | # endif
104 | # else
105 | typedef bool utf8proc_bool;
106 | # endif
107 | #else
108 | # include
109 | # include
110 | # include
111 | typedef int8_t utf8proc_int8_t;
112 | typedef uint8_t utf8proc_uint8_t;
113 | typedef int16_t utf8proc_int16_t;
114 | typedef uint16_t utf8proc_uint16_t;
115 | typedef int32_t utf8proc_int32_t;
116 | typedef uint32_t utf8proc_uint32_t;
117 | typedef size_t utf8proc_size_t;
118 | typedef ptrdiff_t utf8proc_ssize_t;
119 | typedef bool utf8proc_bool;
120 | #endif
121 | #include
122 |
123 | #ifdef UTF8PROC_STATIC
124 | # define UTF8PROC_DLLEXPORT
125 | #else
126 | # ifdef _WIN32
127 | # ifdef UTF8PROC_EXPORTS
128 | # define UTF8PROC_DLLEXPORT __declspec(dllexport)
129 | # else
130 | # define UTF8PROC_DLLEXPORT __declspec(dllimport)
131 | # endif
132 | # elif __GNUC__ >= 4
133 | # define UTF8PROC_DLLEXPORT __attribute__ ((visibility("default")))
134 | # else
135 | # define UTF8PROC_DLLEXPORT
136 | # endif
137 | #endif
138 |
139 | #ifdef __cplusplus
140 | extern "C" {
141 | #endif
142 |
143 | /**
144 | * Option flags used by several functions in the library.
145 | */
146 | typedef enum {
147 | /** The given UTF-8 input is NULL terminated. */
148 | UTF8PROC_NULLTERM = (1<<0),
149 | /** Unicode Versioning Stability has to be respected. */
150 | UTF8PROC_STABLE = (1<<1),
151 | /** Compatibility decomposition (i.e. formatting information is lost). */
152 | UTF8PROC_COMPAT = (1<<2),
153 | /** Return a result with decomposed characters. */
154 | UTF8PROC_COMPOSE = (1<<3),
155 | /** Return a result with decomposed characters. */
156 | UTF8PROC_DECOMPOSE = (1<<4),
157 | /** Strip "default ignorable characters" such as SOFT-HYPHEN or ZERO-WIDTH-SPACE. */
158 | UTF8PROC_IGNORE = (1<<5),
159 | /** Return an error, if the input contains unassigned codepoints. */
160 | UTF8PROC_REJECTNA = (1<<6),
161 | /**
162 | * Indicating that NLF-sequences (LF, CRLF, CR, NEL) are representing a
163 | * line break, and should be converted to the codepoint for line
164 | * separation (LS).
165 | */
166 | UTF8PROC_NLF2LS = (1<<7),
167 | /**
168 | * Indicating that NLF-sequences are representing a paragraph break, and
169 | * should be converted to the codepoint for paragraph separation
170 | * (PS).
171 | */
172 | UTF8PROC_NLF2PS = (1<<8),
173 | /** Indicating that the meaning of NLF-sequences is unknown. */
174 | UTF8PROC_NLF2LF = (UTF8PROC_NLF2LS | UTF8PROC_NLF2PS),
175 | /** Strips and/or convers control characters.
176 | *
177 | * NLF-sequences are transformed into space, except if one of the
178 | * NLF2LS/PS/LF options is given. HorizontalTab (HT) and FormFeed (FF)
179 | * are treated as a NLF-sequence in this case. All other control
180 | * characters are simply removed.
181 | */
182 | UTF8PROC_STRIPCC = (1<<9),
183 | /**
184 | * Performs unicode case folding, to be able to do a case-insensitive
185 | * string comparison.
186 | */
187 | UTF8PROC_CASEFOLD = (1<<10),
188 | /**
189 | * Inserts 0xFF bytes at the beginning of each sequence which is
190 | * representing a single grapheme cluster (see UAX#29).
191 | */
192 | UTF8PROC_CHARBOUND = (1<<11),
193 | /** Lumps certain characters together.
194 | *
195 | * E.g. HYPHEN U+2010 and MINUS U+2212 to ASCII "-". See lump.md for details.
196 | *
197 | * If NLF2LF is set, this includes a transformation of paragraph and
198 | * line separators to ASCII line-feed (LF).
199 | */
200 | UTF8PROC_LUMP = (1<<12),
201 | /** Strips all character markings.
202 | *
203 | * This includes non-spacing, spacing and enclosing (i.e. accents).
204 | * @note This option works only with @ref UTF8PROC_COMPOSE or
205 | * @ref UTF8PROC_DECOMPOSE
206 | */
207 | UTF8PROC_STRIPMARK = (1<<13),
208 | /**
209 | * Strip unassigned codepoints.
210 | */
211 | UTF8PROC_STRIPNA = (1<<14),
212 | } utf8proc_option_t;
213 |
214 | /** @name Error codes
215 | * Error codes being returned by almost all functions.
216 | */
217 | /** @{ */
218 | /** Memory could not be allocated. */
219 | #define UTF8PROC_ERROR_NOMEM -1
220 | /** The given string is too long to be processed. */
221 | #define UTF8PROC_ERROR_OVERFLOW -2
222 | /** The given string is not a legal UTF-8 string. */
223 | #define UTF8PROC_ERROR_INVALIDUTF8 -3
224 | /** The @ref UTF8PROC_REJECTNA flag was set and an unassigned codepoint was found. */
225 | #define UTF8PROC_ERROR_NOTASSIGNED -4
226 | /** Invalid options have been used. */
227 | #define UTF8PROC_ERROR_INVALIDOPTS -5
228 | /** @} */
229 |
230 | /* @name Types */
231 |
232 | /** Holds the value of a property. */
233 | typedef utf8proc_int16_t utf8proc_propval_t;
234 |
235 | /** Struct containing information about a codepoint. */
236 | typedef struct utf8proc_property_struct {
237 | /**
238 | * Unicode category.
239 | * @see utf8proc_category_t.
240 | */
241 | utf8proc_propval_t category;
242 | utf8proc_propval_t combining_class;
243 | /**
244 | * Bidirectional class.
245 | * @see utf8proc_bidi_class_t.
246 | */
247 | utf8proc_propval_t bidi_class;
248 | /**
249 | * @anchor Decomposition type.
250 | * @see utf8proc_decomp_type_t.
251 | */
252 | utf8proc_propval_t decomp_type;
253 | utf8proc_uint16_t decomp_seqindex;
254 | utf8proc_uint16_t casefold_seqindex;
255 | utf8proc_uint16_t uppercase_seqindex;
256 | utf8proc_uint16_t lowercase_seqindex;
257 | utf8proc_uint16_t titlecase_seqindex;
258 | utf8proc_uint16_t comb_index;
259 | unsigned bidi_mirrored:1;
260 | unsigned comp_exclusion:1;
261 | /**
262 | * Can this codepoint be ignored?
263 | *
264 | * Used by @ref utf8proc_decompose_char when @ref UTF8PROC_IGNORE is
265 | * passed as an option.
266 | */
267 | unsigned ignorable:1;
268 | unsigned control_boundary:1;
269 | /** The width of the codepoint. */
270 | unsigned charwidth:2;
271 | unsigned pad:2;
272 | /**
273 | * Boundclass.
274 | * @see utf8proc_boundclass_t.
275 | */
276 | unsigned boundclass:8;
277 | } utf8proc_property_t;
278 |
279 | /** Unicode categories. */
280 | typedef enum {
281 | UTF8PROC_CATEGORY_CN = 0, /**< Other, not assigned */
282 | UTF8PROC_CATEGORY_LU = 1, /**< Letter, uppercase */
283 | UTF8PROC_CATEGORY_LL = 2, /**< Letter, lowercase */
284 | UTF8PROC_CATEGORY_LT = 3, /**< Letter, titlecase */
285 | UTF8PROC_CATEGORY_LM = 4, /**< Letter, modifier */
286 | UTF8PROC_CATEGORY_LO = 5, /**< Letter, other */
287 | UTF8PROC_CATEGORY_MN = 6, /**< Mark, nonspacing */
288 | UTF8PROC_CATEGORY_MC = 7, /**< Mark, spacing combining */
289 | UTF8PROC_CATEGORY_ME = 8, /**< Mark, enclosing */
290 | UTF8PROC_CATEGORY_ND = 9, /**< Number, decimal digit */
291 | UTF8PROC_CATEGORY_NL = 10, /**< Number, letter */
292 | UTF8PROC_CATEGORY_NO = 11, /**< Number, other */
293 | UTF8PROC_CATEGORY_PC = 12, /**< Punctuation, connector */
294 | UTF8PROC_CATEGORY_PD = 13, /**< Punctuation, dash */
295 | UTF8PROC_CATEGORY_PS = 14, /**< Punctuation, open */
296 | UTF8PROC_CATEGORY_PE = 15, /**< Punctuation, close */
297 | UTF8PROC_CATEGORY_PI = 16, /**< Punctuation, initial quote */
298 | UTF8PROC_CATEGORY_PF = 17, /**< Punctuation, final quote */
299 | UTF8PROC_CATEGORY_PO = 18, /**< Punctuation, other */
300 | UTF8PROC_CATEGORY_SM = 19, /**< Symbol, math */
301 | UTF8PROC_CATEGORY_SC = 20, /**< Symbol, currency */
302 | UTF8PROC_CATEGORY_SK = 21, /**< Symbol, modifier */
303 | UTF8PROC_CATEGORY_SO = 22, /**< Symbol, other */
304 | UTF8PROC_CATEGORY_ZS = 23, /**< Separator, space */
305 | UTF8PROC_CATEGORY_ZL = 24, /**< Separator, line */
306 | UTF8PROC_CATEGORY_ZP = 25, /**< Separator, paragraph */
307 | UTF8PROC_CATEGORY_CC = 26, /**< Other, control */
308 | UTF8PROC_CATEGORY_CF = 27, /**< Other, format */
309 | UTF8PROC_CATEGORY_CS = 28, /**< Other, surrogate */
310 | UTF8PROC_CATEGORY_CO = 29, /**< Other, private use */
311 | } utf8proc_category_t;
312 |
313 | /** Bidirectional character classes. */
314 | typedef enum {
315 | UTF8PROC_BIDI_CLASS_L = 1, /**< Left-to-Right */
316 | UTF8PROC_BIDI_CLASS_LRE = 2, /**< Left-to-Right Embedding */
317 | UTF8PROC_BIDI_CLASS_LRO = 3, /**< Left-to-Right Override */
318 | UTF8PROC_BIDI_CLASS_R = 4, /**< Right-to-Left */
319 | UTF8PROC_BIDI_CLASS_AL = 5, /**< Right-to-Left Arabic */
320 | UTF8PROC_BIDI_CLASS_RLE = 6, /**< Right-to-Left Embedding */
321 | UTF8PROC_BIDI_CLASS_RLO = 7, /**< Right-to-Left Override */
322 | UTF8PROC_BIDI_CLASS_PDF = 8, /**< Pop Directional Format */
323 | UTF8PROC_BIDI_CLASS_EN = 9, /**< European Number */
324 | UTF8PROC_BIDI_CLASS_ES = 10, /**< European Separator */
325 | UTF8PROC_BIDI_CLASS_ET = 11, /**< European Number Terminator */
326 | UTF8PROC_BIDI_CLASS_AN = 12, /**< Arabic Number */
327 | UTF8PROC_BIDI_CLASS_CS = 13, /**< Common Number Separator */
328 | UTF8PROC_BIDI_CLASS_NSM = 14, /**< Nonspacing Mark */
329 | UTF8PROC_BIDI_CLASS_BN = 15, /**< Boundary Neutral */
330 | UTF8PROC_BIDI_CLASS_B = 16, /**< Paragraph Separator */
331 | UTF8PROC_BIDI_CLASS_S = 17, /**< Segment Separator */
332 | UTF8PROC_BIDI_CLASS_WS = 18, /**< Whitespace */
333 | UTF8PROC_BIDI_CLASS_ON = 19, /**< Other Neutrals */
334 | UTF8PROC_BIDI_CLASS_LRI = 20, /**< Left-to-Right Isolate */
335 | UTF8PROC_BIDI_CLASS_RLI = 21, /**< Right-to-Left Isolate */
336 | UTF8PROC_BIDI_CLASS_FSI = 22, /**< First Strong Isolate */
337 | UTF8PROC_BIDI_CLASS_PDI = 23, /**< Pop Directional Isolate */
338 | } utf8proc_bidi_class_t;
339 |
340 | /** Decomposition type. */
341 | typedef enum {
342 | UTF8PROC_DECOMP_TYPE_FONT = 1, /**< Font */
343 | UTF8PROC_DECOMP_TYPE_NOBREAK = 2, /**< Nobreak */
344 | UTF8PROC_DECOMP_TYPE_INITIAL = 3, /**< Initial */
345 | UTF8PROC_DECOMP_TYPE_MEDIAL = 4, /**< Medial */
346 | UTF8PROC_DECOMP_TYPE_FINAL = 5, /**< Final */
347 | UTF8PROC_DECOMP_TYPE_ISOLATED = 6, /**< Isolated */
348 | UTF8PROC_DECOMP_TYPE_CIRCLE = 7, /**< Circle */
349 | UTF8PROC_DECOMP_TYPE_SUPER = 8, /**< Super */
350 | UTF8PROC_DECOMP_TYPE_SUB = 9, /**< Sub */
351 | UTF8PROC_DECOMP_TYPE_VERTICAL = 10, /**< Vertical */
352 | UTF8PROC_DECOMP_TYPE_WIDE = 11, /**< Wide */
353 | UTF8PROC_DECOMP_TYPE_NARROW = 12, /**< Narrow */
354 | UTF8PROC_DECOMP_TYPE_SMALL = 13, /**< Small */
355 | UTF8PROC_DECOMP_TYPE_SQUARE = 14, /**< Square */
356 | UTF8PROC_DECOMP_TYPE_FRACTION = 15, /**< Fraction */
357 | UTF8PROC_DECOMP_TYPE_COMPAT = 16, /**< Compat */
358 | } utf8proc_decomp_type_t;
359 |
360 | /** Boundclass property. (TR29) */
361 | typedef enum {
362 | UTF8PROC_BOUNDCLASS_START = 0, /**< Start */
363 | UTF8PROC_BOUNDCLASS_OTHER = 1, /**< Other */
364 | UTF8PROC_BOUNDCLASS_CR = 2, /**< Cr */
365 | UTF8PROC_BOUNDCLASS_LF = 3, /**< Lf */
366 | UTF8PROC_BOUNDCLASS_CONTROL = 4, /**< Control */
367 | UTF8PROC_BOUNDCLASS_EXTEND = 5, /**< Extend */
368 | UTF8PROC_BOUNDCLASS_L = 6, /**< L */
369 | UTF8PROC_BOUNDCLASS_V = 7, /**< V */
370 | UTF8PROC_BOUNDCLASS_T = 8, /**< T */
371 | UTF8PROC_BOUNDCLASS_LV = 9, /**< Lv */
372 | UTF8PROC_BOUNDCLASS_LVT = 10, /**< Lvt */
373 | UTF8PROC_BOUNDCLASS_REGIONAL_INDICATOR = 11, /**< Regional indicator */
374 | UTF8PROC_BOUNDCLASS_SPACINGMARK = 12, /**< Spacingmark */
375 | UTF8PROC_BOUNDCLASS_PREPEND = 13, /**< Prepend */
376 | UTF8PROC_BOUNDCLASS_ZWJ = 14, /**< Zero Width Joiner */
377 |
378 | /* the following are no longer used in Unicode 11, but we keep
379 | the constants here for backward compatibility */
380 | UTF8PROC_BOUNDCLASS_E_BASE = 15, /**< Emoji Base */
381 | UTF8PROC_BOUNDCLASS_E_MODIFIER = 16, /**< Emoji Modifier */
382 | UTF8PROC_BOUNDCLASS_GLUE_AFTER_ZWJ = 17, /**< Glue_After_ZWJ */
383 | UTF8PROC_BOUNDCLASS_E_BASE_GAZ = 18, /**< E_BASE + GLUE_AFTER_ZJW */
384 |
385 | /* the Extended_Pictographic property is used in the Unicode 11
386 | grapheme-boundary rules, so we store it in the boundclass field */
387 | UTF8PROC_BOUNDCLASS_EXTENDED_PICTOGRAPHIC = 19,
388 | UTF8PROC_BOUNDCLASS_E_ZWG = 20, /* UTF8PROC_BOUNDCLASS_EXTENDED_PICTOGRAPHIC + ZWJ */
389 | } utf8proc_boundclass_t;
390 |
391 | /**
392 | * Function pointer type passed to @ref utf8proc_map_custom and
393 | * @ref utf8proc_decompose_custom, which is used to specify a user-defined
394 | * mapping of codepoints to be applied in conjunction with other mappings.
395 | */
396 | typedef utf8proc_int32_t (*utf8proc_custom_func)(utf8proc_int32_t codepoint, void *data);
397 |
398 | /**
399 | * Array containing the byte lengths of a UTF-8 encoded codepoint based
400 | * on the first byte.
401 | */
402 | UTF8PROC_DLLEXPORT extern const utf8proc_int8_t utf8proc_utf8class[256];
403 |
404 | /**
405 | * Returns the utf8proc API version as a string MAJOR.MINOR.PATCH
406 | * (http://semver.org format), possibly with a "-dev" suffix for
407 | * development versions.
408 | */
409 | UTF8PROC_DLLEXPORT const char *utf8proc_version(void);
410 |
411 | /**
412 | * Returns the utf8proc supported Unicode version as a string MAJOR.MINOR.PATCH.
413 | */
414 | UTF8PROC_DLLEXPORT const char *utf8proc_unicode_version(void);
415 |
416 | /**
417 | * Returns an informative error string for the given utf8proc error code
418 | * (e.g. the error codes returned by @ref utf8proc_map).
419 | */
420 | UTF8PROC_DLLEXPORT const char *utf8proc_errmsg(utf8proc_ssize_t errcode);
421 |
422 | /**
423 | * Reads a single codepoint from the UTF-8 sequence being pointed to by `str`.
424 | * The maximum number of bytes read is `strlen`, unless `strlen` is
425 | * negative (in which case up to 4 bytes are read).
426 | *
427 | * If a valid codepoint could be read, it is stored in the variable
428 | * pointed to by `codepoint_ref`, otherwise that variable will be set to -1.
429 | * In case of success, the number of bytes read is returned; otherwise, a
430 | * negative error code is returned.
431 | */
432 | UTF8PROC_DLLEXPORT utf8proc_ssize_t utf8proc_iterate(const utf8proc_uint8_t *str, utf8proc_ssize_t strlen, utf8proc_int32_t *codepoint_ref);
433 |
434 | /**
435 | * Check if a codepoint is valid (regardless of whether it has been
436 | * assigned a value by the current Unicode standard).
437 | *
438 | * @return 1 if the given `codepoint` is valid and otherwise return 0.
439 | */
440 | UTF8PROC_DLLEXPORT utf8proc_bool utf8proc_codepoint_valid(utf8proc_int32_t codepoint);
441 |
442 | /**
443 | * Encodes the codepoint as an UTF-8 string in the byte array pointed
444 | * to by `dst`. This array must be at least 4 bytes long.
445 | *
446 | * In case of success the number of bytes written is returned, and
447 | * otherwise 0 is returned.
448 | *
449 | * This function does not check whether `codepoint` is valid Unicode.
450 | */
451 | UTF8PROC_DLLEXPORT utf8proc_ssize_t utf8proc_encode_char(utf8proc_int32_t codepoint, utf8proc_uint8_t *dst);
452 |
453 | /**
454 | * Look up the properties for a given codepoint.
455 | *
456 | * @param codepoint The Unicode codepoint.
457 | *
458 | * @returns
459 | * A pointer to a (constant) struct containing information about
460 | * the codepoint.
461 | * @par
462 | * If the codepoint is unassigned or invalid, a pointer to a special struct is
463 | * returned in which `category` is 0 (@ref UTF8PROC_CATEGORY_CN).
464 | */
465 | UTF8PROC_DLLEXPORT const utf8proc_property_t *utf8proc_get_property(utf8proc_int32_t codepoint);
466 |
467 | /** Decompose a codepoint into an array of codepoints.
468 | *
469 | * @param codepoint the codepoint.
470 | * @param dst the destination buffer.
471 | * @param bufsize the size of the destination buffer.
472 | * @param options one or more of the following flags:
473 | * - @ref UTF8PROC_REJECTNA - return an error `codepoint` is unassigned
474 | * - @ref UTF8PROC_IGNORE - strip "default ignorable" codepoints
475 | * - @ref UTF8PROC_CASEFOLD - apply Unicode casefolding
476 | * - @ref UTF8PROC_COMPAT - replace certain codepoints with their
477 | * compatibility decomposition
478 | * - @ref UTF8PROC_CHARBOUND - insert 0xFF bytes before each grapheme cluster
479 | * - @ref UTF8PROC_LUMP - lump certain different codepoints together
480 | * - @ref UTF8PROC_STRIPMARK - remove all character marks
481 | * - @ref UTF8PROC_STRIPNA - remove unassigned codepoints
482 | * @param last_boundclass
483 | * Pointer to an integer variable containing
484 | * the previous codepoint's boundary class if the @ref UTF8PROC_CHARBOUND
485 | * option is used. Otherwise, this parameter is ignored.
486 | *
487 | * @return
488 | * In case of success, the number of codepoints written is returned; in case
489 | * of an error, a negative error code is returned (@ref utf8proc_errmsg).
490 | * @par
491 | * If the number of written codepoints would be bigger than `bufsize`, the
492 | * required buffer size is returned, while the buffer will be overwritten with
493 | * undefined data.
494 | */
495 | UTF8PROC_DLLEXPORT utf8proc_ssize_t utf8proc_decompose_char(
496 | utf8proc_int32_t codepoint, utf8proc_int32_t *dst, utf8proc_ssize_t bufsize,
497 | utf8proc_option_t options, int *last_boundclass
498 | );
499 |
500 | /**
501 | * The same as @ref utf8proc_decompose_char, but acts on a whole UTF-8
502 | * string and orders the decomposed sequences correctly.
503 | *
504 | * If the @ref UTF8PROC_NULLTERM flag in `options` is set, processing
505 | * will be stopped, when a NULL byte is encounted, otherwise `strlen`
506 | * bytes are processed. The result (in the form of 32-bit unicode
507 | * codepoints) is written into the buffer being pointed to by
508 | * `buffer` (which must contain at least `bufsize` entries). In case of
509 | * success, the number of codepoints written is returned; in case of an
510 | * error, a negative error code is returned (@ref utf8proc_errmsg).
511 | * See @ref utf8proc_decompose_custom to supply additional transformations.
512 | *
513 | * If the number of written codepoints would be bigger than `bufsize`, the
514 | * required buffer size is returned, while the buffer will be overwritten with
515 | * undefined data.
516 | */
517 | UTF8PROC_DLLEXPORT utf8proc_ssize_t utf8proc_decompose(
518 | const utf8proc_uint8_t *str, utf8proc_ssize_t strlen,
519 | utf8proc_int32_t *buffer, utf8proc_ssize_t bufsize, utf8proc_option_t options
520 | );
521 |
522 | /**
523 | * The same as @ref utf8proc_decompose, but also takes a `custom_func` mapping function
524 | * that is called on each codepoint in `str` before any other transformations
525 | * (along with a `custom_data` pointer that is passed through to `custom_func`).
526 | * The `custom_func` argument is ignored if it is `NULL`. See also @ref utf8proc_map_custom.
527 | */
528 | UTF8PROC_DLLEXPORT utf8proc_ssize_t utf8proc_decompose_custom(
529 | const utf8proc_uint8_t *str, utf8proc_ssize_t strlen,
530 | utf8proc_int32_t *buffer, utf8proc_ssize_t bufsize, utf8proc_option_t options,
531 | utf8proc_custom_func custom_func, void *custom_data
532 | );
533 |
534 | /**
535 | * Normalizes the sequence of `length` codepoints pointed to by `buffer`
536 | * in-place (i.e., the result is also stored in `buffer`).
537 | *
538 | * @param buffer the (native-endian UTF-32) unicode codepoints to re-encode.
539 | * @param length the length (in codepoints) of the buffer.
540 | * @param options a bitwise or (`|`) of one or more of the following flags:
541 | * - @ref UTF8PROC_NLF2LS - convert LF, CRLF, CR and NEL into LS
542 | * - @ref UTF8PROC_NLF2PS - convert LF, CRLF, CR and NEL into PS
543 | * - @ref UTF8PROC_NLF2LF - convert LF, CRLF, CR and NEL into LF
544 | * - @ref UTF8PROC_STRIPCC - strip or convert all non-affected control characters
545 | * - @ref UTF8PROC_COMPOSE - try to combine decomposed codepoints into composite
546 | * codepoints
547 | * - @ref UTF8PROC_STABLE - prohibit combining characters that would violate
548 | * the unicode versioning stability
549 | *
550 | * @return
551 | * In case of success, the length (in codepoints) of the normalized UTF-32 string is
552 | * returned; otherwise, a negative error code is returned (@ref utf8proc_errmsg).
553 | *
554 | * @warning The entries of the array pointed to by `str` have to be in the
555 | * range `0x0000` to `0x10FFFF`. Otherwise, the program might crash!
556 | */
557 | UTF8PROC_DLLEXPORT utf8proc_ssize_t utf8proc_normalize_utf32(utf8proc_int32_t *buffer, utf8proc_ssize_t length, utf8proc_option_t options);
558 |
559 | /**
560 | * Reencodes the sequence of `length` codepoints pointed to by `buffer`
561 | * UTF-8 data in-place (i.e., the result is also stored in `buffer`).
562 | * Can optionally normalize the UTF-32 sequence prior to UTF-8 conversion.
563 | *
564 | * @param buffer the (native-endian UTF-32) unicode codepoints to re-encode.
565 | * @param length the length (in codepoints) of the buffer.
566 | * @param options a bitwise or (`|`) of one or more of the following flags:
567 | * - @ref UTF8PROC_NLF2LS - convert LF, CRLF, CR and NEL into LS
568 | * - @ref UTF8PROC_NLF2PS - convert LF, CRLF, CR and NEL into PS
569 | * - @ref UTF8PROC_NLF2LF - convert LF, CRLF, CR and NEL into LF
570 | * - @ref UTF8PROC_STRIPCC - strip or convert all non-affected control characters
571 | * - @ref UTF8PROC_COMPOSE - try to combine decomposed codepoints into composite
572 | * codepoints
573 | * - @ref UTF8PROC_STABLE - prohibit combining characters that would violate
574 | * the unicode versioning stability
575 | * - @ref UTF8PROC_CHARBOUND - insert 0xFF bytes before each grapheme cluster
576 | *
577 | * @return
578 | * In case of success, the length (in bytes) of the resulting nul-terminated
579 | * UTF-8 string is returned; otherwise, a negative error code is returned
580 | * (@ref utf8proc_errmsg).
581 | *
582 | * @warning The amount of free space pointed to by `buffer` must
583 | * exceed the amount of the input data by one byte, and the
584 | * entries of the array pointed to by `str` have to be in the
585 | * range `0x0000` to `0x10FFFF`. Otherwise, the program might crash!
586 | */
587 | UTF8PROC_DLLEXPORT utf8proc_ssize_t utf8proc_reencode(utf8proc_int32_t *buffer, utf8proc_ssize_t length, utf8proc_option_t options);
588 |
589 | /**
590 | * Given a pair of consecutive codepoints, return whether a grapheme break is
591 | * permitted between them (as defined by the extended grapheme clusters in UAX#29).
592 | *
593 | * @param codepoint1 The first codepoint.
594 | * @param codepoint2 The second codepoint, occurring consecutively after `codepoint1`.
595 | * @param state Beginning with Version 29 (Unicode 9.0.0), this algorithm requires
596 | * state to break graphemes. This state can be passed in as a pointer
597 | * in the `state` argument and should initially be set to 0. If the
598 | * state is not passed in (i.e. a null pointer is passed), UAX#29 rules
599 | * GB10/12/13 which require this state will not be applied, essentially
600 | * matching the rules in Unicode 8.0.0.
601 | *
602 | * @warning If the state parameter is used, `utf8proc_grapheme_break_stateful` must
603 | * be called IN ORDER on ALL potential breaks in a string. However, it
604 | * is safe to reset the state to zero after a grapheme break.
605 | */
606 | UTF8PROC_DLLEXPORT utf8proc_bool utf8proc_grapheme_break_stateful(
607 | utf8proc_int32_t codepoint1, utf8proc_int32_t codepoint2, utf8proc_int32_t *state);
608 |
609 | /**
610 | * Same as @ref utf8proc_grapheme_break_stateful, except without support for the
611 | * Unicode 9 additions to the algorithm. Supported for legacy reasons.
612 | */
613 | UTF8PROC_DLLEXPORT utf8proc_bool utf8proc_grapheme_break(
614 | utf8proc_int32_t codepoint1, utf8proc_int32_t codepoint2);
615 |
616 |
617 | /**
618 | * Given a codepoint `c`, return the codepoint of the corresponding
619 | * lower-case character, if any; otherwise (if there is no lower-case
620 | * variant, or if `c` is not a valid codepoint) return `c`.
621 | */
622 | UTF8PROC_DLLEXPORT utf8proc_int32_t utf8proc_tolower(utf8proc_int32_t c);
623 |
624 | /**
625 | * Given a codepoint `c`, return the codepoint of the corresponding
626 | * upper-case character, if any; otherwise (if there is no upper-case
627 | * variant, or if `c` is not a valid codepoint) return `c`.
628 | */
629 | UTF8PROC_DLLEXPORT utf8proc_int32_t utf8proc_toupper(utf8proc_int32_t c);
630 |
631 | /**
632 | * Given a codepoint `c`, return the codepoint of the corresponding
633 | * title-case character, if any; otherwise (if there is no title-case
634 | * variant, or if `c` is not a valid codepoint) return `c`.
635 | */
636 | UTF8PROC_DLLEXPORT utf8proc_int32_t utf8proc_totitle(utf8proc_int32_t c);
637 |
638 | /**
639 | * Given a codepoint, return a character width analogous to `wcwidth(codepoint)`,
640 | * except that a width of 0 is returned for non-printable codepoints
641 | * instead of -1 as in `wcwidth`.
642 | *
643 | * @note
644 | * If you want to check for particular types of non-printable characters,
645 | * (analogous to `isprint` or `iscntrl`), use @ref utf8proc_category. */
646 | UTF8PROC_DLLEXPORT int utf8proc_charwidth(utf8proc_int32_t codepoint);
647 |
648 | /**
649 | * Return the Unicode category for the codepoint (one of the
650 | * @ref utf8proc_category_t constants.)
651 | */
652 | UTF8PROC_DLLEXPORT utf8proc_category_t utf8proc_category(utf8proc_int32_t codepoint);
653 |
654 | /**
655 | * Return the two-letter (nul-terminated) Unicode category string for
656 | * the codepoint (e.g. `"Lu"` or `"Co"`).
657 | */
658 | UTF8PROC_DLLEXPORT const char *utf8proc_category_string(utf8proc_int32_t codepoint);
659 |
660 | /**
661 | * Maps the given UTF-8 string pointed to by `str` to a new UTF-8
662 | * string, allocated dynamically by `malloc` and returned via `dstptr`.
663 | *
664 | * If the @ref UTF8PROC_NULLTERM flag in the `options` field is set,
665 | * the length is determined by a NULL terminator, otherwise the
666 | * parameter `strlen` is evaluated to determine the string length, but
667 | * in any case the result will be NULL terminated (though it might
668 | * contain NULL characters with the string if `str` contained NULL
669 | * characters). Other flags in the `options` field are passed to the
670 | * functions defined above, and regarded as described. See also
671 | * @ref utf8proc_map_custom to supply a custom codepoint transformation.
672 | *
673 | * In case of success the length of the new string is returned,
674 | * otherwise a negative error code is returned.
675 | *
676 | * @note The memory of the new UTF-8 string will have been allocated
677 | * with `malloc`, and should therefore be deallocated with `free`.
678 | */
679 | UTF8PROC_DLLEXPORT utf8proc_ssize_t utf8proc_map(
680 | const utf8proc_uint8_t *str, utf8proc_ssize_t strlen, utf8proc_uint8_t **dstptr, utf8proc_option_t options
681 | );
682 |
683 | /**
684 | * Like @ref utf8proc_map, but also takes a `custom_func` mapping function
685 | * that is called on each codepoint in `str` before any other transformations
686 | * (along with a `custom_data` pointer that is passed through to `custom_func`).
687 | * The `custom_func` argument is ignored if it is `NULL`.
688 | */
689 | UTF8PROC_DLLEXPORT utf8proc_ssize_t utf8proc_map_custom(
690 | const utf8proc_uint8_t *str, utf8proc_ssize_t strlen, utf8proc_uint8_t **dstptr, utf8proc_option_t options,
691 | utf8proc_custom_func custom_func, void *custom_data
692 | );
693 |
694 | /** @name Unicode normalization
695 | *
696 | * Returns a pointer to newly allocated memory of a NFD, NFC, NFKD, NFKC or
697 | * NFKC_Casefold normalized version of the null-terminated string `str`. These
698 | * are shortcuts to calling @ref utf8proc_map with @ref UTF8PROC_NULLTERM
699 | * combined with @ref UTF8PROC_STABLE and flags indicating the normalization.
700 | */
701 | /** @{ */
702 | /** NFD normalization (@ref UTF8PROC_DECOMPOSE). */
703 | UTF8PROC_DLLEXPORT utf8proc_uint8_t *utf8proc_NFD(const utf8proc_uint8_t *str);
704 | /** NFC normalization (@ref UTF8PROC_COMPOSE). */
705 | UTF8PROC_DLLEXPORT utf8proc_uint8_t *utf8proc_NFC(const utf8proc_uint8_t *str);
706 | /** NFKD normalization (@ref UTF8PROC_DECOMPOSE and @ref UTF8PROC_COMPAT). */
707 | UTF8PROC_DLLEXPORT utf8proc_uint8_t *utf8proc_NFKD(const utf8proc_uint8_t *str);
708 | /** NFKC normalization (@ref UTF8PROC_COMPOSE and @ref UTF8PROC_COMPAT). */
709 | UTF8PROC_DLLEXPORT utf8proc_uint8_t *utf8proc_NFKC(const utf8proc_uint8_t *str);
710 | /**
711 | * NFKC_Casefold normalization (@ref UTF8PROC_COMPOSE and @ref UTF8PROC_COMPAT
712 | * and @ref UTF8PROC_CASEFOLD and @ref UTF8PROC_IGNORE).
713 | **/
714 | UTF8PROC_DLLEXPORT utf8proc_uint8_t *utf8proc_NFKC_Casefold(const utf8proc_uint8_t *str);
715 | /** @} */
716 |
717 | #ifdef __cplusplus
718 | }
719 | #endif
720 |
721 | #endif
722 |
--------------------------------------------------------------------------------
/utils.c:
--------------------------------------------------------------------------------
1 | #define _GNU_SOURCE
2 | #include "utils.h"
3 | #include //strdup, memcpy, strcmp, strlen sscanf strtok
4 | #include //perror printf FILENAME_MAX
5 |
6 | void * xcalloc (size_t n, size_t s)
7 | {
8 | void *val;
9 | val = calloc (n, s);
10 | CHECK_PTR(val)
11 | return val;
12 | }
13 |
14 | void * xrealloc (void *ptr, size_t size)
15 | {
16 | void *value = realloc (ptr, size);
17 | CHECK_PTR(value)
18 | return value;
19 | }
20 |
21 | void * xmalloc (size_t size)
22 | {
23 | void *value = malloc (size);
24 | CHECK_PTR(value)
25 | return value;
26 | }
27 |
28 | char * xstrdup (const char *s1)
29 | {
30 | void *value = strdup(s1);
31 | CHECK_PTR(value)
32 | return value;
33 | }
34 |
35 | void xstrcpy (char **s1,const char *s2)
36 | {
37 | *s1=xmalloc((strlen(s2)+1)*sizeof(char));
38 | strcpy(*s1, s2);
39 | }
40 |
41 | void xasprintf(char **strp, const char *fmt, char *src)
42 | {
43 | int rc;
44 | rc=asprintf(strp, fmt, src);
45 | if(rc==-1)
46 | {
47 | printf("asprintf failed");
48 | exit(EXIT_FAILURE);
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/utils.h:
--------------------------------------------------------------------------------
1 | #include //malloc, realloc, free, size_t, NULL, exit, EXIT_FAILURE , EXIT_SUCCESS, system
2 |
3 |
4 | #define CHECK_PTR(ptr) \
5 | if (ptr == NULL) { \
6 | perror("Out of memory"); \
7 | exit(EXIT_FAILURE); \
8 | };
9 |
10 |
11 | void * xcalloc (size_t n, size_t s);
12 | void * xrealloc (void *ptr, size_t size);
13 | void * xmalloc (size_t size);
14 | char * xstrdup (const char *s1);
15 | void xstrcpy (char **s1,const char *s2);
16 | void xasprintf(char **strp, const char *fmt, char *src);
17 |
--------------------------------------------------------------------------------
/video/cli.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/konstare/gdcv/3151309d57d147231c63bd51fd0f01f10fd6ea55/video/cli.gif
--------------------------------------------------------------------------------
/video/emacs.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/konstare/gdcv/3151309d57d147231c63bd51fd0f01f10fd6ea55/video/emacs.gif
--------------------------------------------------------------------------------
/video/ivy.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/konstare/gdcv/3151309d57d147231c63bd51fd0f01f10fd6ea55/video/ivy.gif
--------------------------------------------------------------------------------