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