├── LICENSE
├── README.md
├── crystal-mode.el
└── flycheck-crystal.el
/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 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
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 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
676 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # emacs-crystal-mode
2 | A minimal crystal mode for emacs, based on ruby-mode (of course)
3 |
--------------------------------------------------------------------------------
/crystal-mode.el:
--------------------------------------------------------------------------------
1 | ;;; crystal-mode.el --- Major mode for editing Crystal files
2 |
3 | ;; Copyright (C) 2015 Jason Pellerin
4 | ;; Authors: Jason Pellerin
5 | ;; URL: https://github.com/jpellerin/emacs-crystal-mode
6 | ;; Created: Tue Jun 23 2015
7 | ;; Keywords: languages crystal
8 | ;; Version 0.1
9 |
10 |
11 | ;; Based on on ruby-mode.el
12 |
13 | ;; Copyright (C) 1994-2015 Free Software Foundation, Inc.
14 |
15 | ;; Authors: Yukihiro Matsumoto
16 | ;; Nobuyoshi Nakada
17 | ;; URL: http://www.emacswiki.org/cgi-bin/wiki/RubyMode
18 | ;; Created: Fri Feb 4 14:49:13 JST 1994
19 | ;; Keywords: languages ruby
20 | ;; Version: 1.2
21 |
22 | ;; This file is part of GNU Emacs.
23 |
24 | ;; GNU Emacs is free software: you can redistribute it and/or modify
25 | ;; it under the terms of the GNU General Public License as published by
26 | ;; the Free Software Foundation, either version 3 of the License, or
27 | ;; (at your option) any later version.
28 |
29 | ;; GNU Emacs is distributed in the hope that it will be useful,
30 | ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
31 | ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
32 | ;; GNU General Public License for more details.
33 |
34 | ;; You should have received a copy of the GNU General Public License
35 | ;; along with GNU Emacs. If not, see .
36 |
37 | ;;; Commentary:
38 |
39 | ;; Provides font-locking, indentation support, and navigation for Crystal code.
40 | ;;
41 | ;; If you're installing manually, you should add this to your .emacs
42 | ;; file after putting it on your load path:
43 | ;;
44 | ;; (autoload 'crystal-mode "crystal-mode" "Major mode for crystal files" t)
45 | ;; (add-to-list 'auto-mode-alist '("\\.cr$" . crystal-mode))
46 | ;; (add-to-list 'interpreter-mode-alist '("crystal" . crystal-mode))
47 | ;;
48 | ;; Still needs more docstrings; search below for TODO.
49 |
50 | ;;; Code:
51 |
52 | (defgroup crystal nil
53 | "Major mode for editing Crystal code."
54 | :prefix "crystal-"
55 | :group 'languages)
56 |
57 | (defconst crystal-block-beg-keywords
58 | '("class" "module" "def" "if" "unless" "case" "while" "until" "for" "begin" "do"
59 | "macro" "lib" "enum" "struct" "describe" "it")
60 | "Keywords at the beginning of blocks.")
61 |
62 | (defconst crystal-block-beg-re
63 | (regexp-opt crystal-block-beg-keywords)
64 | "Regexp to match the beginning of blocks.")
65 |
66 | (defconst crystal-non-block-do-re
67 | (regexp-opt '("while" "until" "rescue") 'symbols)
68 | "Regexp to match keywords that nest without blocks.")
69 |
70 | (defconst crystal-indent-beg-re
71 | (concat "^\\(\\s *" (regexp-opt '("class" "module" "def" "macro" "lib" "enum" "struct"))
72 | "\\|"
73 | (regexp-opt '("if" "unless" "case" "while" "until" "for" "begin"))
74 | "\\)\\_>")
75 | "Regexp to match where the indentation gets deeper.")
76 |
77 | (defconst crystal-modifier-beg-keywords
78 | '("if" "unless" "while" "until")
79 | "Modifiers that are the same as the beginning of blocks.")
80 |
81 | (defconst crystal-modifier-beg-re
82 | (regexp-opt crystal-modifier-beg-keywords)
83 | "Regexp to match modifiers same as the beginning of blocks.")
84 |
85 | (defconst crystal-modifier-re
86 | (regexp-opt (cons "rescue" crystal-modifier-beg-keywords))
87 | "Regexp to match modifiers.")
88 |
89 | (defconst crystal-block-mid-keywords
90 | '("then" "else" "elsif" "when" "rescue" "ensure")
91 | "Keywords where the indentation gets shallower in middle of block statements.")
92 |
93 | (defconst crystal-block-mid-re
94 | (regexp-opt crystal-block-mid-keywords)
95 | "Regexp to match where the indentation gets shallower in middle of block statements.")
96 |
97 | (defconst crystal-block-op-keywords
98 | '("and" "or" "not")
99 | "Regexp to match boolean keywords.")
100 |
101 | (defconst crystal-block-hanging-re
102 | (regexp-opt (append crystal-modifier-beg-keywords crystal-block-op-keywords))
103 | "Regexp to match hanging block modifiers.")
104 |
105 | (defconst crystal-block-end-re "\\_")
106 |
107 | (defconst crystal-defun-beg-re
108 | '"\\(def\\|class\\|module\\|macro\\|lib\\|struct\\|enum\\)"
109 | "Regexp to match the beginning of a defun, in the general sense.")
110 |
111 | (defconst crystal-attr-re
112 | '"\\(@\\[\\)\\(.*\\)\\(\\]\\)"
113 | "Regexp to match attributes preceding a method or type")
114 |
115 | (defconst crystal-singleton-class-re
116 | "class\\s *<<"
117 | "Regexp to match the beginning of a singleton class context.")
118 |
119 | (eval-and-compile
120 | (defconst crystal-here-doc-beg-re
121 | "\\(<\\)<\\(-\\)?\\(\\([a-zA-Z0-9_]+\\)\\|[\"]\\([^\"]+\\)[\"]\\|[']\\([^']+\\)[']\\)"
122 | "Regexp to match the beginning of a heredoc.")
123 |
124 | (defconst crystal-expression-expansion-re
125 | "\\(?:[^\\]\\|\\=\\)\\(\\\\\\\\\\)*\\(#\\({[^}\n\\\\]*\\(\\\\.[^}\n\\\\]*\\)*}\\|\\(\\$\\|@\\|@@\\)\\(\\w\\|_\\)+\\|\\$[^a-zA-Z \n]\\)\\)"))
126 |
127 |
128 | (defun crystal-here-doc-end-match ()
129 | "Return a regexp to find the end of a heredoc.
130 |
131 | This should only be called after matching against `crystal-here-doc-beg-re'."
132 | (concat "^"
133 | (if (match-string 2) "[ \t]*" nil)
134 | (regexp-quote
135 | (or (match-string 4)
136 | (match-string 5)
137 | (match-string 6)))))
138 |
139 | (defconst crystal-delimiter
140 | (concat "[?$/%(){}#\"'`.:]\\|<<\\|\\[\\|\\]\\|\\_<\\|\\<\\("
141 | crystal-block-beg-re
142 | "\\)\\_>\\|" crystal-block-end-re
143 | "\\|^=begin\\|" crystal-here-doc-beg-re))
144 |
145 | (defconst crystal-negative
146 | (concat "^[ \t]*\\(\\(" crystal-block-mid-re "\\)\\>\\|"
147 | crystal-block-end-re "\\|}\\|\\]\\)")
148 | "Regexp to match where the indentation gets shallower.")
149 |
150 | (defconst crystal-operator-re "[-,.+*/%&|^~=<>:]\\|\\\\$"
151 | "Regexp to match operators.")
152 |
153 | (defconst crystal-symbol-chars "a-zA-Z0-9_"
154 | "List of characters that symbol names may contain.")
155 |
156 | (defconst crystal-symbol-re (concat "[" crystal-symbol-chars "]")
157 | "Regexp to match symbols.")
158 |
159 | (defvar crystal-use-smie t)
160 |
161 | (defvar crystal-mode-map
162 | (let ((map (make-sparse-keymap)))
163 | (unless crystal-use-smie
164 | (define-key map (kbd "M-C-b") 'crystal-backward-sexp)
165 | (define-key map (kbd "M-C-f") 'crystal-forward-sexp)
166 | (define-key map (kbd "M-C-q") 'crystal-indent-exp))
167 | (when crystal-use-smie
168 | (define-key map (kbd "M-C-d") 'smie-down-list))
169 | (define-key map (kbd "M-C-p") 'crystal-beginning-of-block)
170 | (define-key map (kbd "M-C-n") 'crystal-end-of-block)
171 | (define-key map (kbd "C-c {") 'crystal-toggle-block)
172 | (define-key map (kbd "C-c '") 'crystal-toggle-string-quotes)
173 | map)
174 | "Keymap used in Crystal mode.")
175 |
176 | (defvar crystal-buffer-name "*crystal*")
177 |
178 | (easy-menu-define
179 | crystal-mode-menu
180 | crystal-mode-map
181 | "Crystal Mode Menu"
182 | '("Crystal"
183 | ["Beginning of Block" crystal-beginning-of-block t]
184 | ["End of Block" crystal-end-of-block t]
185 | ["Toggle Block" crystal-toggle-block t]
186 | "--"
187 | ["Toggle String Quotes" crystal-toggle-string-quotes t]
188 | "--"
189 | ["Backward Sexp" crystal-backward-sexp
190 | :visible (not crystal-use-smie)]
191 | ["Backward Sexp" backward-sexp
192 | :visible crystal-use-smie]
193 | ["Forward Sexp" crystal-forward-sexp
194 | :visible (not crystal-use-smie)]
195 | ["Forward Sexp" forward-sexp
196 | :visible crystal-use-smie]
197 | ["Indent Sexp" crystal-indent-exp
198 | :visible (not crystal-use-smie)]
199 | ["Indent Sexp" prog-indent-sexp
200 | :visible crystal-use-smie]
201 | "--"
202 | ["Format" crystal-format t]))
203 |
204 | (defvar crystal-mode-syntax-table
205 | (let ((table (make-syntax-table)))
206 | (modify-syntax-entry ?\' "\"" table)
207 | (modify-syntax-entry ?\" "\"" table)
208 | (modify-syntax-entry ?\` "\"" table)
209 | (modify-syntax-entry ?# "<" table)
210 | (modify-syntax-entry ?\n ">" table)
211 | (modify-syntax-entry ?\\ "\\" table)
212 | (modify-syntax-entry ?$ "." table)
213 | (modify-syntax-entry ?_ "_" table)
214 | (modify-syntax-entry ?: "_" table)
215 | (modify-syntax-entry ?< "." table)
216 | (modify-syntax-entry ?> "." table)
217 | (modify-syntax-entry ?& "." table)
218 | (modify-syntax-entry ?| "." table)
219 | (modify-syntax-entry ?% "." table)
220 | (modify-syntax-entry ?= "." table)
221 | (modify-syntax-entry ?/ "." table)
222 | (modify-syntax-entry ?+ "." table)
223 | (modify-syntax-entry ?* "." table)
224 | (modify-syntax-entry ?- "." table)
225 | (modify-syntax-entry ?\; "." table)
226 | (modify-syntax-entry ?\( "()" table)
227 | (modify-syntax-entry ?\) ")(" table)
228 | (modify-syntax-entry ?\{ "(}" table)
229 | (modify-syntax-entry ?\} "){" table)
230 | (modify-syntax-entry ?\[ "(]" table)
231 | (modify-syntax-entry ?\] ")[" table)
232 | table)
233 | "Syntax table to use in Crystal mode.")
234 |
235 | (defcustom crystal-indent-tabs-mode nil
236 | "Indentation can insert tabs in Crystal mode if this is non-nil."
237 | :type 'boolean
238 | :group 'crystal
239 | :safe 'booleanp)
240 |
241 | (defcustom crystal-indent-level 2
242 | "Indentation of Crystal statements."
243 | :type 'integer
244 | :group 'crystal
245 | :safe 'integerp)
246 |
247 | (defcustom crystal-executable "crystal"
248 | "Location of Crystal executable."
249 | :type 'string
250 | :group 'crystal)
251 |
252 | (defcustom crystal-comment-column (default-value 'comment-column)
253 | "Indentation column of comments."
254 | :type 'integer
255 | :group 'crystal
256 | :safe 'integerp)
257 |
258 | (defconst crystal-alignable-keywords '(if while unless until begin case for def macro class)
259 | "Keywords that can be used in `crystal-align-to-stmt-keywords'.")
260 |
261 | (defcustom crystal-align-to-stmt-keywords '(def)
262 | "Keywords after which we align the expression body to statement.
263 |
264 | When nil, an expression that begins with one these keywords is
265 | indented to the column of the keyword. Example:
266 |
267 | tee = if foo
268 | bar
269 | else
270 | qux
271 | end
272 |
273 | If this value is t or contains a symbol with the name of given
274 | keyword, the expression is indented to align to the beginning of
275 | the statement:
276 |
277 | tee = if foo
278 | bar
279 | else
280 | qux
281 | end
282 |
283 | Only has effect when `crystal-use-smie' is t.
284 | "
285 | :type `(choice
286 | (const :tag "None" nil)
287 | (const :tag "All" t)
288 | (repeat :tag "User defined"
289 | (choice ,@(mapcar
290 | (lambda (kw) (list 'const kw))
291 | crystal-alignable-keywords))))
292 | :group 'crystal
293 | :safe 'listp
294 | :version "24.4")
295 |
296 | (defcustom crystal-align-chained-calls nil
297 | "If non-nil, align chained method calls.
298 |
299 |
300 | Each method call on a separate line will be aligned to the column
301 | of its parent.
302 |
303 | Only has effect when `crystal-use-smie' is t."
304 | :type 'boolean
305 | :group 'crystal
306 | :safe 'booleanp
307 | :version "24.4")
308 |
309 | (defcustom crystal-deep-arglist t
310 | "Deep indent lists in parenthesis when non-nil.
311 | Also ignores spaces after parenthesis when `space'.
312 | Only has effect when `crystal-use-smie' is nil."
313 | :type 'boolean
314 | :group 'crystal
315 | :safe 'booleanp)
316 |
317 | ;; FIXME Woefully under documented. What is the point of the last `t'?.
318 | (defcustom crystal-deep-indent-paren '(?\( ?\[ ?\] t)
319 | "Deep indent lists in parenthesis when non-nil.
320 | The value t means continuous line.
321 | Also ignores spaces after parenthesis when `space'.
322 | Only has effect when `crystal-use-smie' is nil."
323 | :type '(choice (const nil)
324 | character
325 | (repeat (choice character
326 | (cons character (choice (const nil)
327 | (const t)))
328 | (const t) ; why?
329 | )))
330 | :group 'crystal)
331 |
332 | (defcustom crystal-deep-indent-paren-style 'space
333 | "Default deep indent style.
334 | Only has effect when `crystal-use-smie' is nil."
335 | :type '(choice (const t) (const nil) (const space))
336 | :group 'crystal)
337 |
338 | (defcustom crystal-encoding-map
339 | '((us-ascii . nil) ;; Do not put coding: us-ascii
340 | (shift-jis . cp932) ;; Emacs charset name of Shift_JIS
341 | (shift_jis . cp932) ;; MIME charset name of Shift_JIS
342 | (japanese-cp932 . cp932)) ;; Emacs charset name of CP932
343 | "Alist to map encoding name from Emacs to Crystal.
344 | Associating an encoding name with nil means it needs not be
345 | explicitly declared in magic comment."
346 | :type '(repeat (cons (symbol :tag "From") (symbol :tag "To")))
347 | :group 'crystal)
348 |
349 | (defcustom crystal-insert-encoding-magic-comment nil
350 | "Insert a magic Crystal encoding comment upon save if this is non-nil.
351 | The encoding will be auto-detected. The format of the encoding comment
352 | is customizable via `crystal-encoding-magic-comment-style'.
353 |
354 | When set to `always-utf8' an utf-8 comment will always be added,
355 | even if it's not required."
356 | :type 'boolean :group 'crystal)
357 |
358 | (defcustom crystal-encoding-magic-comment-style 'crystal
359 | "The style of the magic encoding comment to use."
360 | :type '(choice
361 | (const :tag "Emacs Style" emacs)
362 | (const :tag "Crystal Style" crystal)
363 | (const :tag "Custom Style" custom))
364 | :group 'crystal
365 | :version "24.4")
366 |
367 | (defcustom crystal-custom-encoding-magic-comment-template "# encoding: %s"
368 | "A custom encoding comment template.
369 | It is used when `crystal-encoding-magic-comment-style' is set to `custom'."
370 | :type 'string
371 | :group 'crystal
372 | :version "24.4")
373 |
374 | (defcustom crystal-use-encoding-map t
375 | "Use `crystal-encoding-map' to set encoding magic comment if this is non-nil."
376 | :type 'boolean :group 'crystal)
377 |
378 | ;;; SMIE support
379 |
380 | (require 'smie)
381 |
382 | (defconst crystal-smie-grammar
383 | (smie-prec2->grammar
384 | (smie-merge-prec2s
385 | (smie-bnf->prec2
386 | '((id)
387 | (insts (inst) (insts ";" insts))
388 | (inst (exp) (inst "iuwu-mod" exp)
389 | ;; Somewhat incorrect (both can be used multiple times),
390 | ;; but avoids lots of conflicts:
391 | (exp "and" exp) (exp "or" exp))
392 | (exp (exp1) (exp "," exp) (exp "=" exp)
393 | (id " @ " exp))
394 | (exp1 (exp2) (exp2 "?" exp1 ":" exp1))
395 | (exp2 (exp3) (exp3 "." exp2))
396 | (exp3 ("def" insts "end")
397 | ("begin" insts-rescue-insts "end")
398 | ("do" insts "end")
399 | ("class" insts "end") ("module" insts "end") ("struct" insts "end")
400 | ("lib" insts "end") ("enum" insts "end")
401 | ("[" expseq "]")
402 | ("{" hashvals "}")
403 | ("{" insts "}")
404 | ("{{" exp "}}")
405 | ("{{" id "}}")
406 | ("while" insts "end")
407 | ("until" insts "end")
408 | ("unless" insts "end")
409 | ("if" if-body "end")
410 | ("for" for-body "end")
411 | ("->{" proc-body "}")
412 | ("macro" insts "end")
413 | ("{%" exp "%}")
414 | ("{%for%}" insts "{%end%}")
415 | ("{%if%}" if-macro-body "{%end%}")
416 | ("{%unless%}" insts "{%end%}")
417 | ("case" cases "end")
418 | ("lib" insts "end")
419 | ("struct" insts "end")
420 | ("enum" insts "end")
421 | ("fun" insts "end")
422 | ("type" insts "end"))
423 | ;;(macro-cmd (inst) (forexp))
424 | ;;(macro-cmds (macro-cmd) (macro-cmds ";" macro-cmds))
425 | ;;(macro-start ("{%" macro-cmd "%}"))
426 | ;;(macro-block (macro-start macroinsts "{%end%}"))
427 | ;;(macro-code ("{%" macro-cmds "%}"))
428 | ;; FIXME this is wrong
429 | ;;(macro-inst (inst) (macro-block) (macro-code))
430 | ;;(macro-insts (macro-inst) (macro-insts ";" macro-insts))
431 | ;;(macro-body (macro-insts))
432 | (macro-exp (for-head))
433 | (formal-params ("opening-|" exp "closing-|"))
434 | (for-body (for-head ";" insts))
435 | (for-head (exp "in" exp))
436 | (proc-body (insts))
437 | (cases (exp "then" insts)
438 | (cases "when" cases) (insts "else" insts))
439 | (expseq (exp) );;(expseq "," expseq)
440 | (hashvals (id "=>" exp1) (hashvals "," hashvals))
441 | (insts-rescue-insts (insts)
442 | (insts-rescue-insts "rescue" insts-rescue-insts)
443 | (insts-rescue-insts "ensure" insts-rescue-insts))
444 | (itheni (insts) (exp "then" insts))
445 | (ielsei (itheni) (itheni "else" insts))
446 | (if-body (ielsei) (if-body "elsif" if-body))
447 | (itheni-macro (insts) (exp "{%then%}" insts))
448 | (ielsei-macro (itheni-macro) (itheni-macro "{%else%}" insts))
449 | (if-macro-body (ielsei-macro) (if-macro-body "{%elsif%}" if-macro-body))
450 | )
451 |
452 | '((nonassoc "in") (assoc ";") (right " @ ")
453 | (assoc ",") (right "="))
454 | '((assoc "when"))
455 | '((assoc "elsif"))
456 | '((assoc "{%elsif%}"))
457 | '((assoc "rescue" "ensure"))
458 | '((assoc ",")))
459 |
460 | (smie-precs->prec2
461 | '((right "=")
462 | (right "+=" "-=" "*=" "/=" "%=" "**=" "&=" "|=" "^="
463 | "<<=" ">>=" "&&=" "||=")
464 | (left ".." "...")
465 | (left "+" "-")
466 | (left "*" "/" "%" "**")
467 | (left "&&" "||")
468 | (left "^" "&" "|")
469 | (nonassoc "<=>")
470 | (nonassoc ">" ">=" "<" "<=")
471 | (nonassoc "==" "===" "!=")
472 | (nonassoc "=~" "!~")
473 | (left "<<" ">>")
474 | (right "."))))))
475 |
476 | (defun crystal-smie--eoms ()
477 | (save-excursion
478 | (forward-char -2)
479 | (looking-at "%}")
480 | )
481 | )
482 |
483 | (defun crystal-smie--bosp ()
484 | (save-excursion (skip-chars-backward " \t")
485 | (or (bolp) (memq (char-before) '(?\; ?=)))))
486 |
487 | (defun crystal-smie--implicit-semi-p ()
488 | (save-excursion
489 | (skip-chars-backward " \t")
490 | (not (or (bolp)
491 | (memq (char-before) '(?\[ ?\())
492 | (and (memq (char-before)
493 | '(?\; ?- ?+ ?* ?/ ?: ?. ?, ?\\ ?& ?> ?< ?% ?~ ?^))
494 | ;; Not a binary operator symbol.
495 | (not (eq (char-before (1- (point))) ?:))
496 | ;; Not the end of a regexp or a percent literal.
497 | (not (memq (car (syntax-after (1- (point)))) '(7 15))))
498 | (and (eq (char-before) ?\?)
499 | (equal (save-excursion (crystal-smie--backward-token)) "?"))
500 | (and (eq (char-before) ?=)
501 | ;; Not a symbol :==, :!=, or a foo= method.
502 | (string-match "\\`\\s." (save-excursion
503 | (crystal-smie--backward-token))))
504 | (and (eq (char-before) ?|)
505 | (member (save-excursion (crystal-smie--backward-token))
506 | '("|" "||")))
507 | (and (eq (car (syntax-after (1- (point)))) 2)
508 | (member (save-excursion (crystal-smie--backward-token))
509 | '("iuwu-mod" "and" "or")))
510 | (save-excursion
511 | (forward-comment 1)
512 | (eq (char-after) ?.))))))
513 |
514 | (defun crystal-smie--redundant-do-p (&optional skip)
515 | (save-excursion
516 | (if skip (backward-word 1))
517 | (member (nth 2 (smie-backward-sexp ";")) '("while" "until" "for"))))
518 |
519 | ;; this handles "macro def ... end" blocks
520 | (defun crystal-smie--redundant-macro-def-p (&optional skip)
521 | (save-excursion
522 | (if skip (backward-word 1))
523 | (member (nth 2 (smie-backward-sexp ";")) '("macro"))))
524 |
525 | (defun crystal-smie--opening-pipe-p ()
526 | (save-excursion
527 | (if (eq ?| (char-before)) (forward-char -1))
528 | (skip-chars-backward " \t\n")
529 | (or (eq ?\{ (char-before))
530 | (looking-back "\\_ (save-excursion (forward-comment (point-max)) (point))
629 | (line-end-position))
630 | (crystal-smie--forward-token)) ;Fully redundant.
631 | (t ";")))
632 | ((equal tok "class")
633 | (cond
634 | ((> (save-excursion (forward-comment (point-max)) (point))
635 | (line-end-position))
636 | (crystal-smie--forward-token)) ;Fully redundant.
637 | (t ";")))
638 | ((equal tok "do")
639 | (cond
640 | ((not (crystal-smie--redundant-do-p 'skip)) tok)
641 | ((> (save-excursion (forward-comment (point-max)) (point))
642 | (line-end-position))
643 | (crystal-smie--forward-token)) ;Fully redundant.
644 | (t ";")))
645 | (t
646 | ;;(message "forward '%s'" tok)
647 | tok)
648 | ))))))))
649 |
650 | (defun crystal-smie--backward-token ()
651 | (let ((pos (point)))
652 | (forward-comment (- (point)))
653 |
654 | (cond
655 | ;; FIXME why do these never fire?
656 | ;; treat macro expr similarly to heredocs? go backwards and tokenize
657 | ;; as the last token inside of the macro expr
658 | ;;((looking-at crystal-macro-cmd-re) "{%end%}")
659 | ;;((looking-at crystal-macro-end-cmd-re) (match-string 1))
660 | ((looking-back "%}")
661 | ;; (message "looking back at a macro cmd")
662 | ;; scan backawards to {%
663 | (re-search-backward "{%")
664 | ;; (message "at %s %s" (point) (char-after))
665 | (save-excursion
666 | (forward-char 2)
667 | (skip-chars-forward " \t")
668 | ;; fixme only if token is in if/else/for/end/while/unless
669 | (let ((tok (smie-default-forward-token)))
670 | (if (member tok '("if" "else" "end" "elsif" "unless" "for" "while"))
671 | (concat "{%" tok "%}")
672 | ";"))))
673 | ((and (> pos (line-end-position)) (crystal-smie--implicit-semi-p))
674 | (skip-chars-forward " \t") ";")
675 | ((and (bolp) (not (bobp))) ;Presumably a heredoc.
676 | ;; Tokenize the whole heredoc as semicolon.
677 | (goto-char (scan-sexps (point) -1))
678 | ;; (message "back to heredoc")
679 | ";")
680 | ((and (> pos (point)) (not (bolp))
681 | (crystal-smie--args-separator-p pos))
682 | ;; We have "ID SPC ID", which is a method call, but it binds less tightly
683 | ;; than commas, since a method call can also be "ID ARG1, ARG2, ARG3".
684 | ;; In some textbooks, "e1 @ e2" is used to mean "call e1 with arg e2".
685 | " @ ")
686 | (t
687 | (let ((tok (smie-default-backward-token))
688 | (dot (crystal-smie--at-dot-call)))
689 | ;;(message "default backward tok is '%s'" tok)
690 | (when dot
691 | ;; (message "back dot")
692 | (setq tok (concat "." tok)))
693 | (when (and (eq ?: (char-before)) (string-match "\\`\\s." tok))
694 | ;; (message "back :")
695 | (forward-char -1) (setq tok (concat ":" tok))) ;; bug#15208.
696 | (cond
697 | ((member tok '("unless" "if" "while" "until"))
698 | ;; (message "back if while")
699 | (if (crystal-smie--bosp)
700 | tok "iuwu-mod"))
701 | ((equal tok "|")
702 | ;; (message "back pipe")
703 | (cond
704 | ((crystal-smie--opening-pipe-p) "opening-|")
705 | ((crystal-smie--closing-pipe-p) "closing-|")
706 | (t tok)))
707 | ((string-match-p "\\`|[*&]\\'" tok)
708 | ;; (message "back backtick")
709 | (forward-char 1)
710 | (substring tok 1))
711 | ((and (equal tok "") (eq ?\\ (char-before)) (looking-at "\n"))
712 | ;; (message "back escaped")
713 | (forward-char -1) (crystal-smie--backward-token))
714 | ((equal tok "def")
715 | ;; (message "back def")
716 | (cond
717 | ((not (crystal-smie--redundant-macro-def-p)) tok)
718 | ((> (save-excursion (forward-word 1)
719 | (forward-comment (point-max)) (point))
720 | (line-end-position))
721 | (crystal-smie--backward-token)) ;Fully redundant.
722 | (t ";")))
723 | ((equal tok "do")
724 | ;; (message "back do")
725 | (cond
726 | ((not (crystal-smie--redundant-do-p)) tok)
727 | ((> (save-excursion (forward-word 1)
728 | (forward-comment (point-max)) (point))
729 | (line-end-position))
730 | (crystal-smie--backward-token)) ;Fully redundant.
731 | (t ";")))
732 | (t
733 | ;;(message "backward '%s'" tok)
734 | tok)))))))
735 |
736 | (defun crystal-smie--indent-to-stmt ()
737 | (save-excursion
738 | (smie-backward-sexp ";")
739 | (cons 'column (smie-indent-virtual))))
740 |
741 | (defun crystal-smie--indent-to-stmt-p (keyword)
742 | (or (eq t crystal-align-to-stmt-keywords)
743 | (memq (intern keyword) crystal-align-to-stmt-keywords)))
744 |
745 | (defun crystal-smie-rules (kind token)
746 | (message "indent '%s' '%s'" kind token)
747 | (pcase (cons kind token)
748 | (`(:elem . basic) crystal-indent-level)
749 | ;; "foo" "bar" is the concatenation of the two strings, so the second
750 | ;; should be aligned with the first.
751 | (`(:elem . args) (if (looking-at "\\s\"") 0))
752 | ;; (`(:after . ",") (smie-rule-separator kind))
753 | (`(:after . ,(or `"{%else%}" `"{%elsif%}" ))
754 | (smie-rule-parent crystal-indent-level)
755 | )
756 | (`(:before . ";")
757 | ;; (message "Before ;")
758 | (cond
759 | ((smie-rule-parent-p "def" "begin" "do" "class" "module" "{%for%}"
760 | "while" "until" "unless" "macro" "lib" "enum" "struct"
761 | "if" "then" "elsif" "else" "when" "{%if%}"
762 | "{%elsif%}" "{%else%}" "{%unless%}"
763 | "rescue" "ensure" "{")
764 | (message "Still got this one %s" (smie-indent--parent))
765 | (smie-rule-parent crystal-indent-level))
766 | ;; For (invalid) code between switch and case.
767 | ;; (if (smie-parent-p "switch") 4)
768 | ))
769 |
770 | (`(:before . ,(or `"(" `"[" `"{"))
771 | ;; (message "Before ( [ {")
772 | (cond
773 | ((and (equal token "{")
774 | (not (smie-rule-prev-p "(" "{" "[" "," "=>" "=" "return" ";"))
775 | (save-excursion
776 | (forward-comment -1)
777 | (not (eq (preceding-char) ?:))))
778 | ;; Curly block opener.
779 | ;; (message "curly block opener")
780 | (crystal-smie--indent-to-stmt))
781 | ((smie-rule-hanging-p)
782 | ;; (message "hanging p")
783 | ;; Treat purely syntactic block-constructs as being part of their parent,
784 | ;; when the opening token is hanging and the parent is not an
785 | ;; open-paren.
786 | (cond
787 | ((eq (car (smie-indent--parent)) t) nil)
788 | ;; When after `.', let's always de-indent,
789 | ;; because when `.' is inside the line, the
790 | ;; additional indentation from it looks out of place.
791 | ((smie-rule-parent-p ".")
792 | (let (smie--parent)
793 | (save-excursion
794 | ;; Traverse up the parents until the parent is "." at
795 | ;; indentation, or any other token.
796 | (while (and (let ((parent (smie-indent--parent)))
797 | (goto-char (cadr parent))
798 | (save-excursion
799 | (unless (integerp (car parent)) (forward-char -1))
800 | (not (crystal-smie--bosp))))
801 | (progn
802 | (setq smie--parent nil)
803 | (smie-rule-parent-p "."))))
804 | (smie-rule-parent))))
805 | (t (smie-rule-parent))))))
806 | (`(:after . ,(or `"(" "[" "{"))
807 | ;; FIXME: Shouldn't this be the default behavior of
808 | ;; `smie-indent-after-keyword'?
809 | ;; (message "After ([{")
810 | (save-excursion
811 | (forward-char 1)
812 | (skip-chars-forward " \t")
813 | ;; `smie-rule-hanging-p' is not good enough here,
814 | ;; because we want to reject hanging tokens at bol, too.
815 | (unless (or (eolp) (forward-comment 1))
816 | (cons 'column (current-column)))))
817 | (`(:before . " @ ")
818 | ;; (message "Before @")
819 | (save-excursion
820 | (skip-chars-forward " \t")
821 | (cons 'column (current-column))))
822 | (`(:before . "do") (crystal-smie--indent-to-stmt))
823 | (`(:before . ".")
824 | (if (smie-rule-sibling-p)
825 | (and crystal-align-chained-calls 0)
826 | crystal-indent-level))
827 | (`(:before . ,(or `"else" `"then" `"elsif" `"rescue" `"ensure" `"{%else%}" `"{%elsif%}"))
828 | (smie-rule-parent))
829 | (`(:before . "when")
830 | ;; Align to the previous `when', but look up the virtual
831 | ;; indentation of `case'.
832 | (if (smie-rule-sibling-p) 0 (smie-rule-parent)))
833 | (`(:after . ,(or "=" "iuwu-mod" "+" "-" "*" "/" "&&" "||" "%" "**" "^" "&"
834 | "<=>" ">" "<" ">=" "<=" "==" "===" "!=" "<<" ">>"
835 | "+=" "-=" "*=" "/=" "%=" "**=" "&=" "|=" "^=" "|"
836 | "<<=" ">>=" "&&=" "||=" "and" "or"))
837 | (and (smie-rule-parent-p ";" nil)
838 | (smie-indent--hanging-p)
839 | crystal-indent-level))
840 | (`(:after . ,(or "?" ":")) crystal-indent-level)
841 | (`(:before . ,(guard (memq (intern-soft token) crystal-alignable-keywords)))
842 | (when (not (crystal--at-indentation-p))
843 | (if (crystal-smie--indent-to-stmt-p token)
844 | (crystal-smie--indent-to-stmt)
845 | (cons 'column (current-column)))))
846 | ))
847 |
848 | (defun crystal--at-indentation-p (&optional point)
849 | (save-excursion
850 | (unless point (setq point (point)))
851 | (forward-line 0)
852 | (skip-chars-forward " \t")
853 | (eq (point) point)))
854 |
855 | (defun crystal-imenu-create-index-in-block (prefix beg end)
856 | "Create an imenu index of methods inside a block."
857 | (let ((index-alist '()) (case-fold-search nil)
858 | name next pos decl sing)
859 | (goto-char beg)
860 | (while (re-search-forward "^\\s *\\(\\(class\\s +\\|\\(class\\s *<<\\s *\\)\\|module\\s +\\)\\([^\(<\n ]+\\)\\|\\(def\\|alias\\)\\s +\\([^\(\n ]+\\)\\)" end t)
861 | (setq sing (match-beginning 3))
862 | (setq decl (match-string 5))
863 | (setq next (match-end 0))
864 | (setq name (or (match-string 4) (match-string 6)))
865 | (setq pos (match-beginning 0))
866 | (cond
867 | ((string= "alias" decl)
868 | (if prefix (setq name (concat prefix name)))
869 | (push (cons name pos) index-alist))
870 | ((string= "def" decl)
871 | (if prefix
872 | (setq name
873 | (cond
874 | ((string-match "^self\." name)
875 | (concat (substring prefix 0 -1) (substring name 4)))
876 | (t (concat prefix name)))))
877 | (push (cons name pos) index-alist)
878 | (crystal-accurate-end-of-block end))
879 | (t
880 | (if (string= "self" name)
881 | (if prefix (setq name (substring prefix 0 -1)))
882 | (if prefix (setq name (concat (substring prefix 0 -1) "::" name)))
883 | (push (cons name pos) index-alist))
884 | (crystal-accurate-end-of-block end)
885 | (setq beg (point))
886 | (setq index-alist
887 | (nconc (crystal-imenu-create-index-in-block
888 | (concat name (if sing "." "#"))
889 | next beg) index-alist))
890 | (goto-char beg))))
891 | index-alist))
892 |
893 |
894 | (defun crystal-imenu-create-index ()
895 | "Create an imenu index of all methods in the buffer."
896 | (nreverse (crystal-imenu-create-index-in-block nil (point-min) nil)))
897 |
898 | (defun crystal-accurate-end-of-block (&optional end)
899 | "Jump to the end of the current block or END, whichever is closer."
900 | (let (state
901 | (end (or end (point-max))))
902 | (if crystal-use-smie
903 | (save-restriction
904 | (back-to-indentation)
905 | (narrow-to-region (point) end)
906 | (smie-forward-sexp))
907 | (while (and (setq state (apply 'crystal-parse-partial end state))
908 | (>= (nth 2 state) 0) (< (point) end))))))
909 |
910 | (defun crystal-mode-variables ()
911 | "Set up initial buffer-local variables for Crystal mode."
912 | (setq indent-tabs-mode crystal-indent-tabs-mode)
913 | (if crystal-use-smie
914 | (smie-setup crystal-smie-grammar #'crystal-smie-rules
915 | :forward-token #'crystal-smie--forward-token
916 | :backward-token #'crystal-smie--backward-token)
917 | (setq-local indent-line-function 'crystal-indent-line))
918 | (setq-local comment-start "# ")
919 | (setq-local comment-end "")
920 | (setq-local comment-column crystal-comment-column)
921 | (setq-local comment-start-skip "#+ *")
922 | (setq-local parse-sexp-ignore-comments t)
923 | (setq-local parse-sexp-lookup-properties t)
924 | (setq-local paragraph-start (concat "$\\|" page-delimiter))
925 | (setq-local paragraph-separate paragraph-start)
926 | (setq-local paragraph-ignore-fill-prefix t))
927 |
928 | (defun crystal--insert-coding-comment (encoding)
929 | "Insert a magic coding comment for ENCODING.
930 | The style of the comment is controlled by `crystal-encoding-magic-comment-style'."
931 | (let ((encoding-magic-comment-template
932 | (pcase crystal-encoding-magic-comment-style
933 | (`crystal "# coding: %s")
934 | (`emacs "# -*- coding: %s -*-")
935 | (`custom
936 | crystal-custom-encoding-magic-comment-template))))
937 | (insert
938 | (format encoding-magic-comment-template encoding)
939 | "\n")))
940 |
941 | (defun crystal--detect-encoding ()
942 | (if (eq crystal-insert-encoding-magic-comment 'always-utf8)
943 | "utf-8"
944 | (let ((coding-system
945 | (or save-buffer-coding-system
946 | buffer-file-coding-system)))
947 | (if coding-system
948 | (setq coding-system
949 | (or (coding-system-get coding-system 'mime-charset)
950 | (coding-system-change-eol-conversion coding-system nil))))
951 | (if coding-system
952 | (symbol-name
953 | (if crystal-use-encoding-map
954 | (let ((elt (assq coding-system crystal-encoding-map)))
955 | (if elt (cdr elt) coding-system))
956 | coding-system))
957 | "ascii-8bit"))))
958 |
959 | (defun crystal--encoding-comment-required-p ()
960 | (or (eq crystal-insert-encoding-magic-comment 'always-utf8)
961 | (re-search-forward "[^\0-\177]" nil t)))
962 |
963 | (defun crystal-mode-set-encoding ()
964 | "Insert a magic comment header with the proper encoding if necessary."
965 | (save-excursion
966 | (widen)
967 | (goto-char (point-min))
968 | (when (crystal--encoding-comment-required-p)
969 | (goto-char (point-min))
970 | (let ((coding-system (crystal--detect-encoding)))
971 | (when coding-system
972 | (if (looking-at "^#!") (beginning-of-line 2))
973 | (cond ((looking-at "\\s *#\\s *.*\\(en\\)?coding\\s *:\\s *\\([-a-z0-9_]*\\)")
974 | ;; update existing encoding comment if necessary
975 | (unless (string= (match-string 2) coding-system)
976 | (goto-char (match-beginning 2))
977 | (delete-region (point) (match-end 2))
978 | (insert coding-system)))
979 | ((looking-at "\\s *#.*coding\\s *[:=]"))
980 | (t (when crystal-insert-encoding-magic-comment
981 | (crystal--insert-coding-comment coding-system))))
982 | (when (buffer-modified-p)
983 | (basic-save-buffer-1)))))))
984 |
985 | (defvar crystal--electric-indent-chars '(?. ?\) ?} ?\]))
986 |
987 | (defun crystal--electric-indent-p (char)
988 | (cond
989 | ((memq char crystal--electric-indent-chars)
990 | ;; Reindent after typing a char affecting indentation.
991 | (crystal--at-indentation-p (1- (point))))
992 | ((memq (char-after) crystal--electric-indent-chars)
993 | ;; Reindent after inserting something in front of the above.
994 | (crystal--at-indentation-p (1- (point))))
995 | ((or (and (>= char ?a) (<= char ?z)) (memq char '(?_ ?? ?! ?:)))
996 | (let ((pt (point)))
997 | (save-excursion
998 | (skip-chars-backward "[:alpha:]:_?!")
999 | (and (crystal--at-indentation-p)
1000 | (looking-at (regexp-opt (cons "end" crystal-block-mid-keywords)))
1001 | ;; Outdent after typing a keyword.
1002 | (or (eq (match-end 0) pt)
1003 | ;; Reindent if it wasn't a keyword after all.
1004 | (eq (match-end 0) (1- pt)))))))))
1005 |
1006 | ;; FIXME: Remove this? It's unused here, but some redefinitions of
1007 | ;; `crystal-calculate-indent' in user init files still call it.
1008 | (defun crystal-current-indentation ()
1009 | "Return the indentation level of current line."
1010 | (save-excursion
1011 | (beginning-of-line)
1012 | (back-to-indentation)
1013 | (current-column)))
1014 |
1015 | (defun crystal-indent-line (&optional ignored)
1016 | "Correct the indentation of the current Crystal line."
1017 | (interactive)
1018 | (crystal-indent-to (crystal-calculate-indent)))
1019 |
1020 | (defun crystal-indent-to (column)
1021 | "Indent the current line to COLUMN."
1022 | (when column
1023 | (let (shift top beg)
1024 | (and (< column 0) (error "Invalid nesting"))
1025 | (setq shift (current-column))
1026 | (beginning-of-line)
1027 | (setq beg (point))
1028 | (back-to-indentation)
1029 | (setq top (current-column))
1030 | (skip-chars-backward " \t")
1031 | (if (>= shift top) (setq shift (- shift top))
1032 | (setq shift 0))
1033 | (if (and (bolp)
1034 | (= column top))
1035 | (move-to-column (+ column shift))
1036 | (move-to-column top)
1037 | (delete-region beg (point))
1038 | (beginning-of-line)
1039 | (indent-to column)
1040 | (move-to-column (+ column shift))))))
1041 |
1042 | (defun crystal-special-char-p (&optional pos)
1043 | "Return t if the character before POS is a special character.
1044 | If omitted, POS defaults to the current point.
1045 | Special characters are `?', `$', `:' when preceded by whitespace,
1046 | and `\\' when preceded by `?'."
1047 | (setq pos (or pos (point)))
1048 | (let ((c (char-before pos)) (b (and (< (point-min) pos)
1049 | (char-before (1- pos)))))
1050 | (cond ((or (eq c ??) (eq c ?$)))
1051 | ((and (eq c ?:) (or (not b) (eq (char-syntax b) ? ))))
1052 | ((eq c ?\\) (eq b ??)))))
1053 |
1054 | (defun crystal-singleton-class-p (&optional pos)
1055 | (save-excursion
1056 | (when pos (goto-char pos))
1057 | (forward-word -1)
1058 | (and (or (bolp) (not (eq (char-before (point)) ?_)))
1059 | (looking-at crystal-singleton-class-re))))
1060 |
1061 | (defun crystal-expr-beg (&optional option)
1062 | "Check if point is possibly at the beginning of an expression.
1063 | OPTION specifies the type of the expression.
1064 | Can be one of `heredoc', `modifier', `expr-qstr', `expr-re'. `macro-cmd'"
1065 | (save-excursion
1066 | (store-match-data nil)
1067 | (let ((space (skip-chars-backward " \t"))
1068 | (start (point)))
1069 | (cond
1070 | ((bolp) t)
1071 | ((progn
1072 | (forward-char -1)
1073 | (and (looking-at "\\?")
1074 | (or (eq (char-syntax (char-before (point))) ?w)
1075 | (crystal-special-char-p))))
1076 | nil)
1077 | ((looking-at crystal-operator-re))
1078 | ((eq option 'heredoc)
1079 | (and (< space 0) (not (crystal-singleton-class-p start))))
1080 | ((or (looking-at "[\\[({,;]")
1081 | (and (looking-at "[!?]")
1082 | (or (not (eq option 'modifier))
1083 | (bolp)
1084 | (save-excursion (forward-char -1) (looking-at "\\Sw$"))))
1085 | (and (looking-at crystal-symbol-re)
1086 | (skip-chars-backward crystal-symbol-chars)
1087 | (cond
1088 | ((looking-at (regexp-opt
1089 | (append crystal-block-beg-keywords
1090 | crystal-block-op-keywords
1091 | crystal-block-mid-keywords)
1092 | 'words))
1093 | (goto-char (match-end 0))
1094 | (not (looking-at "\\s_")))
1095 | ((eq option 'expr-qstr)
1096 | (looking-at "[a-zA-Z][a-zA-z0-9_]* +%[^ \t}]"))
1097 | ((eq option 'expr-re)
1098 | (looking-at "[a-zA-Z][a-zA-z0-9_]* +/[^ \t]"))
1099 | ((eq option 'macro-cmd)
1100 | (looking-at "{%"))
1101 | ((eq option 'macro-var)
1102 | (looking-at "{{"))
1103 | (t nil)))))))))
1104 |
1105 | (defun crystal-forward-string (term &optional end no-error expand)
1106 | "Move forward across one balanced pair of string delimiters.
1107 | Skips escaped delimiters. If EXPAND is non-nil, also ignores
1108 | delimiters in interpolated strings.
1109 |
1110 | TERM should be a string containing either a single, self-matching
1111 | delimiter (e.g. \"/\"), or a pair of matching delimiters with the
1112 | close delimiter first (e.g. \"][\").
1113 |
1114 | When non-nil, search is bounded by position END.
1115 |
1116 | Throws an error if a balanced match is not found, unless NO-ERROR
1117 | is non-nil, in which case nil will be returned.
1118 |
1119 | This command assumes the character after point is an opening
1120 | delimiter."
1121 | (let ((n 1) (c (string-to-char term))
1122 | (re (concat "[^\\]\\(\\\\\\\\\\)*\\("
1123 | (if (string= term "^") ;[^] is not a valid regexp
1124 | "\\^"
1125 | (concat "[" term "]"))
1126 | (when expand "\\|\\(#{\\)")
1127 | "\\)")))
1128 | (while (and (re-search-forward re end no-error)
1129 | (if (match-beginning 3)
1130 | (crystal-forward-string "}{" end no-error nil)
1131 | (> (setq n (if (eq (char-before (point)) c)
1132 | (1- n) (1+ n))) 0)))
1133 | (forward-char -1))
1134 | (cond ((zerop n))
1135 | (no-error nil)
1136 | ((error "Unterminated string")))))
1137 |
1138 | (defun crystal-deep-indent-paren-p (c)
1139 | "TODO: document."
1140 | (cond ((listp crystal-deep-indent-paren)
1141 | (let ((deep (assoc c crystal-deep-indent-paren)))
1142 | (cond (deep
1143 | (or (cdr deep) crystal-deep-indent-paren-style))
1144 | ((memq c crystal-deep-indent-paren)
1145 | crystal-deep-indent-paren-style))))
1146 | ((eq c crystal-deep-indent-paren) crystal-deep-indent-paren-style)
1147 | ((eq c ?\( ) crystal-deep-arglist)))
1148 |
1149 | (defun crystal-parse-partial (&optional end in-string nest depth pcol indent)
1150 | "TODO: document throughout function body."
1151 | (or depth (setq depth 0))
1152 | (or indent (setq indent 0))
1153 | (when (re-search-forward crystal-delimiter end 'move)
1154 | (let ((pnt (point)) w re expand)
1155 | (goto-char (match-beginning 0))
1156 | (cond
1157 | ((and (memq (char-before) '(?@ ?$)) (looking-at "\\sw"))
1158 | (goto-char pnt))
1159 | ((looking-at "[\"`]") ;skip string
1160 | (cond
1161 | ((and (not (eobp))
1162 | (crystal-forward-string (buffer-substring (point) (1+ (point)))
1163 | end t t))
1164 | nil)
1165 | (t
1166 | (setq in-string (point))
1167 | (goto-char end))))
1168 | ((looking-at "'")
1169 | (cond
1170 | ((and (not (eobp))
1171 | (re-search-forward "[^\\]\\(\\\\\\\\\\)*'" end t))
1172 | nil)
1173 | (t
1174 | (setq in-string (point))
1175 | (goto-char end))))
1176 | ((looking-at "/=")
1177 | (goto-char pnt))
1178 | ((looking-at "/")
1179 | (cond
1180 | ((and (not (eobp)) (crystal-expr-beg 'expr-re))
1181 | (if (crystal-forward-string "/" end t t)
1182 | nil
1183 | (setq in-string (point))
1184 | (goto-char end)))
1185 | (t
1186 | (goto-char pnt))))
1187 | ((looking-at "%")
1188 | (cond
1189 | ((and (not (eobp))
1190 | (crystal-expr-beg 'expr-qstr)
1191 | (not (looking-at "%="))
1192 | (not (looking-at "%}"))
1193 | (looking-at "%[QqrxWw]?\\([^a-zA-Z0-9 \t\n{]\\)"))
1194 | (goto-char (match-beginning 1))
1195 | (setq expand (not (memq (char-before) '(?q ?w))))
1196 | (setq w (match-string 1))
1197 | (cond
1198 | ((string= w "[") (setq re "]["))
1199 | ((string= w "{") (setq re "}{"))
1200 | ((string= w "(") (setq re ")("))
1201 | ((string= w "<") (setq re "><"))
1202 | ((and expand (string= w "\\"))
1203 | (setq w (concat "\\" w))))
1204 | (unless (cond (re (crystal-forward-string re end t expand))
1205 | (expand (crystal-forward-string w end t t))
1206 | (t (re-search-forward
1207 | (if (string= w "\\")
1208 | "\\\\[^\\]*\\\\"
1209 | (concat "[^\\]\\(\\\\\\\\\\)*" w))
1210 | end t)))
1211 | (setq in-string (point))
1212 | (goto-char end)))
1213 | (t
1214 | (goto-char pnt))))
1215 | ((looking-at "\\?") ;skip ?char
1216 | (cond
1217 | ((and (crystal-expr-beg)
1218 | (looking-at "?\\(\\\\C-\\|\\\\M-\\)*\\\\?."))
1219 | (goto-char (match-end 0)))
1220 | (t
1221 | (goto-char pnt))))
1222 | ((looking-at "\\$") ;skip $char
1223 | (goto-char pnt)
1224 | (forward-char 1))
1225 | ((looking-at "#") ;skip comment
1226 | (forward-line 1)
1227 | (goto-char (point))
1228 | )
1229 | ((looking-at "[\\[{(]")
1230 | (let ((deep (crystal-deep-indent-paren-p (char-after))))
1231 | (if (and deep (or (not (eq (char-after) ?\{)) (crystal-expr-beg)))
1232 | (progn
1233 | (and (eq deep 'space) (looking-at ".\\s +[^# \t\n]")
1234 | (setq pnt (1- (match-end 0))))
1235 | (setq nest (cons (cons (char-after (point)) pnt) nest))
1236 | (setq pcol (cons (cons pnt depth) pcol))
1237 | (setq depth 0))
1238 | (setq nest (cons (cons (char-after (point)) pnt) nest))
1239 | (setq depth (1+ depth))))
1240 | (goto-char pnt)
1241 | )
1242 | ((looking-at "[])}]")
1243 | (if (crystal-deep-indent-paren-p (matching-paren (char-after)))
1244 | (setq depth (cdr (car pcol)) pcol (cdr pcol))
1245 | (setq depth (1- depth)))
1246 | (setq nest (cdr nest))
1247 | (goto-char pnt))
1248 | ((looking-at crystal-block-end-re)
1249 | (if (or (and (not (bolp))
1250 | (progn
1251 | (forward-char -1)
1252 | (setq w (char-after (point)))
1253 | (or (eq ?_ w)
1254 | (eq ?. w))))
1255 | (progn
1256 | (goto-char pnt)
1257 | (setq w (char-after (point)))
1258 | (or (eq ?_ w)
1259 | (eq ?! w)
1260 | (eq ?? w))))
1261 | nil
1262 | (setq nest (cdr nest))
1263 | (setq depth (1- depth)))
1264 | (goto-char pnt))
1265 | ((looking-at "def\\s +[^(\n;]*")
1266 | (if (or (bolp)
1267 | (progn
1268 | (forward-char -1)
1269 | (not (eq ?_ (char-after (point))))))
1270 | (progn
1271 | (setq nest (cons (cons nil pnt) nest))
1272 | (setq depth (1+ depth))))
1273 | (goto-char (match-end 0)))
1274 | ((looking-at (concat "\\_<\\(" crystal-block-beg-re "\\)\\_>"))
1275 | (and
1276 | (save-match-data
1277 | (or (not (looking-at "do\\_>"))
1278 | (save-excursion
1279 | (back-to-indentation)
1280 | (not (looking-at crystal-non-block-do-re)))))
1281 | (or (bolp)
1282 | (progn
1283 | (forward-char -1)
1284 | (setq w (char-after (point)))
1285 | (not (or (eq ?_ w)
1286 | (eq ?. w)))))
1287 | (goto-char pnt)
1288 | (not (eq ?! (char-after (point))))
1289 | (skip-chars-forward " \t")
1290 | (goto-char (match-beginning 0))
1291 | (or (not (looking-at crystal-modifier-re))
1292 | (crystal-expr-beg 'modifier))
1293 | (goto-char pnt)
1294 | (setq nest (cons (cons nil pnt) nest))
1295 | (setq depth (1+ depth)))
1296 | (goto-char pnt))
1297 | ((looking-at ":\\(['\"]\\)")
1298 | (goto-char (match-beginning 1))
1299 | (crystal-forward-string (match-string 1) end t))
1300 | ((looking-at ":\\([-,.+*/%&|^~<>]=?\\|===?\\|<=>\\|![~=]?\\)")
1301 | (goto-char (match-end 0)))
1302 | ((looking-at ":\\([a-zA-Z_][a-zA-Z_0-9]*[!?=]?\\)?")
1303 | (goto-char (match-end 0)))
1304 | ((or (looking-at "\\.\\.\\.?")
1305 | (looking-at "\\.[0-9]+")
1306 | (looking-at "\\.[a-zA-Z_0-9]+")
1307 | (looking-at "\\."))
1308 | (goto-char (match-end 0)))
1309 | ((looking-at "^=begin")
1310 | (if (re-search-forward "^=end" end t)
1311 | (forward-line 1)
1312 | (setq in-string (match-end 0))
1313 | (goto-char end)))
1314 | ((looking-at "<<")
1315 | (cond
1316 | ((and (crystal-expr-beg 'heredoc)
1317 | (looking-at "<<\\(-\\)?\\(\\([\"'`]\\)\\([^\n]+?\\)\\3\\|\\(?:\\sw\\|\\s_\\)+\\)"))
1318 | (setq re (regexp-quote (or (match-string 4) (match-string 2))))
1319 | (if (match-beginning 1) (setq re (concat "\\s *" re)))
1320 | (let* ((id-end (goto-char (match-end 0)))
1321 | (line-end-position (point-at-eol))
1322 | (state (list in-string nest depth pcol indent)))
1323 | ;; parse the rest of the line
1324 | (while (and (> line-end-position (point))
1325 | (setq state (apply 'crystal-parse-partial
1326 | line-end-position state))))
1327 | (setq in-string (car state)
1328 | nest (nth 1 state)
1329 | depth (nth 2 state)
1330 | pcol (nth 3 state)
1331 | indent (nth 4 state))
1332 | ;; skip heredoc section
1333 | (if (re-search-forward (concat "^" re "$") end 'move)
1334 | (forward-line 1)
1335 | (setq in-string id-end)
1336 | (goto-char end))))
1337 | (t
1338 | (goto-char pnt))))
1339 | ((looking-at "^__END__$")
1340 | (goto-char pnt))
1341 | ((and (looking-at crystal-here-doc-beg-re)
1342 | (boundp 'crystal-indent-point))
1343 | (if (re-search-forward (crystal-here-doc-end-match)
1344 | crystal-indent-point t)
1345 | (forward-line 1)
1346 | (setq in-string (match-end 0))
1347 | (goto-char crystal-indent-point)))
1348 | (t
1349 | (error (format "Bad string %s"
1350 | (buffer-substring (point) pnt)
1351 | ))))))
1352 | (list in-string nest depth pcol))
1353 |
1354 | (defun crystal-parse-region (start end)
1355 | "TODO: document."
1356 | (let (state)
1357 | (save-excursion
1358 | (if start
1359 | (goto-char start)
1360 | (crystal-beginning-of-indent))
1361 | (save-restriction
1362 | (narrow-to-region (point) end)
1363 | (while (and (> end (point))
1364 | (setq state (apply 'crystal-parse-partial end state))))))
1365 | (list (nth 0 state) ; in-string
1366 | (car (nth 1 state)) ; nest
1367 | (nth 2 state) ; depth
1368 | (car (car (nth 3 state))) ; pcol
1369 | ;(car (nth 5 state)) ; indent
1370 | )))
1371 |
1372 | (defun crystal-indent-size (pos nest)
1373 | "Return the indentation level in spaces NEST levels deeper than POS."
1374 | (+ pos (* (or nest 1) crystal-indent-level)))
1375 |
1376 | (defun crystal-calculate-indent (&optional parse-start)
1377 | "Return the proper indentation level of the current line."
1378 | ;; TODO: Document body
1379 | (save-excursion
1380 | (beginning-of-line)
1381 | (let ((crystal-indent-point (point))
1382 | (case-fold-search nil)
1383 | state eol begin op-end
1384 | (paren (progn (skip-syntax-forward " ")
1385 | (and (char-after) (matching-paren (char-after)))))
1386 | (indent 0))
1387 | (if parse-start
1388 | (goto-char parse-start)
1389 | (crystal-beginning-of-indent)
1390 | (setq parse-start (point)))
1391 | (back-to-indentation)
1392 | (setq indent (current-column))
1393 | (setq state (crystal-parse-region parse-start crystal-indent-point))
1394 | (cond
1395 | ((nth 0 state) ; within string
1396 | (setq indent nil)) ; do nothing
1397 | ((car (nth 1 state)) ; in paren
1398 | (goto-char (setq begin (cdr (nth 1 state))))
1399 | (let ((deep (crystal-deep-indent-paren-p (car (nth 1 state)))))
1400 | (if deep
1401 | (cond ((and (eq deep t) (eq (car (nth 1 state)) paren))
1402 | (skip-syntax-backward " ")
1403 | (setq indent (1- (current-column))))
1404 | ((let ((s (crystal-parse-region (point) crystal-indent-point)))
1405 | (and (nth 2 s) (> (nth 2 s) 0)
1406 | (or (goto-char (cdr (nth 1 s))) t)))
1407 | (forward-word -1)
1408 | (setq indent (crystal-indent-size (current-column)
1409 | (nth 2 state))))
1410 | (t
1411 | (setq indent (current-column))
1412 | (cond ((eq deep 'space))
1413 | (paren (setq indent (1- indent)))
1414 | (t (setq indent (crystal-indent-size (1- indent) 1))))))
1415 | (if (nth 3 state) (goto-char (nth 3 state))
1416 | (goto-char parse-start) (back-to-indentation))
1417 | (setq indent (crystal-indent-size (current-column) (nth 2 state))))
1418 | (and (eq (car (nth 1 state)) paren)
1419 | (crystal-deep-indent-paren-p (matching-paren paren))
1420 | (search-backward (char-to-string paren))
1421 | (setq indent (current-column)))))
1422 | ((and (nth 2 state) (> (nth 2 state) 0)) ; in nest
1423 | (if (null (cdr (nth 1 state)))
1424 | (error "Invalid nesting"))
1425 | (goto-char (cdr (nth 1 state)))
1426 | (forward-word -1) ; skip back a keyword
1427 | (setq begin (point))
1428 | (cond
1429 | ((looking-at "do\\>[^_]") ; iter block is a special case
1430 | (if (nth 3 state) (goto-char (nth 3 state))
1431 | (goto-char parse-start) (back-to-indentation))
1432 | (setq indent (crystal-indent-size (current-column) (nth 2 state))))
1433 | (t
1434 | (setq indent (+ (current-column) crystal-indent-level)))))
1435 |
1436 | ((and (nth 2 state) (< (nth 2 state) 0)) ; in negative nest
1437 | (setq indent (crystal-indent-size (current-column) (nth 2 state)))))
1438 | (when indent
1439 | (goto-char crystal-indent-point)
1440 | (end-of-line)
1441 | (setq eol (point))
1442 | (beginning-of-line)
1443 | (cond
1444 | ((and (not (crystal-deep-indent-paren-p paren))
1445 | (re-search-forward crystal-negative eol t))
1446 | (and (not (eq ?_ (char-after (match-end 0))))
1447 | (setq indent (- indent crystal-indent-level))))
1448 | ((and
1449 | (save-excursion
1450 | (beginning-of-line)
1451 | (not (bobp)))
1452 | (or (crystal-deep-indent-paren-p t)
1453 | (null (car (nth 1 state)))))
1454 | ;; goto beginning of non-empty no-comment line
1455 | (let (end done)
1456 | (while (not done)
1457 | (skip-chars-backward " \t\n")
1458 | (setq end (point))
1459 | (beginning-of-line)
1460 | (if (re-search-forward "^\\s *#" end t)
1461 | (beginning-of-line)
1462 | (setq done t))))
1463 | (end-of-line)
1464 | ;; skip the comment at the end
1465 | (skip-chars-backward " \t")
1466 | (let (end (pos (point)))
1467 | (beginning-of-line)
1468 | (while (and (re-search-forward "#" pos t)
1469 | (setq end (1- (point)))
1470 | (or (crystal-special-char-p end)
1471 | (and (setq state (crystal-parse-region
1472 | parse-start end))
1473 | (nth 0 state))))
1474 | (setq end nil))
1475 | (goto-char (or end pos))
1476 | (skip-chars-backward " \t")
1477 | (setq begin (if (and end (nth 0 state)) pos (cdr (nth 1 state))))
1478 | (setq state (crystal-parse-region parse-start (point))))
1479 | (or (bobp) (forward-char -1))
1480 | (and
1481 | (or (and (looking-at crystal-symbol-re)
1482 | (skip-chars-backward crystal-symbol-chars)
1483 | (looking-at (concat "\\<\\(" crystal-block-hanging-re
1484 | "\\)\\>"))
1485 | (not (eq (point) (nth 3 state)))
1486 | (save-excursion
1487 | (goto-char (match-end 0))
1488 | (not (looking-at "[a-z_]"))))
1489 | (and (looking-at crystal-operator-re)
1490 | (not (crystal-special-char-p))
1491 | (save-excursion
1492 | (forward-char -1)
1493 | (or (not (looking-at crystal-operator-re))
1494 | (not (eq (char-before) ?:))))
1495 | ;; Operator at the end of line.
1496 | (let ((c (char-after (point))))
1497 | (and
1498 | ;; (or (null begin)
1499 | ;; (save-excursion
1500 | ;; (goto-char begin)
1501 | ;; (skip-chars-forward " \t")
1502 | ;; (not (or (eolp) (looking-at "#")
1503 | ;; (and (eq (car (nth 1 state)) ?{)
1504 | ;; (looking-at "|"))))))
1505 | ;; Not a regexp or percent literal.
1506 | (null (nth 0 (crystal-parse-region (or begin parse-start)
1507 | (point))))
1508 | (or (not (eq ?| (char-after (point))))
1509 | (save-excursion
1510 | (or (eolp) (forward-char -1))
1511 | (cond
1512 | ((search-backward "|" nil t)
1513 | (skip-chars-backward " \t\n")
1514 | (and (not (eolp))
1515 | (progn
1516 | (forward-char -1)
1517 | (not (looking-at "{")))
1518 | (progn
1519 | (forward-word -1)
1520 | (not (looking-at "do\\>[^_]")))))
1521 | (t t))))
1522 | (not (eq ?, c))
1523 | (setq op-end t)))))
1524 | (setq indent
1525 | (cond
1526 | ((and
1527 | (null op-end)
1528 | (not (looking-at (concat "\\<\\(" crystal-block-hanging-re
1529 | "\\)\\>")))
1530 | (eq (crystal-deep-indent-paren-p t) 'space)
1531 | (not (bobp)))
1532 | (widen)
1533 | (goto-char (or begin parse-start))
1534 | (skip-syntax-forward " ")
1535 | (current-column))
1536 | ((car (nth 1 state)) indent)
1537 | (t
1538 | (+ indent crystal-indent-level))))))))
1539 | (goto-char crystal-indent-point)
1540 | (beginning-of-line)
1541 | (skip-syntax-forward " ")
1542 | (if (looking-at "\\.[^.]")
1543 | (+ indent crystal-indent-level)
1544 | indent))))
1545 |
1546 | (defun crystal-beginning-of-defun (&optional arg)
1547 | "Move backward to the beginning of the current defun.
1548 | With ARG, move backward multiple defuns. Negative ARG means
1549 | move forward."
1550 | (interactive "p")
1551 | (let (case-fold-search)
1552 | (and (re-search-backward (concat "^\\s *" crystal-defun-beg-re "\\_>")
1553 | nil t (or arg 1))
1554 | (beginning-of-line))))
1555 |
1556 | (defun crystal-end-of-defun ()
1557 | "Move point to the end of the current defun.
1558 | The defun begins at or after the point. This function is called
1559 | by `end-of-defun'."
1560 | (interactive "p")
1561 | (crystal-forward-sexp)
1562 | (let (case-fold-search)
1563 | (when (looking-back (concat "^\\s *" crystal-block-end-re))
1564 | (forward-line 1))))
1565 |
1566 | (defun crystal-beginning-of-indent ()
1567 | "Backtrack to a line which can be used as a reference for
1568 | calculating indentation on the lines after it."
1569 | (while (and (re-search-backward crystal-indent-beg-re nil 'move)
1570 | (if (crystal-in-ppss-context-p 'anything)
1571 | t
1572 | ;; We can stop, then.
1573 | (beginning-of-line)))))
1574 |
1575 |
1576 | (defun crystal-move-to-block (n)
1577 | "Move to the beginning (N < 0) or the end (N > 0) of the
1578 | current block, a sibling block, or an outer block. Do that (abs N) times."
1579 | (back-to-indentation)
1580 | (let ((signum (if (> n 0) 1 -1))
1581 | (backward (< n 0))
1582 | (depth (or (nth 2 (crystal-parse-region (point) (line-end-position))) 0))
1583 | case-fold-search
1584 | down done)
1585 | (when (looking-at crystal-block-mid-re)
1586 | (setq depth (+ depth signum)))
1587 | (when (< (* depth signum) 0)
1588 | ;; Moving end -> end or beginning -> beginning.
1589 | (setq depth 0))
1590 | (dotimes (_ (abs n))
1591 | (setq done nil)
1592 | (setq down (save-excursion
1593 | (back-to-indentation)
1594 | ;; There is a block start or block end keyword on this
1595 | ;; line, don't need to look for another block.
1596 | (and (re-search-forward
1597 | (if backward crystal-block-end-re
1598 | (concat "\\_<\\(" crystal-block-beg-re "\\)\\_>"))
1599 | (line-end-position) t)
1600 | (not (nth 8 (syntax-ppss))))))
1601 | (while (and (not done) (not (if backward (bobp) (eobp))))
1602 | (forward-line signum)
1603 | (cond
1604 | ;; Skip empty and commented out lines.
1605 | ((looking-at "^\\s *$"))
1606 | ((looking-at "^\\s *#"))
1607 | ;; Skip block comments;
1608 | ((and (not backward) (looking-at "^=begin\\>"))
1609 | (re-search-forward "^=end\\>"))
1610 | ((and backward (looking-at "^=end\\>"))
1611 | (re-search-backward "^=begin\\>"))
1612 | ;; Jump over a multiline literal.
1613 | ((crystal-in-ppss-context-p 'string)
1614 | (goto-char (nth 8 (syntax-ppss)))
1615 | (unless backward
1616 | (forward-sexp)
1617 | (when (bolp) (forward-char -1)))) ; After a heredoc.
1618 | (t
1619 | (let ((state (crystal-parse-region (point) (line-end-position))))
1620 | (unless (car state) ; Line ends with unfinished string.
1621 | (setq depth (+ (nth 2 state) depth))))
1622 | (cond
1623 | ;; Increased depth, we found a block.
1624 | ((> (* signum depth) 0)
1625 | (setq down t))
1626 | ;; We're at the same depth as when we started, and we've
1627 | ;; encountered a block before. Stop.
1628 | ((and down (zerop depth))
1629 | (setq done t))
1630 | ;; Lower depth, means outer block, can stop now.
1631 | ((< (* signum depth) 0)
1632 | (setq done t)))))))
1633 | (back-to-indentation)))
1634 |
1635 | (defun crystal-beginning-of-block (&optional arg)
1636 | "Move backward to the beginning of the current block.
1637 | With ARG, move up multiple blocks."
1638 | (interactive "p")
1639 | (crystal-move-to-block (- (or arg 1))))
1640 |
1641 | (defun crystal-end-of-block (&optional arg)
1642 | "Move forward to the end of the current block.
1643 | With ARG, move out of multiple blocks."
1644 | (interactive "p")
1645 | (crystal-move-to-block (or arg 1)))
1646 |
1647 | (defun crystal-forward-sexp (&optional arg)
1648 | "Move forward across one balanced expression (sexp).
1649 | With ARG, do it many times. Negative ARG means move backward."
1650 | ;; TODO: Document body
1651 | (interactive "p")
1652 | (cond
1653 | (crystal-use-smie (forward-sexp arg))
1654 | ((and (numberp arg) (< arg 0)) (crystal-backward-sexp (- arg)))
1655 | (t
1656 | (let ((i (or arg 1)))
1657 | (condition-case nil
1658 | (while (> i 0)
1659 | (skip-syntax-forward " ")
1660 | (if (looking-at ",\\s *") (goto-char (match-end 0)))
1661 | (cond ((looking-at "\\?\\(\\\\[CM]-\\)*\\\\?\\S ")
1662 | (goto-char (match-end 0)))
1663 | ((progn
1664 | (skip-chars-forward ",.:;|&^~=!?\\+\\-\\*")
1665 | (looking-at "\\s("))
1666 | (goto-char (scan-sexps (point) 1)))
1667 | ((and (looking-at (concat "\\<\\(" crystal-block-beg-re
1668 | "\\)\\>"))
1669 | (not (eq (char-before (point)) ?.))
1670 | (not (eq (char-before (point)) ?:)))
1671 | (crystal-end-of-block)
1672 | (forward-word 1))
1673 | ((looking-at "\\(\\$\\|@@?\\)?\\sw")
1674 | (while (progn
1675 | (while (progn (forward-word 1) (looking-at "_")))
1676 | (cond ((looking-at "::") (forward-char 2) t)
1677 | ((> (skip-chars-forward ".") 0))
1678 | ((looking-at "\\?\\|!\\(=[~=>]\\|[^~=]\\)")
1679 | (forward-char 1) nil)))))
1680 | ((let (state expr)
1681 | (while
1682 | (progn
1683 | (setq expr (or expr (crystal-expr-beg)
1684 | (looking-at "%\\sw?\\Sw\\|[\"'`/]")))
1685 | (nth 1 (setq state (apply #'crystal-parse-partial
1686 | nil state))))
1687 | (setq expr t)
1688 | (skip-chars-forward "<"))
1689 | (not expr))))
1690 | (setq i (1- i)))
1691 | ((error) (forward-word 1)))
1692 | i))))
1693 |
1694 | (defun crystal-backward-sexp (&optional arg)
1695 | "Move backward across one balanced expression (sexp).
1696 | With ARG, do it many times. Negative ARG means move forward."
1697 | ;; TODO: Document body
1698 | (interactive "p")
1699 | (cond
1700 | (crystal-use-smie (backward-sexp arg))
1701 | ((and (numberp arg) (< arg 0)) (crystal-forward-sexp (- arg)))
1702 | (t
1703 | (let ((i (or arg 1)))
1704 | (condition-case nil
1705 | (while (> i 0)
1706 | (skip-chars-backward " \t\n,.:;|&^~=!?\\+\\-\\*")
1707 | (forward-char -1)
1708 | (cond ((looking-at "\\s)")
1709 | (goto-char (scan-sexps (1+ (point)) -1))
1710 | (pcase (char-before)
1711 | (`?% (forward-char -1))
1712 | ((or `?q `?Q `?w `?W `?r `?x)
1713 | (if (eq (char-before (1- (point))) ?%)
1714 | (forward-char -2))))
1715 | nil)
1716 | ((looking-at "\\s\"\\|\\\\\\S_")
1717 | (let ((c (char-to-string (char-before (match-end 0)))))
1718 | (while (and (search-backward c)
1719 | (eq (logand (skip-chars-backward "\\") 1)
1720 | 1))))
1721 | nil)
1722 | ((looking-at "\\s.\\|\\s\\")
1723 | (if (crystal-special-char-p) (forward-char -1)))
1724 | ((looking-at "\\s(") nil)
1725 | (t
1726 | (forward-char 1)
1727 | (while (progn (forward-word -1)
1728 | (pcase (char-before)
1729 | (`?_ t)
1730 | (`?. (forward-char -1) t)
1731 | ((or `?$ `?@)
1732 | (forward-char -1)
1733 | (and (eq (char-before) (char-after))
1734 | (forward-char -1)))
1735 | (`?:
1736 | (forward-char -1)
1737 | (eq (char-before) :)))))
1738 | (if (looking-at crystal-block-end-re)
1739 | (crystal-beginning-of-block))
1740 | nil))
1741 | (setq i (1- i)))
1742 | ((error)))
1743 | i))))
1744 |
1745 | (defun crystal-indent-exp (&optional ignored)
1746 | "Indent each line in the balanced expression following the point."
1747 | (interactive "*P")
1748 | (let ((here (point-marker)) start top column (nest t))
1749 | (set-marker-insertion-type here t)
1750 | (unwind-protect
1751 | (progn
1752 | (beginning-of-line)
1753 | (setq start (point) top (current-indentation))
1754 | (while (and (not (eobp))
1755 | (progn
1756 | (setq column (crystal-calculate-indent start))
1757 | (cond ((> column top)
1758 | (setq nest t))
1759 | ((and (= column top) nest)
1760 | (setq nest nil) t))))
1761 | (crystal-indent-to column)
1762 | (beginning-of-line 2)))
1763 | (goto-char here)
1764 | (set-marker here nil))))
1765 |
1766 | (defun crystal-add-log-current-method ()
1767 | "Return the current method name as a string.
1768 | This string includes all namespaces.
1769 |
1770 | For example:
1771 |
1772 | #exit
1773 | String#gsub
1774 | Net::HTTP#active?
1775 | File.open
1776 |
1777 | See `add-log-current-defun-function'."
1778 | (condition-case nil
1779 | (save-excursion
1780 | (let* ((indent 0) mname mlist
1781 | (start (point))
1782 | (make-definition-re
1783 | (lambda (re)
1784 | (concat "^[ \t]*" re "[ \t]+"
1785 | "\\("
1786 | ;; \\. and :: for class methods
1787 | "\\([A-Za-z_]" crystal-symbol-re "*\\|\\.\\|::" "\\)"
1788 | "+\\)")))
1789 | (definition-re (funcall make-definition-re crystal-defun-beg-re))
1790 | (module-re (funcall make-definition-re "\\(class\\|module\\)")))
1791 | ;; Get the current method definition (or class/module).
1792 | (when (re-search-backward definition-re nil t)
1793 | (goto-char (match-beginning 1))
1794 | (if (not (string-equal "def" (match-string 1)))
1795 | (setq mlist (list (match-string 2)))
1796 | ;; We're inside the method. For classes and modules,
1797 | ;; this check is skipped for performance.
1798 | (when (crystal-block-contains-point start)
1799 | (setq mname (match-string 2))))
1800 | (setq indent (current-column))
1801 | (beginning-of-line))
1802 | ;; Walk up the class/module nesting.
1803 | (while (and (> indent 0)
1804 | (re-search-backward module-re nil t))
1805 | (goto-char (match-beginning 1))
1806 | (when (< (current-column) indent)
1807 | (setq mlist (cons (match-string 2) mlist))
1808 | (setq indent (current-column))
1809 | (beginning-of-line)))
1810 | ;; Process the method name.
1811 | (when mname
1812 | (let ((mn (split-string mname "\\.\\|::")))
1813 | (if (cdr mn)
1814 | (progn
1815 | (unless (string-equal "self" (car mn)) ; def self.foo
1816 | ;; def C.foo
1817 | (let ((ml (nreverse mlist)))
1818 | ;; If the method name references one of the
1819 | ;; containing modules, drop the more nested ones.
1820 | (while ml
1821 | (if (string-equal (car ml) (car mn))
1822 | (setq mlist (nreverse (cdr ml)) ml nil))
1823 | (or (setq ml (cdr ml)) (nreverse mlist))))
1824 | (if mlist
1825 | (setcdr (last mlist) (butlast mn))
1826 | (setq mlist (butlast mn))))
1827 | (setq mname (concat "." (car (last mn)))))
1828 | ;; See if the method is in singleton class context.
1829 | (let ((in-singleton-class
1830 | (when (re-search-forward crystal-singleton-class-re start t)
1831 | (goto-char (match-beginning 0))
1832 | ;; FIXME: Optimize it out, too?
1833 | ;; This can be slow in a large file, but
1834 | ;; unlike class/module declaration
1835 | ;; indentations, method definitions can be
1836 | ;; intermixed with these, and may or may not
1837 | ;; be additionally indented after visibility
1838 | ;; keywords.
1839 | (crystal-block-contains-point start))))
1840 | (setq mname (concat
1841 | (if in-singleton-class "." "#")
1842 | mname))))))
1843 | ;; Generate the string.
1844 | (if (consp mlist)
1845 | (setq mlist (mapconcat (function identity) mlist "::")))
1846 | (if mname
1847 | (if mlist (concat mlist mname) mname)
1848 | mlist)))))
1849 |
1850 | (defun crystal-block-contains-point (pt)
1851 | (save-excursion
1852 | (save-match-data
1853 | (crystal-forward-sexp)
1854 | (> (point) pt))))
1855 |
1856 | (defun crystal-brace-to-do-end (orig end)
1857 | (let (beg-marker end-marker)
1858 | (goto-char end)
1859 | (when (eq (char-before) ?\})
1860 | (delete-char -1)
1861 | (when (save-excursion
1862 | (skip-chars-backward " \t")
1863 | (not (bolp)))
1864 | (insert "\n"))
1865 | (insert "end")
1866 | (setq end-marker (point-marker))
1867 | (when (and (not (eobp)) (eq (char-syntax (char-after)) ?w))
1868 | (insert " "))
1869 | (goto-char orig)
1870 | (delete-char 1)
1871 | (when (eq (char-syntax (char-before)) ?w)
1872 | (insert " "))
1873 | (insert "do")
1874 | (setq beg-marker (point-marker))
1875 | (when (looking-at "\\(\\s \\)*|")
1876 | (unless (match-beginning 1)
1877 | (insert " "))
1878 | (goto-char (1+ (match-end 0)))
1879 | (search-forward "|"))
1880 | (unless (looking-at "\\s *$")
1881 | (insert "\n"))
1882 | (indent-region beg-marker end-marker)
1883 | (goto-char beg-marker)
1884 | t)))
1885 |
1886 | (defun crystal-do-end-to-brace (orig end)
1887 | (let (beg-marker end-marker beg-pos end-pos)
1888 | (goto-char (- end 3))
1889 | (when (looking-at crystal-block-end-re)
1890 | (delete-char 3)
1891 | (setq end-marker (point-marker))
1892 | (insert "}")
1893 | (goto-char orig)
1894 | (delete-char 2)
1895 | ;; Maybe this should be customizable, let's see if anyone asks.
1896 | (insert "{ ")
1897 | (setq beg-marker (point-marker))
1898 | (when (looking-at "\\s +|")
1899 | (delete-char (- (match-end 0) (match-beginning 0) 1))
1900 | (forward-char)
1901 | (re-search-forward "|" (line-end-position) t))
1902 | (save-excursion
1903 | (skip-chars-forward " \t\n\r")
1904 | (setq beg-pos (point))
1905 | (goto-char end-marker)
1906 | (skip-chars-backward " \t\n\r")
1907 | (setq end-pos (point)))
1908 | (when (or
1909 | (< end-pos beg-pos)
1910 | (and (= (line-number-at-pos beg-pos) (line-number-at-pos end-pos))
1911 | (< (+ (current-column) (- end-pos beg-pos) 2) fill-column)))
1912 | (just-one-space -1)
1913 | (goto-char end-marker)
1914 | (just-one-space -1))
1915 | (goto-char beg-marker)
1916 | t)))
1917 |
1918 | (defun crystal-toggle-block ()
1919 | "Toggle block type from do-end to braces or back.
1920 | The block must begin on the current line or above it and end after the point.
1921 | If the result is do-end block, it will always be multiline."
1922 | (interactive)
1923 | (let ((start (point)) beg end)
1924 | (end-of-line)
1925 | (unless
1926 | (if (and (re-search-backward "\\(?:[^#]\\)\\({\\)\\|\\(\\_\\)")
1927 | (progn
1928 | (goto-char (or (match-beginning 1) (match-beginning 2)))
1929 | (setq beg (point))
1930 | (save-match-data (crystal-forward-sexp))
1931 | (setq end (point))
1932 | (> end start)))
1933 | (if (match-beginning 1)
1934 | (crystal-brace-to-do-end beg end)
1935 | (crystal-do-end-to-brace beg end)))
1936 | (goto-char start))))
1937 |
1938 | (defun crystal--string-region ()
1939 | "Return region for string at point."
1940 | (let ((state (syntax-ppss)))
1941 | (when (memq (nth 3 state) '(?' ?\"))
1942 | (save-excursion
1943 | (goto-char (nth 8 state))
1944 | (forward-sexp)
1945 | (list (nth 8 state) (point))))))
1946 |
1947 | (defun crystal-string-at-point-p ()
1948 | "Check if cursor is at a string or not."
1949 | (crystal--string-region))
1950 |
1951 | (defun crystal--inverse-string-quote (string-quote)
1952 | "Get the inverse string quoting for STRING-QUOTE."
1953 | (if (equal string-quote "\"") "'" "\""))
1954 |
1955 | (defun crystal-toggle-string-quotes ()
1956 | "Toggle string literal quoting between single and double."
1957 | (interactive)
1958 | (when (crystal-string-at-point-p)
1959 | (let* ((region (crystal--string-region))
1960 | (min (nth 0 region))
1961 | (max (nth 1 region))
1962 | (string-quote (crystal--inverse-string-quote (buffer-substring-no-properties min (1+ min))))
1963 | (content
1964 | (buffer-substring-no-properties (1+ min) (1- max))))
1965 | (setq content
1966 | (if (equal string-quote "\"")
1967 | (replace-regexp-in-string "\\\\\"" "\"" (replace-regexp-in-string "\\([^\\\\]\\)'" "\\1\\\\'" content))
1968 | (replace-regexp-in-string "\\\\\'" "'" (replace-regexp-in-string "\\([^\\\\]\\)\"" "\\1\\\\\"" content))))
1969 | (let ((orig-point (point)))
1970 | (delete-region min max)
1971 | (insert
1972 | (format "%s%s%s" string-quote content string-quote))
1973 | (goto-char orig-point)))))
1974 |
1975 | (eval-and-compile
1976 | (defconst crystal-percent-literal-beg-re
1977 | "\\(%\\)[qQrswWxIi]?\\([!\"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|~]\\)"
1978 | "Regexp to match the beginning of percent literal.")
1979 |
1980 | (defconst crystal-syntax-methods-before-regexp
1981 | '("gsub" "gsub!" "sub" "sub!" "scan" "split" "split!" "index" "match"
1982 | "assert_match" "Given" "Then" "When")
1983 | "Methods that can take regexp as the first argument.
1984 | It will be properly highlighted even when the call omits parens.")
1985 |
1986 | (defvar crystal-syntax-before-regexp-re
1987 | (concat
1988 | ;; Special tokens that can't be followed by a division operator.
1989 | "\\(^\\|[[=(,~;<>]"
1990 | ;; Distinguish ternary operator tokens.
1991 | ;; FIXME: They don't really have to be separated with spaces.
1992 | "\\|[?:] "
1993 | ;; Control flow keywords and operators following bol or whitespace.
1994 | "\\|\\(?:^\\|\\s \\)"
1995 | (regexp-opt '("if" "elsif" "unless" "while" "until" "when" "and"
1996 | "or" "not" "&&" "||"))
1997 | ;; Method name from the list.
1998 | "\\|\\_<"
1999 | (regexp-opt crystal-syntax-methods-before-regexp)
2000 | "\\)\\s *")
2001 | "Regexp to match text that can be followed by a regular expression."))
2002 |
2003 | (defun crystal-syntax-propertize-function (start end)
2004 | "Syntactic keywords for Crystal mode. See `syntax-propertize-function'."
2005 | (let (case-fold-search)
2006 | (goto-char start)
2007 | (remove-text-properties start end '(crystal-expansion-match-data))
2008 | (crystal-syntax-propertize-heredoc end)
2009 | (crystal-syntax-enclosing-percent-literal end)
2010 | (funcall
2011 | (syntax-propertize-rules
2012 | ;; $' $" $` .... are variables.
2013 | ;; ?' ?" ?` are character literals (one-char strings in 1.9+).
2014 | ("\\([?$]\\)[#\"'`]"
2015 | (1 (if (save-excursion
2016 | (nth 3 (syntax-ppss (match-beginning 0))))
2017 | ;; Within a string, skip.
2018 | (goto-char (match-end 1))
2019 | (string-to-syntax "\\"))))
2020 | ;; Part of symbol when at the end of a method name.
2021 | ("[!?]"
2022 | (0 (unless (save-excursion
2023 | (or (nth 8 (syntax-ppss (match-beginning 0)))
2024 | (eq (char-before) ?:)
2025 | (let (parse-sexp-lookup-properties)
2026 | (zerop (skip-syntax-backward "w_")))
2027 | (memq (preceding-char) '(?@ ?$))))
2028 | (string-to-syntax "_"))))
2029 | ;; Regular expressions. Start with matching unescaped slash.
2030 | ("\\(?:\\=\\|[^\\]\\)\\(?:\\\\\\\\\\)*\\(/\\)"
2031 | (1 (let ((state (save-excursion (syntax-ppss (match-beginning 1)))))
2032 | (when (or
2033 | ;; Beginning of a regexp.
2034 | (and (null (nth 8 state))
2035 | (save-excursion
2036 | (forward-char -1)
2037 | (looking-back crystal-syntax-before-regexp-re
2038 | (point-at-bol))))
2039 | ;; End of regexp. We don't match the whole
2040 | ;; regexp at once because it can have
2041 | ;; string interpolation inside, or span
2042 | ;; several lines.
2043 | (eq ?/ (nth 3 state)))
2044 | (string-to-syntax "\"/")))))
2045 | ;; Expression expansions in strings. We're handling them
2046 | ;; here, so that the regexp rule never matches inside them.
2047 | (crystal-expression-expansion-re
2048 | (0 (ignore (crystal-syntax-propertize-expansion))))
2049 | ("^=en\\(d\\)\\_>" (1 "!"))
2050 | ("^\\(=\\)begin\\_>" (1 "!"))
2051 | ;; Handle here documents.
2052 | ((concat crystal-here-doc-beg-re ".*\\(\n\\)")
2053 | (7 (unless (or (nth 8 (save-excursion
2054 | (syntax-ppss (match-beginning 0))))
2055 | (crystal-singleton-class-p (match-beginning 0)))
2056 | (put-text-property (match-beginning 7) (match-end 7)
2057 | 'syntax-table (string-to-syntax "\""))
2058 | (crystal-syntax-propertize-heredoc end))))
2059 | ;; Handle percent literals: %w(), %q{}, etc.
2060 | ((concat "\\(?:^\\|[[ \t\n<+(,=]\\)" crystal-percent-literal-beg-re)
2061 | (1 (prog1 "|" (crystal-syntax-propertize-percent-literal end)))))
2062 | (point) end)))
2063 |
2064 | (defun crystal-syntax-propertize-heredoc (limit)
2065 | (let ((ppss (syntax-ppss))
2066 | (res '()))
2067 | (when (eq ?\n (nth 3 ppss))
2068 | (save-excursion
2069 | (goto-char (nth 8 ppss))
2070 | (beginning-of-line)
2071 | (while (re-search-forward crystal-here-doc-beg-re
2072 | (line-end-position) t)
2073 | (unless (crystal-singleton-class-p (match-beginning 0))
2074 | (push (concat (crystal-here-doc-end-match) "\n") res))))
2075 | (save-excursion
2076 | ;; With multiple openers on the same line, we don't know in which
2077 | ;; part `start' is, so we have to go back to the beginning.
2078 | (when (cdr res)
2079 | (goto-char (nth 8 ppss))
2080 | (setq res (nreverse res)))
2081 | (while (and res (re-search-forward (pop res) limit 'move))
2082 | (if (null res)
2083 | (put-text-property (1- (point)) (point)
2084 | 'syntax-table (string-to-syntax "\""))))
2085 | ;; End up at bol following the heredoc openers.
2086 | ;; Propertize expression expansions from this point forward.
2087 | ))))
2088 |
2089 | (defun crystal-syntax-enclosing-percent-literal (limit)
2090 | (let ((state (syntax-ppss))
2091 | (start (point)))
2092 | ;; When already inside percent literal, re-propertize it.
2093 | (when (eq t (nth 3 state))
2094 | (goto-char (nth 8 state))
2095 | (when (looking-at crystal-percent-literal-beg-re)
2096 | (crystal-syntax-propertize-percent-literal limit))
2097 | (when (< (point) start) (goto-char start)))))
2098 |
2099 | (defun crystal-syntax-propertize-percent-literal (limit)
2100 | (goto-char (match-beginning 2))
2101 | ;; Not inside a simple string or comment.
2102 | (when (eq t (nth 3 (syntax-ppss)))
2103 | (let* ((op (char-after))
2104 | (ops (char-to-string op))
2105 | (cl (or (cdr (aref (syntax-table) op))
2106 | (cdr (assoc op '((?< . ?>))))))
2107 | parse-sexp-lookup-properties)
2108 | (save-excursion
2109 | (condition-case nil
2110 | (progn
2111 | (if cl ; Paired delimiters.
2112 | ;; Delimiter pairs of the same kind can be nested
2113 | ;; inside the literal, as long as they are balanced.
2114 | ;; Create syntax table that ignores other characters.
2115 | (with-syntax-table (make-char-table 'syntax-table nil)
2116 | (modify-syntax-entry op (concat "(" (char-to-string cl)))
2117 | (modify-syntax-entry cl (concat ")" ops))
2118 | (modify-syntax-entry ?\\ "\\")
2119 | (save-restriction
2120 | (narrow-to-region (point) limit)
2121 | (forward-list))) ; skip to the paired character
2122 | ;; Single character delimiter.
2123 | (re-search-forward (concat "[^\\]\\(?:\\\\\\\\\\)*"
2124 | (regexp-quote ops)) limit nil))
2125 | ;; Found the closing delimiter.
2126 | (put-text-property (1- (point)) (point) 'syntax-table
2127 | (string-to-syntax "|")))
2128 | ;; Unclosed literal, do nothing.
2129 | ((scan-error search-failed)))))))
2130 |
2131 | (defun crystal-syntax-propertize-expansion ()
2132 | ;; Save the match data to a text property, for font-locking later.
2133 | ;; Set the syntax of all double quotes and backticks to punctuation.
2134 | (let* ((beg (match-beginning 2))
2135 | (end (match-end 2))
2136 | (state (and beg (save-excursion (syntax-ppss beg)))))
2137 | (when (crystal-syntax-expansion-allowed-p state)
2138 | (put-text-property beg (1+ beg) 'crystal-expansion-match-data
2139 | (match-data))
2140 | (goto-char beg)
2141 | (while (re-search-forward "[\"`]" end 'move)
2142 | (put-text-property (match-beginning 0) (match-end 0)
2143 | 'syntax-table (string-to-syntax "."))))))
2144 |
2145 | (defun crystal-syntax-expansion-allowed-p (parse-state)
2146 | "Return non-nil if expression expansion is allowed."
2147 | (let ((term (nth 3 parse-state)))
2148 | (cond
2149 | ((memq term '(?\" ?` ?\n ?/)))
2150 | ((eq term t)
2151 | (save-match-data
2152 | (save-excursion
2153 | (goto-char (nth 8 parse-state))
2154 | (looking-at "%\\(?:[QWrxI]\\|\\W\\)")))))))
2155 |
2156 | (defun crystal-syntax-propertize-expansions (start end)
2157 | (save-excursion
2158 | (goto-char start)
2159 | (while (re-search-forward crystal-expression-expansion-re end 'move)
2160 | (crystal-syntax-propertize-expansion))))
2161 |
2162 | (defun crystal-in-ppss-context-p (context &optional ppss)
2163 | (let ((ppss (or ppss (syntax-ppss (point)))))
2164 | (if (cond
2165 | ((eq context 'anything)
2166 | (or (nth 3 ppss)
2167 | (nth 4 ppss)))
2168 | ((eq context 'string)
2169 | (nth 3 ppss))
2170 | ((eq context 'heredoc)
2171 | (eq ?\n (nth 3 ppss)))
2172 | ((eq context 'non-heredoc)
2173 | (and (crystal-in-ppss-context-p 'anything)
2174 | (not (crystal-in-ppss-context-p 'heredoc))))
2175 | ((eq context 'comment)
2176 | (nth 4 ppss))
2177 | (t
2178 | (error (concat
2179 | "Internal error on `crystal-in-ppss-context-p': "
2180 | "context name `" (symbol-name context) "' is unknown"))))
2181 | t)))
2182 |
2183 | (defvar crystal-font-lock-syntax-table
2184 | (let ((tbl (copy-syntax-table crystal-mode-syntax-table)))
2185 | (modify-syntax-entry ?_ "w" tbl)
2186 | tbl)
2187 | "The syntax table to use for fontifying Crystal mode buffers.
2188 | See `font-lock-syntax-table'.")
2189 |
2190 | (defconst crystal-font-lock-keyword-beg-re "\\(?:^\\|[^.@$]\\|\\.\\.\\)")
2191 |
2192 | (defconst crystal-font-lock-keywords
2193 | `(;; Functions.
2194 | ("^\\s *def\\s +\\(?:[^( \t\n.{}]*\\.\\)?\\([^( \t\n{}]+\\)"
2195 | 1 font-lock-function-name-face)
2196 | ;; Keywords.
2197 | (,(concat
2198 | crystal-font-lock-keyword-beg-re
2199 | (regexp-opt
2200 | '("alias"
2201 | "and"
2202 | "begin"
2203 | "break"
2204 | "case"
2205 | "class"
2206 | "def"
2207 | "defined?"
2208 | "do"
2209 | "elsif"
2210 | "else"
2211 | "fail"
2212 | "ensure"
2213 | "enum"
2214 | "for"
2215 | "end"
2216 | "if"
2217 | "in"
2218 | "lib"
2219 | "macro"
2220 | "module"
2221 | "next"
2222 | "not"
2223 | "of"
2224 | "or"
2225 | "redo"
2226 | "rescue"
2227 | "retry"
2228 | "return"
2229 | "then"
2230 | "struct"
2231 | "super"
2232 | "unless"
2233 | "undef"
2234 | "until"
2235 | "when"
2236 | "while"
2237 | "yield"
2238 | "lib"
2239 | "struct"
2240 | "enum"
2241 | "fun"
2242 | "type")
2243 | 'symbols))
2244 | (1 font-lock-keyword-face))
2245 | ;; Core methods that have required arguments.
2246 | (,(concat
2247 | crystal-font-lock-keyword-beg-re
2248 | (regexp-opt
2249 | '( ;; built-in methods on Kernel
2250 | "at_exit"
2251 | "autoload"
2252 | "autoload?"
2253 | "catch"
2254 | "eval"
2255 | "exec"
2256 | "fork"
2257 | "format"
2258 | "load"
2259 | "loop"
2260 | "open"
2261 | "p"
2262 | "pp"
2263 | "print"
2264 | "printf"
2265 | "putc"
2266 | "puts"
2267 | "require"
2268 | "spawn"
2269 | "sprintf"
2270 | "syscall"
2271 | "system"
2272 | "trap"
2273 | "warn"
2274 | ;; keyword-like private methods on Module
2275 | "alias_method"
2276 | "attr"
2277 | "property"
2278 | "getter"
2279 | "setter"
2280 | "define_method"
2281 | "extend"
2282 | "include"
2283 | "module_function"
2284 | "prepend"
2285 | "private_class_method"
2286 | "private_constant"
2287 | "public_class_method"
2288 | "public_constant"
2289 | "refine"
2290 | "using"
2291 | "record")
2292 | 'symbols))
2293 | (1 (unless (looking-at " *\\(?:[]|,.)}=]\\|$\\)")
2294 | font-lock-builtin-face)))
2295 | ;; Kernel methods that have no required arguments.
2296 | (,(concat
2297 | crystal-font-lock-keyword-beg-re
2298 | (regexp-opt
2299 | '("__callee__"
2300 | "__dir__"
2301 | "__method__"
2302 | "abort"
2303 | "at_exit"
2304 | "binding"
2305 | "block_given?"
2306 | "caller"
2307 | "exit"
2308 | "exit!"
2309 | "fail"
2310 | "abstract"
2311 | "private"
2312 | "protected"
2313 | "public"
2314 | "raise"
2315 | "rand"
2316 | "readline"
2317 | "readlines"
2318 | "sleep"
2319 | "srand"
2320 | "throw")
2321 | 'symbols))
2322 | (1 font-lock-builtin-face))
2323 | ;; Here-doc beginnings.
2324 | (,crystal-here-doc-beg-re
2325 | (0 (unless (crystal-singleton-class-p (match-beginning 0))
2326 | 'font-lock-string-face)))
2327 | ;; Perl-ish keywords.
2328 | "\\_<\\(?:BEGIN\\|END\\)\\_>\\|^__END__$"
2329 | ;; Variables.
2330 | (,(concat crystal-font-lock-keyword-beg-re
2331 | "\\_<\\(nil\\|self\\|true\\|false\\)\\_>")
2332 | 1 font-lock-variable-name-face)
2333 | ;; Keywords that evaluate to certain values.
2334 | ("\\_<__\\(?:LINE\\|ENCODING\\|FILE\\)__\\_>"
2335 | (0 font-lock-builtin-face))
2336 | ;; Symbols.
2337 | ("\\(^\\|[^:]\\)\\(:\\([-+~]@?\\|[/%&|^`]\\|\\*\\*?\\|<\\(<\\|=>?\\)?\\|>[>=]?\\|===?\\|=~\\|![~=]?\\|\\[\\]=?\\|@?\\(\\w\\|_\\)+\\([!?=]\\|\\b_*\\)\\|#{[^}\n\\\\]*\\(\\\\.[^}\n\\\\]*\\)*}\\)\\)"
2338 | 2 font-lock-constant-face)
2339 | ;; Special globals.
2340 | (,(concat "\\$\\(?:[:\"!@;,/\\._><\\$?~=*&`'+0-9]\\|-[0adFiIlpvw]\\|"
2341 | (regexp-opt '("LOAD_PATH" "LOADED_FEATURES" "PROGRAM_NAME"
2342 | "ERROR_INFO" "ERROR_POSITION"
2343 | "FS" "FIELD_SEPARATOR"
2344 | "OFS" "OUTPUT_FIELD_SEPARATOR"
2345 | "RS" "INPUT_RECORD_SEPARATOR"
2346 | "ORS" "OUTPUT_RECORD_SEPARATOR"
2347 | "NR" "INPUT_LINE_NUMBER"
2348 | "LAST_READ_LINE" "DEFAULT_OUTPUT" "DEFAULT_INPUT"
2349 | "PID" "PROCESS_ID" "CHILD_STATUS"
2350 | "LAST_MATCH_INFO" "IGNORECASE"
2351 | "ARGV" "MATCH" "PREMATCH" "POSTMATCH"
2352 | "LAST_PAREN_MATCH" "stdin" "stdout" "stderr"
2353 | "DEBUG" "FILENAME" "VERBOSE" "SAFE" "CLASSPATH"))
2354 | "\\_>\\)")
2355 | 0 font-lock-builtin-face)
2356 | ("\\(\\$\\|@\\|@@\\)\\(\\w\\|_\\)+"
2357 | 0 font-lock-variable-name-face)
2358 | ;; Attributes
2359 | (, crystal-attr-re
2360 | (1 font-lock-preprocessor-face)
2361 | (3 font-lock-preprocessor-face))
2362 | ;; Constants.
2363 | ("\\(?:\\_<\\|::\\|\\s+:\\s+\\)\\([A-Z]+\\(\\w\\|_\\)*\\)"
2364 | 1 (unless (eq ?\( (char-after)) font-lock-type-face))
2365 | ("\\(^\\s *\\|[\[\{\(,]\\s *\\|\\sw\\s +\\)\\(\\(\\sw\\|_\\)+\\):[^:]"
2366 | (2 font-lock-constant-face))
2367 | ;; Conversion methods on Kernel.
2368 | (,(concat crystal-font-lock-keyword-beg-re
2369 | (regexp-opt '("Array" "Complex" "Float" "Hash"
2370 | "Integer" "Rational" "String" "Tuple" "NamedTuple") 'symbols))
2371 | (1 font-lock-builtin-face))
2372 | ;; Expression expansion.
2373 | (crystal-match-expression-expansion
2374 | 2 font-lock-variable-name-face t)
2375 | ;; Negation char.
2376 | ("\\(?:^\\|[^[:alnum:]_]\\)\\(!+\\)[^=~]"
2377 | 1 font-lock-negation-char-face)
2378 | ;; Character literals.
2379 | ;; FIXME: Support longer escape sequences.
2380 | ("\\_<\\?\\\\?\\S " 0 font-lock-string-face)
2381 | ;; macro delimiters
2382 | ("\\({%\\|{{\\|}}\\|%}\\)" 1 font-lock-preprocessor-face)
2383 | ;; Regexp options.
2384 | ("\\(?:\\s|\\|/\\)\\([imxo]+\\)"
2385 | 1 (when (save-excursion
2386 | (let ((state (syntax-ppss (match-beginning 0))))
2387 | (and (nth 3 state)
2388 | (or (eq (char-after) ?/)
2389 | (progn
2390 | (goto-char (nth 8 state))
2391 | (looking-at "%r"))))))
2392 | font-lock-preprocessor-face))
2393 | )
2394 | "Additional expressions to highlight in Crystal mode.")
2395 |
2396 | (defun crystal-match-expression-expansion (limit)
2397 | (let* ((prop 'crystal-expansion-match-data)
2398 | (pos (next-single-char-property-change (point) prop nil limit))
2399 | value)
2400 | (when (and pos (> pos (point)))
2401 | (goto-char pos)
2402 | (or (and (setq value (get-text-property pos prop))
2403 | (progn (set-match-data value) t))
2404 | (crystal-match-expression-expansion limit)))))
2405 |
2406 | ;;;; Crystal tooling functions
2407 | (defun crystal-exec (args output-buffer-name)
2408 | "Run crystal with the supplied args and put the result in output-buffer-name"
2409 | (apply 'call-process
2410 | (append (list crystal-executable nil output-buffer-name t)
2411 | args)))
2412 |
2413 | (defun crystal-format ()
2414 | "Format the contents of the current buffer without persisting the result."
2415 | (interactive)
2416 | (let ((oldbuf (current-buffer))
2417 | (name (make-temp-file "crystal-format")))
2418 | (with-temp-file name (insert-buffer-substring oldbuf))
2419 | (crystal-exec (list "tool" "format" name) "*messages*")
2420 | (insert-file-contents name nil nil nil t)))
2421 |
2422 | ;;;###autoload
2423 | (define-derived-mode crystal-mode prog-mode "Crystal"
2424 | "Major mode for editing Crystal code.
2425 |
2426 | \\{crystal-mode-map}"
2427 | (crystal-mode-variables)
2428 |
2429 | (setq-local imenu-create-index-function 'crystal-imenu-create-index)
2430 | (setq-local add-log-current-defun-function 'crystal-add-log-current-method)
2431 | (setq-local beginning-of-defun-function 'crystal-beginning-of-defun)
2432 | (setq-local end-of-defun-function 'crystal-end-of-defun)
2433 |
2434 | (add-hook 'after-save-hook 'crystal-mode-set-encoding nil 'local)
2435 | (add-hook 'electric-indent-functions 'crystal--electric-indent-p nil 'local)
2436 |
2437 | (setq-local font-lock-defaults '((crystal-font-lock-keywords) nil nil))
2438 | (setq-local font-lock-keywords crystal-font-lock-keywords)
2439 | (setq-local font-lock-syntax-table crystal-font-lock-syntax-table)
2440 |
2441 | (setq-local syntax-propertize-function #'crystal-syntax-propertize-function))
2442 |
2443 | ;;; Invoke crystal-mode when appropriate
2444 |
2445 | ;;;###autoload
2446 | (add-to-list 'auto-mode-alist
2447 | (cons (purecopy (concat "\\(?:\\."
2448 | "cr"
2449 | "\\)\\'")) 'crystal-mode))
2450 |
2451 | ;;;###autoload
2452 | (dolist (name (list "crystal"))
2453 | (add-to-list 'interpreter-mode-alist (cons (purecopy name) 'crystal-mode)))
2454 |
2455 | (provide 'crystal-mode)
2456 |
2457 | ;;; crystal-mode.el ends here
2458 |
--------------------------------------------------------------------------------
/flycheck-crystal.el:
--------------------------------------------------------------------------------
1 | ;;; flycheck-crystal.el --- Add support for Crystal to Flycheck
2 |
3 | ;; Version: 0.1
4 | ;; Package-Requires: ((flycheck "30"))
5 | ;; Keywords: tools crystal
6 |
7 | ;;; Commentary:
8 |
9 | ;; This package provides error-checking support for the Crystal language to the
10 | ;; Flycheck package. To use it, have Flycheck installed, then add the following
11 | ;; to your init file:
12 | ;;
13 | ;; (require 'flycheck-crystal)
14 | ;; (add-hook 'crystal-mode-hook 'flycheck-mode)
15 |
16 | ;;; Code:
17 |
18 | (require 'flycheck)
19 |
20 | (flycheck-define-checker crystal-build
21 | "A Crystal syntax checker using crystal build"
22 | :command ("crystal"
23 | "build"
24 | "--no-codegen"
25 | "--no-color"
26 | source-inplace)
27 | :error-patterns
28 | ((error line-start "Error in " (file-name) ":" line ":" (message) line-end)
29 | (error line-start "Syntax error in " (file-name) ":" line ":" (message) line-end)
30 | (warning line-start "Warning in " (file-name) ":" line ":" (message) line-end)
31 | )
32 | :modes crystal-mode
33 | )
34 |
35 | (add-to-list 'flycheck-checkers 'crystal-build)
36 |
37 | (provide 'flycheck-crystal)
38 |
39 | ;;; flycheck-crystal.el ends here
40 |
--------------------------------------------------------------------------------