├── .elpaignore ├── .gitignore ├── .travis.yml ├── LICENSE ├── Makefile ├── README ├── README.md ├── backend ├── gforth.el ├── lbforth.el ├── pforth.el ├── spforth.el ├── swiftforth.el ├── swiftforth.fth └── vfxforth.el ├── build.el ├── forth-block-mode.el ├── forth-interaction-mode.el ├── forth-mode.el ├── forth-mode.texi ├── forth-parse.el ├── forth-smie.el ├── forth-spec.el ├── forth-syntax.el └── test ├── block1.fth ├── block2.fth ├── noblock.fth └── tests.el /.elpaignore: -------------------------------------------------------------------------------- 1 | autoloads.el 2 | build.el 3 | forth-mode-autoloads.el 4 | forth-mode-pkg.el 5 | Makefile 6 | .travis.yml -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | *.elc 3 | *.info 4 | autoloads.el 5 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: emacs-lisp 2 | sudo: required 3 | env: 4 | - EMACS=emacs24 5 | - EMACS=emacs25 6 | install: 7 | - sudo add-apt-repository -y ppa:ubuntu-elisp 8 | - sudo apt-get update -y 9 | - sudo apt-get install emacs24 emacs25 10 | - sudo apt-get install gforth || true 11 | script: make EMACS=$EMACS 12 | notifications: 13 | email: lars@nocrew.org 14 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | EMACS = emacs 2 | EMACS_LOAD = $(EMACS) -Q --batch --load 3 | FORTH = gforth-0.7.3 4 | 5 | SRC = $(wildcard *.el) $(wildcard backend/*.el) 6 | 7 | all: forth-mode.elc 8 | 9 | forth-mode.elc: $(SRC) 10 | FORTH=$(FORTH) $(EMACS_LOAD) build.el 11 | 12 | doc: forth-mode.info 13 | 14 | %.info: %.texi 15 | makeinfo $< 16 | 17 | check: forth-mode.elc 18 | FORTH=$(FORTH) $(EMACS) -Q --batch -L . -l test/tests.el \ 19 | -f ert-run-tests-batch-and-exit 20 | 21 | clean: 22 | rm -f autoloads.el *.elc backend/*.elc 23 | -------------------------------------------------------------------------------- /README: -------------------------------------------------------------------------------- 1 | Programming language mode for Forth. 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Programming language mode for Forth. 2 | 3 | [![Build Status](https://travis-ci.org/larsbrinkhoff/forth-mode.svg)](https://travis-ci.org/larsbrinkhoff/forth-mode) 4 | [![MELPA](https://melpa.org/packages/forth-mode-badge.svg)](https://melpa.org/#/forth-mode) 5 | 6 | Features in progress: 7 | 8 | - Recognises definitions and moves by balanced expressions. 9 | - Interact with a Forth session: enter commands, load files, evalutate 10 | expressions. 11 | - Display stack comment when moving the cursor over a word. 12 | - Edit block files. 13 | - Tab completion. 14 | - Query a running Forth about words, search order, etc. 15 | 16 | ### Installation 17 | 18 | MELPA: 19 | 20 | M-x package-install forth-mode 21 | 22 | Manual: 23 | 24 | git clone http://github.com/larsbrinkhoff/forth-mode DIR 25 | 26 | # Add to .emacs 27 | (add-to-list 'load-path "DIR") 28 | (require 'forth-mode) 29 | (require 'forth-block-mode) 30 | (require 'forth-interaction-mode) 31 | 32 | ### Usage 33 | 34 | To enable Forth major mode, type `M-x forth-mode`. The file 35 | extensions `.f`, `.fs`, `.fth`, and `.4th` are recognised 36 | automatically. 37 | 38 | To start an interactive Forth session, type `M-x run-forth`. 39 | 40 | Key bindings: 41 | 42 | - `C-M-a`, `C-M-e` - beginning / end of colon definition. 43 | - `C-M-f`, `C-M-b` - forward / backward expression (not very useful yet). 44 | - `C-M-h` - mark colon definition. 45 | - `C-c C-l` - load file. 46 | - `C-c C-r` - evaluate region. 47 | - `C-c C-k` - kill interactive Forth. 48 | - `M-TAB`, `C-M-i` - complete-symbol. 49 | -------------------------------------------------------------------------------- /backend/gforth.el: -------------------------------------------------------------------------------- 1 | (require 'forth-interaction-mode) 2 | 3 | (defun forth-gforth-init (backend-type process) 4 | (when (eq backend-type 'gforth) 5 | (forth-interaction-send "' drop is Attr!"))) 6 | 7 | (add-hook 'forth-interaction-init-backend-hook #'forth-gforth-init) 8 | 9 | (provide 'gforth) 10 | -------------------------------------------------------------------------------- /backend/lbforth.el: -------------------------------------------------------------------------------- 1 | (provide 'lbforth) 2 | -------------------------------------------------------------------------------- /backend/pforth.el: -------------------------------------------------------------------------------- 1 | (provide 'pforth) 2 | -------------------------------------------------------------------------------- /backend/spforth.el: -------------------------------------------------------------------------------- 1 | (provide 'spforth) 2 | -------------------------------------------------------------------------------- /backend/swiftforth.el: -------------------------------------------------------------------------------- 1 | (require 'forth-interaction-mode) 2 | 3 | (defun forth-swiftforth-init (backend-type process) 4 | (when (eq backend-type 'swiftforth) 5 | (set-process-coding-system process 'raw-text-dos 'raw-text-dos) 6 | (forth-interaction-send (concat "include " forth-backend-dir 7 | "/swiftforth.fth")))) 8 | 9 | (add-hook 'forth-interaction-init-backend-hook #'forth-swiftforth-init) 10 | 11 | (provide 'swiftforth) 12 | -------------------------------------------------------------------------------- /backend/swiftforth.fth: -------------------------------------------------------------------------------- 1 | : 2null 0 0 ; 2 | : big-size 200 100 ; 3 | 4 | \ Similar to ACCEPT but doesn't display the received characters. 5 | \ Reads one line (whithout trailing newline). 6 | : accept-no-echo ( addr u1 -- u2 ) 7 | tuck 8 | begin ( u1 addr u ) 9 | dup 0= if 2drop exit then 10 | key 11 | case 12 | \ remove \n and \r 13 | 10 of nip - exit endof 14 | 13 of endof \ FIXME: should detect \r\n sequences properly 15 | 2 pick c! 16 | 1 /string 17 | 0 18 | endcase 19 | again ; 20 | 21 | create winning-personality 22 | 4 cells , 19 , 0 , 0 , 23 | ' noop , ' noop , ' noop , 24 | 'emit @ , 25 | 'type @ , 26 | '?type @ , 27 | 'cr @ , 28 | ' noop , \ page 29 | ' drop , \ attribute 30 | 'key @ , 31 | 'key? @ , 32 | 'ekey @ , 33 | 'ekey? @ , 34 | 'akey @ , 35 | 'pushtext @ , 36 | ' 2drop , \ at-xy 37 | ' 2null , \ get-xy 38 | ' big-size , \ get-size 39 | ' accept-no-echo , \ accept 40 | 41 | :noname cr ." ok " ; is prompt 42 | : clearstack ( ... -- ) begin depth 0> while drop repeat ; 43 | : repl 44 | winning-personality open-personality /interpreter 45 | \ Could just call QUIT but running our own REPL is cooler. 46 | begin 47 | state @ 0= if prompt then 48 | \ NOTE: refill prints a space (don't ask me why) 49 | refill 0= abort" refill failed" 50 | source ['] evaluate catch 51 | ?dup if cr ." Error: " .catch cr 52 | clearstack 53 | then 54 | again ; 55 | 56 | repl 57 | -------------------------------------------------------------------------------- /backend/vfxforth.el: -------------------------------------------------------------------------------- 1 | (provide 'vfxforth) 2 | -------------------------------------------------------------------------------- /build.el: -------------------------------------------------------------------------------- 1 | (princ (emacs-version)) 2 | (setq forth-executable (getenv "FORTH")) 3 | 4 | (require 'autoload) 5 | (let ((generated-autoload-file (concat default-directory "autoloads.el"))) 6 | (update-directory-autoloads "." "./backend")) 7 | (load-file "autoloads.el") 8 | (add-to-list 'load-path default-directory) 9 | 10 | (if (locate-library "ert") 11 | (require 'ert) 12 | (defmacro ert-deftest (name args &rest body) 13 | `(progn (message "Testing: %s" ',name) ,@body)) 14 | (defun ert-run-tests-batch-and-exit (&optional x) 15 | (kill-emacs 0)) 16 | (defun should (arg) 17 | (unless arg 18 | (kill-emacs 1))) 19 | (defun should-not (arg) 20 | (should (not arg)))) 21 | 22 | (ert-deftest compile-package () 23 | "Compile package." 24 | (should-not (string-match "failed" (byte-recompile-directory "." 0)))) 25 | 26 | (load-file "test/tests.el") 27 | 28 | ;;; Ensure compile-package is run first. 29 | (ert-run-tests-batch-and-exit '(or compile-package t)) 30 | -------------------------------------------------------------------------------- /forth-block-mode.el: -------------------------------------------------------------------------------- 1 | (require 'forth-mode) 2 | 3 | (defvar forth-block-with-newlines) 4 | 5 | (defun forth-line (n) 6 | (goto-char (point-min)) 7 | (forward-line (1- n))) 8 | 9 | (defun forth-unblockify () 10 | (let ((after-change-functions nil)) 11 | (save-excursion 12 | (forth-beginning) 13 | (while (ignore-errors (forward-char 64) t) 14 | (insert ?\n)) 15 | (let ((delete-trailing-lines t)) 16 | (delete-trailing-whitespace)) 17 | (set-buffer-modified-p nil)))) 18 | 19 | (defun forth-pad-line () 20 | (end-of-line) 21 | (while (cl-plusp (logand (1- (point)) 63)) 22 | (insert " ")) 23 | (ignore-errors (delete-char 1) 24 | (if (looking-at "\n") 25 | (insert " ")) 26 | t)) 27 | 28 | (defun forth-blockify () 29 | (let ((after-change-functions nil)) 30 | (save-excursion 31 | (forth-beginning) 32 | (while (forth-pad-line)) 33 | (while (plusp (logand (point) 1023)) 34 | (insert " ")) 35 | (insert " ")))) 36 | 37 | (defun forth-block-annotations ()) 38 | 39 | ;;; format-alist 40 | '(forth/blocks "Forth blocks" nil forth-unblockify forth-block-annotations 41 | nil forth-block-mode nil) 42 | 43 | (defvar forth-change-newlines) 44 | 45 | (defun forth-count-newlines (start end) 46 | (let ((n 0)) 47 | (save-excursion 48 | (goto-char start) 49 | (while (< (point) end) 50 | (if (looking-at "\n") 51 | (cl-incf n)) 52 | (forward-char 1))) 53 | (message "N = %d" n) 54 | n)) 55 | 56 | (defun forth-before-change (start end) 57 | (setq forth-change-newlines (forth-count-newlines start end))) 58 | 59 | (defun forth-after-change (start end z) 60 | (message "Change: %s %s %s" start end z) 61 | (setq forth-change-newlines (- (forth-count-newlines start end) 62 | forth-change-newlines)) 63 | (message "New lines: %d" forth-change-newlines) 64 | (cond ((plusp forth-change-newlines) 65 | (let ((n (logand (+ (line-number-at-pos) 15) -16))) 66 | (save-excursion 67 | (forth-line (1+ n)) 68 | (delete-region (line-beginning-position) (line-end-position)) 69 | (delete-char 1)))) 70 | ((cl-minusp forth-change-newlines) 71 | (let ((n (logand (+ (line-number-at-pos) 15) -16))) 72 | (save-excursion 73 | (forth-line n) 74 | (insert "\n"))))) 75 | (save-excursion 76 | (end-of-line) 77 | (while (> (- (point) (line-beginning-position)) 64) 78 | (delete-char -1)))) 79 | 80 | ;;;###autoload 81 | (define-minor-mode forth-block-mode 82 | "Minor mode for Forth code in blocks." 83 | :lighter " block" 84 | (make-local-variable 'forth-block-with-newlines) 85 | (setq forth-block-with-newlines (forth-block-with-newlines-p)) 86 | (setq require-final-newline nil) 87 | (forth-unblockify) 88 | (add-hook 'before-save-hook 'forth-blockify nil t) 89 | (add-hook 'after-save-hook 'forth-unblockify nil t) 90 | (add-to-list (make-local-variable 'before-change-functions) 91 | #'forth-before-change) 92 | (add-to-list (make-local-variable 'after-change-functions) 93 | #'forth-after-change)) 94 | 95 | (provide 'forth-block-mode) 96 | -------------------------------------------------------------------------------- /forth-interaction-mode.el: -------------------------------------------------------------------------------- 1 | (eval-when-compile (byte-compile-disable-warning 'cl-functions)) 2 | 3 | (require 'comint) 4 | (require 'forth-mode) 5 | 6 | (defvar forth-interaction-buffer nil) 7 | (defvar forth-interaction-source-buffer nil) 8 | (defvar forth-interaction-callback nil) 9 | (defvar forth-words-cache nil) 10 | (defvar forth-implementation nil) 11 | (defvar forth-banner "") 12 | (defvar forth-backend-dir 13 | (concat (file-name-directory load-file-name) "backend")) 14 | 15 | (defvar forth-implementation-matches 16 | '(("Gforth" . gforth) 17 | ("SP-FORTH" . spforth) 18 | ("PForth" . pforth) 19 | ("VFX Forth" . vfxforth) 20 | ("SwiftForth" . swiftforth) 21 | ("lbForth" . lbforth))) 22 | 23 | (defvar forth-interaction-mode-map 24 | (let ((map (copy-keymap forth-mode-map))) 25 | (set-keymap-parent map comint-mode-map) 26 | (define-key map (kbd "C-c C-f") 'forth-restart) 27 | (define-key map (kbd "C-c C-z") 'forth-switch-to-source-buffer) 28 | map) 29 | "Keymap for Forth interaction.") 30 | 31 | (define-derived-mode forth-interaction-mode comint-mode "Forth Interaction" 32 | "Major mode for interacting with Forth." 33 | :syntax-table forth-mode-syntax-table 34 | (use-local-map forth-interaction-mode-map)) 35 | 36 | (defvar forth-interaction-init-backend-hook '()) 37 | 38 | (defun forth-interaction-preoutput-filter (text) 39 | (unless forth-implementation 40 | (setq forth-banner (concat forth-banner text)) 41 | (dolist (x forth-implementation-matches) 42 | (when (string-match (car x) forth-banner) 43 | (setq forth-implementation (cdr x)) 44 | (let ((load-path (cons forth-backend-dir load-path))) 45 | (require forth-implementation)) 46 | (run-hook-with-args 'forth-interaction-init-backend-hook 47 | forth-implementation 48 | (get-buffer-process (current-buffer)))))) 49 | (if forth-interaction-callback 50 | (funcall forth-interaction-callback text) 51 | text)) 52 | 53 | ;;;###autoload 54 | (defun forth-kill (&optional buffer) 55 | (interactive) 56 | (setq buffer (or buffer forth-interaction-buffer)) 57 | (when (get-buffer-process buffer) 58 | (set-process-query-on-exit-flag (get-buffer-process buffer) nil)) 59 | (kill-buffer buffer) 60 | (setq forth-interaction-buffer nil)) 61 | 62 | (defun forth-interaction-sentinel (proc arg) 63 | (message "Forth: %s" arg) 64 | ;;FIXME: Can't do this because it calls process-mark, which 65 | ;; errors out in killed processes. Still, would be nice to see 66 | ;; something in the *forth* buffer. 67 | ;;(comint-output-filter proc (format "\nForth: %s\n" arg)) 68 | ) 69 | 70 | (defvar forth-executable nil) 71 | 72 | (defvar run-forth-hooks) 73 | 74 | ;;;###autoload 75 | (defun run-forth () 76 | "Start an interactive forth session." 77 | (interactive) 78 | (setq forth-implementation nil) 79 | (setq forth-banner "") 80 | (unless forth-executable 81 | (setq forth-executable 82 | (read-string "Forth executable: "))) 83 | (let ((buffer (get-buffer-create "*forth*"))) 84 | (pop-to-buffer buffer) 85 | (unless (comint-check-proc buffer) 86 | (run-hooks 'run-forth-hooks) 87 | (make-comint-in-buffer "forth" buffer forth-executable) 88 | (set-process-window-size (get-buffer-process buffer) 89 | (window-height) (window-width)) 90 | (set-process-sentinel (get-buffer-process buffer) 91 | 'forth-interaction-sentinel) 92 | (forth-interaction-mode) 93 | (add-hook 'comint-preoutput-filter-functions 94 | 'forth-interaction-preoutput-filter nil t) 95 | (setq forth-interaction-buffer buffer)))) 96 | 97 | ;;;###autoload 98 | (defun forth-restart () 99 | (interactive) 100 | (forth-kill) 101 | (run-forth)) 102 | 103 | (defun forth-ensure () 104 | (unless (buffer-live-p forth-interaction-buffer) 105 | (run-forth)) 106 | (get-buffer-process forth-interaction-buffer)) 107 | 108 | (defun forth-scrub (string &optional keep-ok) 109 | "Remove terminal escape sequences from STRING." 110 | (let ((n 0)) 111 | (while (setq n (string-match "[?[0-9;]*[a-z]" string n)) 112 | (setq string (replace-match "" t t string)))) 113 | (setq string (replace-regexp-in-string "\\`[[:space:]\n]*" "" string)) 114 | (setq string (replace-regexp-in-string "[[:space:]\n]*\\'" "" string)) 115 | (if keep-ok 116 | string 117 | (setq string (replace-regexp-in-string "ok\\'" "" string)) 118 | (setq string (replace-regexp-in-string "[[:space:]\n]*\\'" "" string)))) 119 | 120 | (defun forth-interaction-send-raw-result (&rest strings) 121 | (let* ((proc (forth-ensure)) 122 | (forth-result nil) 123 | (forth-interaction-callback (lambda (x) 124 | (setq forth-result (concat forth-result x)) 125 | "")) 126 | (end-time (+ (float-time) .4))) 127 | (dolist (s strings) 128 | (comint-send-string proc s)) 129 | (comint-send-string proc "\n") 130 | (while (< (float-time) end-time) 131 | (accept-process-output proc 0.1)) 132 | (setq forth-words-cache nil) 133 | forth-result)) 134 | 135 | ;;;###autoload 136 | (defun forth-interaction-send (&rest strings) 137 | (forth-scrub (apply #'forth-interaction-send-raw-result strings))) 138 | 139 | ;;;###autoload 140 | (defun forth-words () 141 | (when forth-interaction-buffer 142 | (or forth-words-cache 143 | (setq forth-words-cache 144 | (split-string (forth-interaction-send "words")))))) 145 | 146 | ;;;###autoload 147 | (defun forth-eval (string) 148 | (interactive "sForth expression: ") 149 | (message "%s" (forth-interaction-send string))) 150 | 151 | ;;;###autoload 152 | (defun forth-eval-region (start end) 153 | (interactive "r") 154 | (forth-eval (buffer-substring start end))) 155 | 156 | ;;;###autoload 157 | (defun forth-eval-defun () 158 | (interactive) 159 | (save-excursion 160 | (mark-defun) 161 | (forth-eval-region (point) (mark)))) 162 | 163 | ;;;###autoload 164 | (defun forth-load-file (file) 165 | (interactive (list (buffer-file-name (current-buffer)))) 166 | (save-some-buffers) 167 | (let ((result (forth-interaction-send-raw-result (format "s\" %s\" included" file)))) 168 | (setq result (forth-scrub result t)) 169 | (if (< (cl-count ?\n result) 2) 170 | (message "%s" result) 171 | (pop-to-buffer forth-interaction-buffer)) 172 | (comint-output-filter (get-buffer-process forth-interaction-buffer) 173 | (concat result "\n")))) 174 | 175 | ;;;###autoload 176 | (defun forth-see (word) 177 | (interactive (list (forth-word-at-point))) 178 | (let ((buffer (get-buffer-create "*see*"))) 179 | (pop-to-buffer buffer) 180 | (let ((inhibit-read-only t)) 181 | (erase-buffer) 182 | (insert (forth-interaction-send "see " word))) 183 | (special-mode))) 184 | 185 | (defun forth-switch-to-buffer (buffer) 186 | ;; If buffer is visible, switch to that window. Otherwise, display 187 | ;; buffer in current window. 188 | (select-window (display-buffer buffer 189 | '((display-buffer-reuse-window 190 | display-buffer-same-window))))) 191 | 192 | ;;;###autoload 193 | (defun forth-switch-to-output-buffer () 194 | (interactive) 195 | (if forth-interaction-buffer 196 | (progn 197 | (setq forth-interaction-source-buffer (current-buffer)) 198 | (forth-switch-to-buffer forth-interaction-buffer)) 199 | (message "Forth not started."))) 200 | 201 | ;;;###autoload 202 | (defun forth-switch-to-source-buffer () 203 | (interactive) 204 | (if forth-interaction-source-buffer 205 | (forth-switch-to-buffer forth-interaction-source-buffer) 206 | (message "Don't know which buffer to switch to."))) 207 | 208 | ;;;###autoload 209 | (defun forth-eval-last-expression () 210 | (interactive) 211 | (save-excursion 212 | (backward-sexp) 213 | (let ((start (point))) 214 | (forward-sexp) 215 | (forth-eval-region start (point))))) 216 | 217 | ;;;###autoload 218 | (defun forth-eval-last-expression-display-output () 219 | (interactive) 220 | (if forth-interaction-buffer 221 | (save-excursion 222 | (backward-sexp) 223 | (let ((start (point))) 224 | (forward-sexp) 225 | (let ((string (buffer-substring start (point)))) 226 | (forth-switch-to-output-buffer) 227 | (insert (forth-interaction-send string))))) 228 | (message "Forth not started."))) 229 | 230 | (provide 'forth-interaction-mode) 231 | -------------------------------------------------------------------------------- /forth-mode.el: -------------------------------------------------------------------------------- 1 | ;;; forth-mode.el --- Programming language mode for Forth 2 | ;;; Copyright 2014 Lars Brinkhoff 3 | 4 | ;; Author: Lars Brinkhoff 5 | ;; Keywords: languages forth 6 | ;; URL: http://github.com/larsbrinkhoff/forth-mode 7 | ;; Package-Requires: ((cl-lib "0.2")) 8 | ;; Version: 0.2 9 | 10 | ;;; Commentary: 11 | ;; Programming language mode for Forth 12 | 13 | ;;; Code: 14 | 15 | (eval-when-compile (byte-compile-disable-warning 'cl-functions)) 16 | (require 'cl-lib) 17 | (require 'forth-syntax) 18 | (require 'forth-smie) 19 | (require 'forth-spec) 20 | 21 | (defvar forth-mode-map 22 | (let ((map (make-sparse-keymap))) 23 | (define-key map (kbd "C-c C-r") 'forth-eval-region) 24 | (define-key map (kbd "C-c C-l") 'forth-load-file) 25 | (define-key map (kbd "C-c C-s") 'forth-see) 26 | (define-key map (kbd "C-M-x") 'forth-eval-defun) 27 | (define-key map (kbd "C-c C-k") 'forth-kill) 28 | (define-key map (kbd "C-c C-f") 'forth-restart) 29 | (define-key map (kbd "C-c C-e") 'forth-eval-last-expression) 30 | (define-key map (kbd "C-x M-e") 'forth-eval-last-expression-display-output) 31 | (define-key map (kbd "C-c C-z") 'forth-switch-to-output-buffer) 32 | (define-key map (kbd "C-c :") 'forth-eval) 33 | (define-key map (kbd "C-c C-d 1") 'forth-spec-lookup-1994) 34 | (define-key map (kbd "C-c C-d 2") 'forth-spec-lookup-2012) 35 | ;; (define-key map (kbd "C-c C-c") 'eval-buffer) 36 | ;; (define-key map (kbd "C-x `") #'forth-next-error) 37 | ;; (define-key map (kbd "M-n") #'forth-next-note) 38 | ;; (define-key map (kbd "M-p") #'forth-previous-note) 39 | ;; (define-key map (kbd "M-.") #'forth-find-definition) 40 | map)) 41 | 42 | (defvar forth-mode-syntax-table 43 | (let ((table (make-syntax-table))) 44 | (modify-syntax-entry ?\\ "<" table) 45 | (modify-syntax-entry ?\n ">" table) 46 | (modify-syntax-entry ?\( "<1b" table) 47 | (modify-syntax-entry ?\) ">4b" table) 48 | (modify-syntax-entry ?* "_23n" table) 49 | (modify-syntax-entry ?\{ "_" table) 50 | (modify-syntax-entry ?\} "_" table) 51 | (modify-syntax-entry ?\: "(;" table) 52 | (modify-syntax-entry ?\; "):" table) 53 | (modify-syntax-entry ?\[ "_" table) 54 | (modify-syntax-entry ?\] "_" table) 55 | (modify-syntax-entry ?\? "_" table) 56 | (modify-syntax-entry ?! "_" table) 57 | (modify-syntax-entry ?@ "_" table) 58 | (modify-syntax-entry ?< "_" table) 59 | (modify-syntax-entry ?> "_" table) 60 | (modify-syntax-entry ?. "_" table) 61 | (modify-syntax-entry ?, "_" table) 62 | (modify-syntax-entry ?' "_" table) 63 | (modify-syntax-entry ?\" "\"" table) 64 | table)) 65 | 66 | ;; forth-menu-entries: 67 | ;; In the list, the three elements are 68 | ;; 1. menu name (internal) 69 | ;; 2. menu string (shown to the user) 70 | ;; 3. function name (to be called whe this menu entry iss 71 | ;; clicked on 72 | (defvar forth-menu-entries 73 | (reverse (list 74 | '(see "See" forth-see) 75 | '(eval "Eval" forth-eval) 76 | '(eval-defun "Eval defun" forth-eval-defun) 77 | '(eval-region "Eval region" forth-eval-region) 78 | '(eval-last "Eval last" forth-eval-last-expression) 79 | '(eval-display "Eval last and display" forth-eval-last-expression-display-output) 80 | '(separator1 "--") 81 | '(lookup-1994 "Lookup 1994 spec" forth-spec-lookup-1994) 82 | '(lookup-2012 "Lookup-2012 spec" forth-spec-lookup-2012) 83 | '(separator2 "--") 84 | '(load-file "Load file" forth-load-file) 85 | '(run "Run Forth" run-forth) 86 | '(restart "Restart Forth" forth-restart) 87 | '(kill "Kill" forth-kill)))) 88 | 89 | ;; forth-create-menu will actually call define-key to 90 | ;; add meu entries. The format is that of the variable 91 | ;; forth-menu-entries. 92 | (defun forth-create-menu (entries) 93 | (mapcar (lambda (entry) 94 | (let ((menu-name (cl-first entry)) 95 | (menu-string (cl-second entry)) 96 | (menu-function (cl-third entry))) 97 | (define-key forth-mode-map 98 | (vector 'menu-bar 'forth menu-name) 99 | (cons menu-string menu-function)))) 100 | entries)) 101 | 102 | (defun forth-mode-init-menu () 103 | (define-key-after 104 | forth-mode-map 105 | [menu-bar forth] 106 | (cons "Forth" (make-sparse-keymap "Forth")) 107 | 'tools) 108 | (forth-create-menu forth-menu-entries)) 109 | 110 | (defvar forth-mode-hook) 111 | 112 | (defun forth-symbol-start () 113 | (save-excursion 114 | (skip-chars-backward forth-syntax-non-whitespace) 115 | (point))) 116 | 117 | (defun forth-symbol-end () 118 | (save-excursion 119 | (skip-chars-forward forth-syntax-non-whitespace) 120 | (point))) 121 | 122 | (defun forth-word-at-point () 123 | (buffer-substring (forth-symbol-start) (forth-symbol-end))) 124 | 125 | (defun forth-expand-symbol () 126 | (let ((list (forth-words))) 127 | (when (fboundp 'imenu--make-index-alist) 128 | (dolist (index (imenu--make-index-alist t)) 129 | (when (listp (cl-rest index)) 130 | (dolist (def (cl-rest index)) 131 | (push (car def) list))))) 132 | (list (forth-symbol-start) (forth-symbol-end) 133 | ;; FIXME: this should use `completion-table-case-fold' or 134 | ;; closures but neither is available in Emacs23. 135 | `(lambda (string pred action) 136 | (let ((completion-ignore-case t)) 137 | (complete-with-action action ',list string pred)))))) 138 | 139 | (defun forth-block-with-newlines-p () 140 | (save-excursion 141 | (forth-beginning) 142 | (let ((result t)) 143 | (dotimes (i 16) 144 | (goto-char (* 64 (1+ i))) 145 | (unless (looking-at "\n") 146 | (setq result nil))) 147 | result))) 148 | 149 | (defun forth-block-without-newlines-p () 150 | (save-excursion 151 | (forth-beginning) 152 | (not (search-forward "\n" 1024 t)))) 153 | 154 | (defun forth-block-p () 155 | "Guess whether the current buffer is a Forth block file." 156 | (and (> (point-max) 1) 157 | (eq (logand (point-max) 1023) 1) 158 | (or (forth-block-with-newlines-p) 159 | (forth-block-without-newlines-p)))) 160 | 161 | ;; This just calls the standard `fill-paragraph' with adjusted 162 | ;; paramaters. 163 | (defun forth-fill-paragraph (&rest args) 164 | (let ((fill-paragraph-function nil) 165 | (fill-paragraph-handle-comment t) 166 | (comment-start "\\ ") 167 | (comment-end "")) 168 | (apply #'fill-paragraph args))) 169 | 170 | (defun forth-comment-region (&rest args) 171 | (let ((comment-start "\\ ") 172 | (comment-end "")) 173 | (apply #'comment-region-default args))) 174 | 175 | (defun forth-beginning-of-defun (arg) 176 | (and (re-search-backward "^\\s *: \\_<" nil t (or arg 1)) 177 | (beginning-of-line))) 178 | 179 | (unless (fboundp 'prog-mode) 180 | (defalias 'prog-mode 'fundamental-mode)) 181 | 182 | (unless (fboundp 'setq-local) 183 | (defmacro setq-local (var val) 184 | `(set (make-local-variable ',var) ,val))) 185 | 186 | ;;;###autoload 187 | (define-derived-mode forth-mode prog-mode "Forth" 188 | "Major mode for editing Forth files." 189 | :syntax-table forth-mode-syntax-table 190 | (if (forth-block-p) 191 | (forth-block-mode)) 192 | (setq font-lock-defaults '(nil)) 193 | (setq-local completion-at-point-functions '(forth-expand-symbol)) 194 | (when (boundp 'syntax-propertize-function) 195 | (setq-local syntax-propertize-function #'forth-syntax-propertize)) 196 | (setq-local parse-sexp-lookup-properties t) 197 | (hack-local-variables) 198 | (forth-smie-setup) 199 | (setq-local fill-paragraph-function #'forth-fill-paragraph) 200 | (setq-local beginning-of-defun-function #'forth-beginning-of-defun) 201 | (setq-local comment-start-skip "[(\\][ \t*]+") 202 | (setq-local comment-start "( ") 203 | (setq-local comment-end " )") 204 | (setq-local comment-region-function #'forth-comment-region) 205 | (setq imenu-generic-expression 206 | '(("Words" 207 | "^\\s-*\\(:\\|code\\|defer\\)\\s-+\\(\\(\\sw\\|\\s_\\)+\\)" 2) 208 | ("Variables" 209 | "^\\s-*2?\\(variable\\|create\\|value\\)\\s-+\\(\\(\\sw\\|\\s_\\)+\\)" 2) 210 | ("Constants" 211 | "\\s-2?constant\\s-+\\(\\(\\sw\\|\\s_\\)+\\)" 1))) 212 | (forth-mode-init-menu)) 213 | 214 | ;;;###autoload 215 | (add-to-list 'auto-mode-alist '("\\.\\(f\\|fs\\|fth\\|4th\\)\\'" . forth-mode)) 216 | 217 | (unless (fboundp 'with-eval-after-load) 218 | (defmacro with-eval-after-load (lib &rest forms) 219 | `(eval-after-load ,lib '(progn ,@forms)))) 220 | 221 | (with-eval-after-load "speedbar" 222 | (when (fboundp 'speedbar-add-supported-extension) 223 | (speedbar-add-supported-extension ".f") 224 | (speedbar-add-supported-extension ".fs") 225 | (speedbar-add-supported-extension ".fth") 226 | (speedbar-add-supported-extension ".forth") 227 | (speedbar-add-supported-extension ".4th"))) 228 | 229 | (defun forth-beginning () 230 | (goto-char (point-min))) 231 | 232 | (add-hook 'forth-mode-hook 'forth-mode-init-menu) 233 | 234 | (provide 'forth-mode) 235 | ;;; forth-mode.el ends here 236 | -------------------------------------------------------------------------------- /forth-mode.texi: -------------------------------------------------------------------------------- 1 | \input texinfo 2 | @settitle Forth Mode 3 | 4 | @copying 5 | Copyright @copyright{} 2015 Lars Brinkhoff 6 | @end copying 7 | 8 | @dircategory Emacs editing modes 9 | @direntry 10 | * Forth mode: (forth-mode). Emacs mode for editing Forth files. 11 | @end direntry 12 | 13 | @titlepage 14 | @title Forth Mode 15 | @subtitle An Emacs mode for editing Forth files 16 | @end titlepage 17 | 18 | @page 19 | @contents 20 | 21 | @node Top 22 | @top Forth Mode 23 | 24 | Forth Mode is a programming language mode for Forth. It can be used 25 | to edit regular Forth files, and block files. There is also a host of 26 | commands for interacting with a running Forth session. 27 | 28 | @menu 29 | * Overview:: 30 | * Using Forth Mode:: 31 | * Forth Interaction:: 32 | @end menu 33 | 34 | @node Overview 35 | 36 | Programming language mode for Forth. 37 | 38 | @node Using Forth Mode 39 | 40 | How to use forth-mode. 41 | 42 | Key bindings: 43 | 44 | @table @kbd 45 | 46 | @item M-TAB 47 | @itemx C-M-i 48 | @itemx M-x completion-at-point 49 | 50 | Attempt to complete the Forth word under point. 51 | 52 | @item C-M-f 53 | @itemx M-x forward-sexp 54 | 55 | Move forward across one balanced expression. 56 | 57 | @item C-M-b 58 | @itemx M-x backward-sexp 59 | 60 | Move backward across one balanced expression. 61 | 62 | @end table 63 | 64 | @node Forth Interaction 65 | 66 | How to interact with Forth. 67 | 68 | Key bindings: 69 | 70 | @table @kbd 71 | 72 | @item M-x run-forth 73 | 74 | Start an interactive Forth session. 75 | 76 | @item C-c C-z 77 | @itemx M-x forth-switch-to-output-buffer 78 | 79 | Switch to the interactive Forth session. 80 | 81 | @item C-c C-r 82 | @itemx M-x forth-restart 83 | 84 | Restart the interactive Forth session. 85 | 86 | @item C-c C-k 87 | @itemx M-x forth-kill 88 | 89 | End the interactive Forth session. 90 | 91 | @item C-c : 92 | @itemx M-x forth-eval 93 | 94 | Enter a string to evaluation. The output, if any, is printed in the 95 | minibuffer. 96 | 97 | @item C-c C-r 98 | @itemx M-x forth-eval-region 99 | 100 | Evaluate the current region. The output, if any, is printed in the 101 | minibuffer. 102 | 103 | @item C-c C-e 104 | @itemx M-x forth-eval-last-expression 105 | 106 | Evaluate the expression before point. The output, if any, is printed 107 | in the minibuffer. 108 | 109 | @item C-x M-e 110 | @itemx M-x forth-eval-last-expression-display-output 111 | 112 | Evaluate the expression before point. Display the output, if any, in 113 | the interactive Forth session. 114 | 115 | @item C-M-x 116 | @itemx M-x forth-eval-defun 117 | 118 | Evaluate the colon definition under point. The output, if any, is 119 | printed in the minibuffer. 120 | 121 | @item C-c C-l 122 | @itemx M-x forth-load-file 123 | 124 | Load the current file into the interactive Forth Session. 125 | 126 | @item C-c C-s 127 | @itemx M-x forth-see 128 | 129 | Display a human-readable representation of the word under point. 130 | 131 | @end table 132 | 133 | @bye 134 | -------------------------------------------------------------------------------- /forth-parse.el: -------------------------------------------------------------------------------- 1 | (require 'forth-mode) 2 | 3 | (defvar forth-stack-comments (make-hash-table :test 'equal)) 4 | 5 | (defun forth-parse-colon-definition () 6 | (forward-char) 7 | (re-search-forward "[[:graph:]]") 8 | (backward-char) 9 | (let ((start (point))) 10 | (re-search-forward "[^[:graph:]]") 11 | (let ((name (buffer-substring start (1- (point))))) 12 | (when (looking-at "(") 13 | (forward-char 2) 14 | (let ((start (point))) 15 | (search-forward ")") 16 | (setf (gethash name forth-stack-comments) 17 | (buffer-substring start (1- (point))))))))) 18 | 19 | (defun forth-parse-definition () 20 | (cond ((looking-at ":") (forth-parse-colon-definition)) 21 | ((looking-at "create") t) 22 | ((looking-at "variable") t) 23 | ((looking-at "2variable") t) 24 | ((looking-at "defer") t) 25 | ((looking-at "code") t))) 26 | 27 | (defun forth-parse-buffer (&optional buffer) 28 | (setq buffer (or buffer (current-buffer))) 29 | (save-excursion 30 | (forth-beginning) 31 | (end-of-defun) 32 | (beginning-of-defun) 33 | (while t 34 | (forth-parse-definition) 35 | (end-of-defun) 36 | (end-of-defun) 37 | (beginning-of-defun)))) 38 | 39 | (defun forth-word-at-point () 40 | (if (looking-at "[^[:graph:]]") 41 | nil 42 | (save-excursion 43 | (re-search-backward "[^[:graph:]]") 44 | (forward-char) 45 | (let ((start (point))) 46 | (re-search-forward "[^[:graph:]]") 47 | (buffer-substring start (1- (point))))))) 48 | 49 | (defun forth-stack-comment () 50 | (let ((word (forth-word-at-point))) 51 | (when word 52 | (let ((stack-comment (gethash word forth-stack-comments))) 53 | (when stack-comment 54 | (message "%s" stack-comment)))))) 55 | 56 | (defun forth-stack-comments-mode () 57 | (interactive) 58 | (add-hook 'post-command-hook 'forth-stack-comment nil t)) 59 | 60 | (provide 'forth-parse) 61 | -------------------------------------------------------------------------------- /forth-smie.el: -------------------------------------------------------------------------------- 1 | ;; SMIE based indentation 2 | 3 | (require 'smie) 4 | 5 | (defcustom forth-smie-basic-indent 2 6 | "Basic amount of indentation." 7 | :type 'integer 8 | :group 'forth-smie 9 | :safe 'integerp) 10 | 11 | (defcustom forth-smie-bnf-extensions '() 12 | "Rules for non-standard syntax. 13 | 14 | We add this list of BNF rules to the default rules to support 15 | user defined syntax. E.g., setting this variable to 16 | 17 | '((gforth-ext (\"?of\" words \"endof\"))) 18 | 19 | tells Emacs to recognize ?OF ... ENDOF as a matching pair of tokens. 20 | 21 | This variable can also be set in .dir-locals.el, e.g.: 22 | 23 | ((forth-mode . ((forth-smie-bnf-extensions 24 | . ((my-stuff (\"import\" words \"{\" words \"}\"))))))). 25 | " 26 | :type '(alist :key-type symbol :value-type (list (list string symbol))) 27 | :group 'forth-smie 28 | :safe 'listp) 29 | 30 | (defconst forth-smie--bnf 31 | '((control 32 | ("if" words "else" words "then") 33 | ("if" words "then") 34 | ("begin" words "while" words "repeat") 35 | ("begin" words "until") 36 | ("begin" words "again") 37 | ("of" words "endof") 38 | ("case" words "endcase") 39 | ("?do" words "loop") 40 | ("?do" words "+loop") 41 | ("do" words "loop") 42 | ("do" words "+loop") 43 | ("begin-structure" words "end-structure") 44 | (":" words ";") 45 | (":noname" words ";")) 46 | (words))) 47 | 48 | (defun forth-smie--grammar () 49 | (smie-prec2->grammar 50 | (smie-bnf->prec2 (append forth-smie--bnf 51 | forth-smie-bnf-extensions)))) 52 | 53 | (unless (fboundp 'pcase) 54 | (defmacro pcase (form &rest forms) 55 | 0)) 56 | 57 | (defun forth-smie--indentation-rules (kind token) 58 | (pcase (cons kind token) 59 | (`(:elem . basic) forth-smie-basic-indent) 60 | (`(:elem . args) 61 | (cond ((smie-rule-prev-p ":" "begin-structure") 62 | (- (+ (save-excursion 63 | (forth-smie--backward-token) 64 | (current-column)) 65 | forth-smie-basic-indent) 66 | (current-column))) 67 | (t 0))) 68 | (`(:after . ":") (* 2 forth-smie-basic-indent)) 69 | (`(:after . "begin-structure") (* 2 forth-smie-basic-indent)) 70 | (`(:before . ":noname") (cond ((smie-rule-hanging-p) 71 | (current-column)) 72 | (t nil))) 73 | (`(:list-intro . ":") nil) 74 | (`(:list-intro . "begin-structure") nil) 75 | (`(:list-intro . ,_) t) 76 | (_ nil))) 77 | 78 | (defconst forth-smie--parsing-word-regexp 79 | (eval-when-compile 80 | (concat "^" 81 | (regexp-opt '("postpone" "[']" "[char]")) 82 | "$"))) 83 | 84 | (defun forth-smie--forward-word () 85 | (let* ((start (progn (skip-syntax-forward " ") (point))) 86 | (end (progn (skip-syntax-forward "w_") (point)))) 87 | (buffer-substring-no-properties start end))) 88 | 89 | (defun forth-smie--backward-word () 90 | (let* ((end (progn (skip-syntax-backward " ") (point))) 91 | (start (progn (skip-syntax-backward "w_") (point)))) 92 | (buffer-substring-no-properties start end))) 93 | 94 | (defun forth-smie--forward-token () 95 | (forward-comment (point-max)) 96 | (let* ((word1 (downcase (forth-smie--forward-word))) 97 | (pos1 (point)) 98 | (word2 (downcase (forth-smie--forward-word)))) 99 | (cond ((string-match forth-smie--parsing-word-regexp word1) 100 | (list word1 word2)) 101 | (t 102 | (goto-char pos1) 103 | word1)))) 104 | 105 | (defun forth-smie--backward-token () 106 | (forward-comment (- (point))) 107 | (let* ((word1 (downcase (forth-smie--backward-word))) 108 | (pos1 (point)) 109 | (word2 (downcase (forth-smie--backward-word)))) 110 | (cond ((string-match forth-smie--parsing-word-regexp word2) 111 | (list word2 word1)) 112 | (t 113 | (goto-char pos1) 114 | word1)))) 115 | 116 | (defun forth-smie-setup () 117 | (smie-setup (forth-smie--grammar) #'forth-smie--indentation-rules 118 | :forward-token #'forth-smie--forward-token 119 | :backward-token #'forth-smie--backward-token)) 120 | 121 | (provide 'forth-smie) 122 | -------------------------------------------------------------------------------- /forth-spec.el: -------------------------------------------------------------------------------- 1 | ;;; forth-spec.el --- Browse words in Forth standard -*-lexical-binding:t-*- 2 | ;; 3 | ;; Copyright (C) 2016 Helmut Eller 4 | ;; 5 | ;; This program is free software: you can redistribute it and/or modify 6 | ;; it under the terms of the GNU General Public License as published by 7 | ;; the Free Software Foundation, either version 3 of the License, or 8 | ;; (at your option) any later version. 9 | ;; 10 | ;; This program is distributed in the hope that it will be useful, 11 | ;; but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | ;; GNU General Public License for more details. 14 | ;; 15 | ;; You should have received a copy of the GNU General Public License 16 | ;; along with GNU Emacs. If not, see . 17 | 18 | ;;; Commentary: 19 | ;; 20 | ;; This package makes it convenient to browse documentation for 21 | ;; standard Forth words from within Emacs. The command 22 | ;; `forth-spec-lookup' asks for the word name and invokes the HTML 23 | ;; browser with the right URL. 24 | 25 | ;;; Code: 26 | 27 | (require 'cl-lib nil t) 28 | 29 | (defgroup forth-spec 30 | nil 31 | "Browsing Forth standards." 32 | :group 'forth) 33 | 34 | ;; A HTML version of the standard can be downloaded from: 35 | ;; http://www.forth200x.org/documents/forth-2012-html-3.zip 36 | (defcustom forth-spec-url-2012 "https://forth-standard.org/standard/" 37 | "The URL which contains the HTML version of the standard. 38 | If you have a local copy set this variable to 39 | something like \"file:/home/joe/docs/ANS-Forth/\". 40 | 41 | Note: the string should have a trailing backslash." 42 | :type 'file 43 | :group 'forth-spec) 44 | 45 | (defcustom forth-spec-url-1994 "http://lars.nocrew.org/dpans/" 46 | "URL for 1994 version of standard." 47 | :type 'file 48 | :group 'forth-spec) 49 | 50 | (defcustom forth-spec-browse-url #'browse-url 51 | "Just in case you want to use a special browser." 52 | :type 'function 53 | :group 'forth-spec) 54 | 55 | (defun forth-spec-lookup-2012 (name) 56 | "View the documentation on NAME from the Forth 2012 Standard." 57 | (interactive (list (forth-spec--read-name 2012))) 58 | (forth-spec--lookup name 2012)) 59 | 60 | (defun forth-spec-lookup-1994 (name) 61 | "View the documentation on NAME from the ANS'94 Forth Standard." 62 | (interactive (list (forth-spec--read-name 1994))) 63 | (forth-spec--lookup name 1994)) 64 | 65 | (defun forth-spec--lookup (name version) 66 | (funcall forth-spec-browse-url (forth-spec--build-url name version))) 67 | 68 | (defvar forth-spec--lookup-history '()) 69 | 70 | (defun forth-spec--read-name (version) 71 | "Read a word-name in the minibuffer, with completion." 72 | (let ((completion-ignore-case t)) 73 | (completing-read "Word: " (forth-spec--index version) 74 | nil t (thing-at-point 'symbol) 75 | 'forth-spec--lookup-history))) 76 | (eval-and-compile 77 | (defvar forth-spec--versioned-info 78 | '((2012 forth-spec-url-2012 "alpha.html" #'forth-spec--parse-2012) 79 | (1994 forth-spec-url-1994 "dpansf.htm" #'forth-spec--parse-1994)))) 80 | 81 | (defmacro forth-spec--versioned (name version) 82 | (let ((index (cl-ecase name 83 | (url 1) 84 | (index 2) 85 | (parse-index 3)))) 86 | `(cl-ecase ,version 87 | (2012 ,(elt (assoc 2012 forth-spec--versioned-info) index)) 88 | (1994 ,(elt (assoc 1994 forth-spec--versioned-info) index))))) 89 | 90 | (defun forth-spec--root (version) 91 | (forth-spec--versioned url version)) 92 | 93 | (defun forth-spec--build-url (name version) 94 | "Return the URL for the word NAME." 95 | (concat (forth-spec--root version) 96 | (elt (or (assoc name (forth-spec--index version)) 97 | (error "Name not found in index: %s" name)) 98 | 1))) 99 | 100 | (defvar forth-spec--index-cache nil) 101 | 102 | (defun forth-spec--index (version) 103 | "Return a list ((NAME HREF PRONUNCIATION) ...)." 104 | (let ((entry (assoc version forth-spec--index-cache))) 105 | (cond (entry (cdr entry)) 106 | (t 107 | (let ((index (forth-spec--parse-index version))) 108 | (push (cons version index) forth-spec--index-cache) 109 | index))))) 110 | 111 | (defun forth-spec--index-url (version) 112 | (concat (forth-spec--root version) (forth-spec--versioned index version))) 113 | 114 | (defun forth-spec--parse-index (version) 115 | (forth-spec--call/url-buffer (forth-spec--index-url version) 116 | (forth-spec--versioned parse-index version))) 117 | 118 | (defun forth-spec--call/url-buffer (url fun) 119 | (let* ((buffer (url-retrieve-synchronously url)) 120 | (buffer 121 | ;; try without .html (workaround for forth-standard.org) 122 | (save-current-buffer 123 | (set-buffer buffer) 124 | (goto-char (point-min)) 125 | (cond ((and (search-forward "{\"NOT\":\"FOUND\"}" nil t) 126 | (string-match "^\\(.*\\)\\.html$" url)) 127 | (let ((url-sans-html (match-string 1 url))) 128 | (kill-buffer buffer) 129 | (url-retrieve-synchronously url-sans-html))) 130 | (t buffer))))) 131 | (unwind-protect 132 | (with-current-buffer buffer 133 | (funcall fun)) 134 | (kill-buffer buffer)))) 135 | 136 | (defun forth-spec--parse-2012 () 137 | (let ((index '()) 138 | (case-fold-search nil) 139 | (rx "\ 140 | \\([^<]+\\)\\(:?\"\\([^\"]+\\)\"\\)?\ 141 | [^<]*")) 142 | (search-forward "]+\\)>[^<]+[ ]*\\([^ ]+\\)[ ]*\ 154 | \\(?:\\([^\<]+\\)\\)?")) 155 | (search-forward "
")
156 |     (while (re-search-forward rx nil t)
157 |       (push (list (forth-spec--decode-entities (match-string 2))
158 | 		  (match-string 1)
159 | 		  (match-string 3))
160 | 	    index))
161 |     (reverse index)))
162 | 
163 | (declare-function mm-url-decode-entities "gnus/mm-url")
164 | (autoload 'mm-url-decode-entities "gnus/mm-url")
165 | ;; For annoying reasons, we need to declare this here.
166 | (autoload 'mm-disable-multibyte "gnus/mm-util")
167 | 
168 | (defun forth-spec--decode-entities (string)
169 |   (with-temp-buffer
170 |     (insert string)
171 |     (goto-char (point-min))
172 |     (save-match-data
173 |       (mm-url-decode-entities))
174 |     (buffer-string)))
175 | 
176 | (provide 'forth-spec)
177 | 
178 | ;;; forth-spec.el ends here
179 | 


--------------------------------------------------------------------------------
/forth-syntax.el:
--------------------------------------------------------------------------------
  1 | ;;; forth-syntax.el -- syntax-propertize function       -*-lexical-binding:t-*-
  2 | 
  3 | ;; This code mimics the Forth text interpreter and adds text
  4 | ;; properties as side effect.
  5 | 
  6 | (require 'cl-lib)
  7 | 
  8 | 
  9 | ;;; Helpers
 10 | 
 11 | (defvar forth-syntax-whitespace " \t\n\f\r")
 12 | (defvar forth-syntax-non-whitespace (concat "^" forth-syntax-whitespace))
 13 | 
 14 | ;; Skip forward over whitespace and the following word. Return the
 15 | ;; start position of the word.
 16 | (defun forth-syntax--skip-word ()
 17 |   (skip-chars-forward forth-syntax-whitespace)
 18 |   (let ((start (point)))
 19 |     (skip-chars-forward forth-syntax-non-whitespace)
 20 |     start))
 21 | 
 22 | ;; Return the whitespace-delimited word at position POS.
 23 | ;; Return nil if POS is at end-of-buffer.
 24 | (defun forth-syntax--word-at (pos)
 25 |   (save-excursion
 26 |     (goto-char pos)
 27 |     (let ((start (forth-syntax--skip-word)))
 28 |       (cond ((= start (point)) nil)
 29 | 	    (t (buffer-substring-no-properties start (point)))))))
 30 | 
 31 | (defmacro forth-syntax--set-syntax (start end syntax)
 32 |   "Set the 'syntax-table property in the region START/END to SYNTAX.
 33 | SYNTAX must be a valid argument for `string-to-syntax'."
 34 |   `(put-text-property ,start ,end 'syntax-table ',(string-to-syntax syntax)))
 35 | 
 36 | ;; Set the syntax in the region START/END to "word" or "symbol".  Do
 37 | ;; nothing for characters that already have the correct syntax so that
 38 | ;; word movement commands work "naturally".
 39 | (defun forth-syntax--set-word-syntax (start end)
 40 |   (save-excursion
 41 |     (goto-char start)
 42 |     (while (progn
 43 | 	     (skip-syntax-forward "w_" end)
 44 | 	     (cond ((< (point) end)
 45 | 		    (let ((start (point)))
 46 | 		      (skip-syntax-forward "^w_" end)
 47 | 		      (forth-syntax--set-syntax start (point) "_")
 48 | 		      t))
 49 | 		   (t nil))))))
 50 | 
 51 | 
 52 | ;;; State functions
 53 | 
 54 | ;; The parser is a loop that calls "state-functions".
 55 | ;; A state function parses forward from point, adds text-properties as needed,
 56 | ;; and returns the next state-function.
 57 | ;;
 58 | ;; The naming convention for state-functions is forth-syntax--state-FOO.
 59 | 
 60 | (defun forth-syntax--state-eob ()
 61 |   (cl-assert (eobp))
 62 |   (error "This state function should never be called"))
 63 | 
 64 | ;; One line strings
 65 | (defun forth-syntax--state-string ()
 66 |   (forth-syntax--set-syntax (1- (point)) (point) "|")
 67 |   (cond ((re-search-forward "[\"\n]" nil t)
 68 | 	 (forth-syntax--set-syntax (1- (point)) (point) "|")
 69 | 	 #'forth-syntax--state-normal)
 70 | 	(t
 71 | 	 (goto-char (point-max))
 72 | 	 #'forth-syntax--state-eob)))
 73 | 
 74 | (defun forth-syntax--state-s\\\" ()
 75 |   (forth-syntax--set-syntax (1- (point)) (point) "|")
 76 |   (while (and (re-search-forward "\\([\"\n]\\|\\\\\\\\\\|\\\\\"\\)" nil t)
 77 | 	      (cond ((= (char-after (match-beginning 0)) ?\\)
 78 | 		     (forth-syntax--set-syntax (match-beginning 0)
 79 | 					       (1+ (match-beginning 0))
 80 | 					       "\\")
 81 | 		     t))))
 82 |   (cond ((looking-back "[\"\n]" 1)
 83 | 	 (forth-syntax--set-syntax (1- (point)) (point) "|")
 84 | 	 #'forth-syntax--state-normal)
 85 | 	(t
 86 | 	 (goto-char (point-max))
 87 | 	 #'forth-syntax--state-eob)))
 88 | 
 89 | ;; The position where the current word started.  It is setup by
 90 | ;; `forth-syntax--state-normal'.  It avoids the need to scan backward
 91 | ;; so often.
 92 | (defvar forth-syntax--current-word-start -1)
 93 | 
 94 | ;; For the word before point, set the font-lock-face property.
 95 | (defun forth-syntax--mark-font-lock-keyword ()
 96 |   (let ((start forth-syntax--current-word-start))
 97 |     (put-text-property start (point) 'font-lock-face font-lock-keyword-face)))
 98 | 
 99 | (defun forth-syntax--state-font-lock-keyword ()
100 |   (forth-syntax--mark-font-lock-keyword)
101 |   (forth-syntax--state-normal))
102 | 
103 | 
104 | ;; State for words that parse the following word, e.g. POSTPONE S"
105 | ;; where POSTPONE parses S".
106 | ;;
107 | ;; FIXME: It would nice be to know if we are in compilation state for
108 | ;; things like this: : FOO CREATE , ;
109 | ;; Because in this case CREATE doesn't parse immediately.
110 | (defun forth-syntax--state-parsing-word ()
111 |   (let ((start (forth-syntax--skip-word)))
112 |     (cond ((= start (point))
113 | 	   #'forth-syntax--state-eob)
114 | 	  (t
115 | 	   (forth-syntax--set-word-syntax start (point))
116 | 	   #'forth-syntax--state-normal))))
117 | 
118 | ;; This is like `forth-syntax--state-parsing-word' but additionally
119 | ;; sets the font-lock-keyword-face.
120 | (defun forth-syntax--state-parsing-keyword ()
121 |   (forth-syntax--mark-font-lock-keyword)
122 |   (forth-syntax--state-parsing-word))
123 | 
124 | ;; This is also like `forth-syntax--state-parsing-word' but
125 | ;; additionally set font-lock-keyword-face for the current word and
126 | ;; font-lock-function-name-face for the following word.
127 | ;; It's intended for thigs like: DEFER S"
128 | (defun forth-syntax--state-defining-word ()
129 |   (forth-syntax--mark-font-lock-keyword)
130 |   (let ((start (forth-syntax--skip-word)))
131 |     (cond ((= start (point))
132 | 	   #'forth-syntax--state-eob)
133 | 	  (t
134 | 	   (forth-syntax--set-word-syntax start (point))
135 | 	   (put-text-property start (point) 'font-lock-face
136 | 			      font-lock-function-name-face)
137 | 	   #'forth-syntax--state-normal))))
138 | 
139 | (defun forth-syntax--parse-comment (backward-regexp forward-regexp)
140 |   (let ((pos (point)))
141 |     (re-search-backward backward-regexp)
142 |     (forth-syntax--set-syntax (point) (1+ (point)) "!")
143 |     (goto-char pos)
144 |     (cond ((re-search-forward forward-regexp nil t)
145 | 	   (forth-syntax--set-syntax (1- (point)) (point) "!")
146 | 	   #'forth-syntax--state-normal)
147 | 	  (t
148 | 	   (goto-char (point-max))
149 | 	   #'forth-syntax--state-eob))))
150 | 
151 | ;; Define a state-function for comments.  The comment starts with
152 | ;; the string BEGIN and ends with the string END.
153 | (defmacro forth-syntax--define-comment-state (begin end)
154 |   (let ((fname (intern (concat "forth-syntax--state-" begin))))
155 |     `(defun ,fname ()
156 |        (forth-syntax--parse-comment ,(concat (regexp-quote begin) "\\=")
157 | 				    ,(regexp-quote end)))))
158 | 
159 | (forth-syntax--define-comment-state "(" ")")
160 | (forth-syntax--define-comment-state "\\" "\n")
161 | (forth-syntax--define-comment-state ".(" ")")
162 | 
163 | ;; For now, treat locals like comments
164 | (forth-syntax--define-comment-state "{:" ":}")
165 | 
166 | ;; Hashtable that maps strings (word names) to parser functions.
167 | (defvar forth-syntax--parsers (make-hash-table :test 'equal))
168 | 
169 | (defun forth-syntax--define (word parsing-function)
170 |   (setf (gethash (downcase word) forth-syntax--parsers) parsing-function))
171 | 
172 | ;; Find the parsing function for WORD.
173 | (defun forth-syntax--lookup (word)
174 |   (gethash (downcase word) forth-syntax--parsers))
175 | 
176 | (forth-syntax--define "s\"" #'forth-syntax--state-string)
177 | (forth-syntax--define ".\"" #'forth-syntax--state-string)
178 | (forth-syntax--define "c\"" #'forth-syntax--state-string)
179 | (forth-syntax--define "abort\"" #'forth-syntax--state-string)
180 | 
181 | (forth-syntax--define "s\\\"" #'forth-syntax--state-s\\\")
182 | 
183 | (forth-syntax--define "(" #'forth-syntax--state-\()
184 | (forth-syntax--define "\\" #'forth-syntax--state-\\)
185 | (forth-syntax--define ".(" #'forth-syntax--state-.\()
186 | (forth-syntax--define "{:" #'forth-syntax--state-{:)
187 | 
188 | (forth-syntax--define "postpone" #'forth-syntax--state-parsing-keyword)
189 | 
190 | (defvar forth-syntax--parsing-words
191 |   '("'" "[']" "char" "[char]"))
192 | 
193 | (defvar forth-syntax--defining-words
194 |   '(":" "create" "synonym" "defer" "code"
195 |     "constant" "2constant" "fconstant"
196 |     "value" "2value" "fvalue"
197 |     "variable" "2variable" "fvariable"
198 |     "+field" "field:" "cfield:" "ffield:" "sffield:" "dffield:"
199 |     ))
200 | 
201 | (defvar forth-syntax--font-lock-keywords
202 |   '("if" "else" "then"
203 |     "?do" "do" "unloop" "exit" "leave" "loop" "+loop"
204 |     "begin" "while" "repeat" "again" "until"
205 |     "case" "?of" "of" "endof" "endcase"
206 |     ":noname" ";" "does>" "immediate"
207 |     "is" "to"
208 |     "literal" "2literal" "fliteral" "sliteral"
209 |     "begin-structure" "end-structure"))
210 | 
211 | (dolist (w forth-syntax--parsing-words)
212 |   (forth-syntax--define w #'forth-syntax--state-parsing-word))
213 | 
214 | (dolist (w forth-syntax--defining-words)
215 |   (forth-syntax--define w #'forth-syntax--state-defining-word))
216 | 
217 | (dolist (w forth-syntax--font-lock-keywords)
218 |   (forth-syntax--define w #'forth-syntax--state-font-lock-keyword))
219 | 
220 | ;; Look for the next whitespace delimited word; mark all its
221 | ;; characters as "word constituents"; finally return state-function
222 | ;; for the word.
223 | (defun forth-syntax--state-normal ()
224 |   (let ((start (forth-syntax--skip-word)))
225 |     (cond ((= start (point))
226 | 	   #'forth-syntax--state-eob)
227 | 	  (t
228 | 	   (forth-syntax--set-word-syntax start (point))
229 | 	   (let* ((word (buffer-substring-no-properties start (point)))
230 | 		  (parser (forth-syntax--lookup word)))
231 | 	     (cond (parser
232 | 		    (setq forth-syntax--current-word-start start)
233 | 		    (funcall parser))
234 | 		   (t
235 | 		    #'forth-syntax--state-normal)))))))
236 | 
237 | 
238 | ;;; Guess initial state
239 | 
240 | ;; Is it normal that `syntax-ppss' moves point or is that a bug?
241 | (defun forth-syntax--ppss (pos)
242 |   (save-excursion
243 |     (syntax-ppss pos)))
244 | 
245 | (defun forth-syntax--in-comment-p (pos)
246 |   (not (null (elt (forth-syntax--ppss pos) 4))))
247 | 
248 | (defun forth-syntax--comment-start-position (pos)
249 |   (elt (forth-syntax--ppss pos) 8))
250 | 
251 | ;; Make a guess for the syntax state at position POS.
252 | ;; Return a pair (START .  PARSING-FUNCTION).
253 | (defun forth-syntax--guess-state (pos)
254 |     (cond ((and (< (point-min) pos)
255 | 		(forth-syntax--in-comment-p (1- pos)))
256 | 	   (cons (forth-syntax--comment-start-position (1- pos))
257 | 		 #'forth-syntax--state-normal))
258 | 	  (t
259 | 	   (cons pos #'forth-syntax--state-normal))))
260 | 
261 | 
262 | ;;; Main entry point
263 | 
264 | ;; Guess a state for the position START, then call state-functions
265 | ;; until the position END is reached.
266 | (defun forth-syntax-propertize (start end)
267 |   (save-excursion
268 |     (remove-text-properties start end '(font-lock-face))
269 |     (let* ((guess (forth-syntax--guess-state start))
270 | 	   (state (cdr guess)))
271 |       ;;(message "forth-syntax-propertize: %s %s %s" start end guess)
272 |       (goto-char (car guess))
273 |       (while (< (point) end)
274 | 	(let ((start (point)))
275 | 	  (setq state (funcall state))
276 | 	  (cl-assert (< start (point))))))))
277 | 
278 | (provide 'forth-syntax)
279 | 


--------------------------------------------------------------------------------
/test/block1.fth:
--------------------------------------------------------------------------------
1 |                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 


--------------------------------------------------------------------------------
/test/block2.fth:
--------------------------------------------------------------------------------
 1 |                                                                
 2 |                                                                
 3 |                                                                
 4 |                                                                
 5 |                                                                
 6 |                                                                
 7 |                                                                
 8 |                                                                
 9 |                                                                
10 |                                                                
11 |                                                                
12 |                                                                
13 |                                                                
14 |                                                                
15 |                                                                
16 |                                                                
17 |                                                                
18 |                                                                
19 |                                                                
20 |                                                                
21 |                                                                
22 |                                                                
23 |                                                                
24 |                                                                
25 |                                                                
26 |                                                                
27 |                                                                
28 |                                                                
29 |                                                                
30 |                                                                
31 |                                                                
32 |                                                                
33 | 


--------------------------------------------------------------------------------
/test/noblock.fth:
--------------------------------------------------------------------------------
1 | : foo ;
2 | 


--------------------------------------------------------------------------------
/test/tests.el:
--------------------------------------------------------------------------------
  1 | (require 'forth-mode)
  2 | (require 'forth-interaction-mode)
  3 | (require 'forth-block-mode)
  4 | 
  5 | (unless forth-executable
  6 |   (setq forth-executable (getenv "FORTH")))
  7 | 
  8 | (ert-deftest load-not-block ()
  9 |   (find-file "test/noblock.fth")
 10 |   (should (eq major-mode 'forth-mode))
 11 |   (should-not (and (boundp 'forth-block-mode) forth-block-mode))
 12 |   (kill-buffer))
 13 | 
 14 | (ert-deftest load-block-with-newlines ()
 15 |   (find-file "test/block2.fth")
 16 |   (should (eq major-mode 'forth-mode))
 17 |   (should (and (boundp 'forth-block-mode) forth-block-mode))
 18 |   (kill-buffer))
 19 | 
 20 | (ert-deftest load-block-without-newlines ()
 21 |   (find-file "test/block1.fth")
 22 |   (should (eq major-mode 'forth-mode))
 23 |   (should (and (boundp 'forth-block-mode) forth-block-mode))
 24 |   (kill-buffer))
 25 | 
 26 | (defmacro forth-with-temp-buffer (contents &rest body)
 27 |   (declare (indent 1) (debug t))
 28 |   `(with-temp-buffer
 29 |      (insert ,contents)
 30 |      (forth-mode)
 31 |      ,@body))
 32 | 
 33 | (unless (boundp 'font-lock-ensure)
 34 |   ;; Emacs 24 doesn't have font-lock-ensure.
 35 |   (defun font-lock-ensure ()
 36 |     (font-lock-fontify-buffer)))
 37 | 
 38 | (defun forth-strip-| (string)
 39 |   (replace-regexp-in-string "^[ \t]*|" "" (substring-no-properties  string)))
 40 | 
 41 | (defun forth-strip-|-and-→ (string)
 42 |   (let* ((s2 (forth-strip-| string))
 43 | 	 (pos (1+ (string-match "→" s2))))
 44 |     (list (remove ?→ s2) pos)))
 45 | 
 46 | (defun forth-strip-|-and-¹² (string)
 47 |   (let* ((s2 (forth-strip-| string))
 48 | 	 (start (1+ (string-match "¹" (remove ?² s2))))
 49 | 	 (end (1+ (string-match "²" (remove ?¹ s2)))))
 50 |     (list (remove ?² (remove ?¹ s2))
 51 | 	  start end)))
 52 | 
 53 | (defun forth-assert-face (content face)
 54 |   (when (boundp 'syntax-propertize-function)
 55 |     (cl-destructuring-bind (content pos) (forth-strip-|-and-→ content)
 56 |       (forth-with-temp-buffer content
 57 | 	(font-lock-ensure)
 58 | 	(should (eq face (or (get-text-property pos 'face)
 59 | 			     (get-text-property pos 'font-lock-face))))))))
 60 | 
 61 | (defun forth-should-indent (expected &optional content)
 62 |   "Assert that CONTENT turns into EXPECTED after the buffer is re-indented.
 63 | If CONTENT is not supplied uses EXPECTED as input.
 64 | The whitespace before and including \"|\" on each line is removed."
 65 |   (let ((content (or content expected)))
 66 |     (forth-with-temp-buffer (forth-strip-| content)
 67 |       (let ((inhibit-message t)) ; Suppress "Indenting region ... done" message
 68 | 	(indent-region (point-min) (point-max)))
 69 |       ;; TODO: Can we check for a missing function in Emacs 23?
 70 |       (unless (version< emacs-version "24")
 71 | 	(should (string= (forth-strip-| expected)
 72 | 			 (substring-no-properties (buffer-string))))))))
 73 | 
 74 | (defun forth-assert-forward-sexp (content)
 75 |   (cl-destructuring-bind (content start end) (forth-strip-|-and-¹² content)
 76 |     (forth-with-temp-buffer content
 77 |       (goto-char start)
 78 |       (forward-sexp)
 79 |       (should (= (point) end)))))
 80 | 
 81 | (defun forth-assert-forward-word (content)
 82 |   (cl-destructuring-bind (content start end) (forth-strip-|-and-¹² content)
 83 |     (forth-with-temp-buffer content
 84 |       (goto-char start)
 85 |       (font-lock-ensure) ; Make sure syntax-propertize function is called
 86 |       (forward-word)
 87 |       (should (= (point) end)))))
 88 | 
 89 | (defun forth-should-before/after (before after fun)
 90 |   (cl-destructuring-bind (before point-before) (forth-strip-|-and-→ before)
 91 |     (cl-destructuring-bind (after point-after) (forth-strip-|-and-→ after)
 92 |       (forth-with-temp-buffer before
 93 | 	(goto-char point-before)
 94 | 	(funcall fun)
 95 | 	(should (string= after (substring-no-properties (buffer-string))))
 96 | 	(should (= (point) point-after))))))
 97 | 
 98 | (defun forth-should-region-before/after (before after fun)
 99 |   (cl-destructuring-bind (before start1 end1) (forth-strip-|-and-¹² before)
100 |     (cl-destructuring-bind (after point-after) (forth-strip-|-and-→ after)
101 |       (forth-with-temp-buffer before
102 | 	(set-mark start1)
103 | 	(goto-char end1)
104 | 	(activate-mark)
105 | 	(funcall fun)
106 | 	(should (string= after (substring-no-properties (buffer-string))))
107 | 	(should (= (point) point-after))))))
108 | 
109 | (defmacro forth-with-forth (&rest body)
110 |   (declare (indent 0))
111 |   `(let* ((proc (get-buffer-process forth-interaction-buffer)))
112 |      ;; FIXME: there should be a better way to do this. Probably a
113 |      ;; callback function.
114 |      (while (not (processp proc))
115 |        (run-forth)
116 |        (message "Waiting for Forth to start ...")
117 |        (accept-process-output nil 0.3)
118 |        (setq proc (get-buffer-process forth-interaction-buffer)))
119 |      (unwind-protect
120 | 	 (progn . ,body)
121 | 	 (kill-process proc))))
122 | 
123 | (defun forth-assert-backward-token (content token)
124 |   (cl-destructuring-bind (content pos1 pos2) (forth-strip-|-and-¹² content)
125 |     (forth-with-temp-buffer content
126 |       (goto-char pos1)
127 |       (let ((token2 (forth-smie--backward-token)))
128 | 	(should (equal token2 token))
129 | 	(should (= (point) pos2))))))
130 | 
131 | (defun forth-assert-forward-token (content token)
132 |   (cl-destructuring-bind (content pos1 pos2) (forth-strip-|-and-¹² content)
133 |     (forth-with-temp-buffer content
134 |       (goto-char pos1)
135 |       (let ((token2 (forth-smie--forward-token)))
136 | 	(should (equal token2 token))
137 | 	(should (= (point) pos2))))))
138 | 
139 | (ert-deftest forth-paren-comment-font-lock ()
140 |   (forth-assert-face "→( )" font-lock-comment-delimiter-face)
141 |   (forth-assert-face "→.( )" font-lock-comment-face)
142 |   (forth-assert-face "( →)" font-lock-comment-delimiter-face)
143 |   (forth-assert-face " →( )" font-lock-comment-delimiter-face)
144 |   (forth-assert-face "\t→( )" font-lock-comment-delimiter-face)
145 |   (forth-assert-face "→(\t)" font-lock-comment-delimiter-face)
146 |   (forth-assert-face "(fo→o) " nil)
147 |   (forth-assert-face "(fo→o)" nil)
148 |   (forth-assert-face "(→) " nil)
149 |   (forth-assert-face "( →foo) " font-lock-comment-face)
150 |   (forth-assert-face "( a b --
151 |                         →x y )" font-lock-comment-face))
152 | 
153 | (ert-deftest forth-backslash-comment-font-lock ()
154 |   (forth-assert-face "→\\" font-lock-comment-face)
155 |   (forth-assert-face "→\\ " font-lock-comment-delimiter-face)
156 |   (forth-assert-face " →\\" font-lock-comment-face)
157 |   (forth-assert-face "\t→\\ " font-lock-comment-delimiter-face)
158 |   (forth-assert-face " →\\\t" font-lock-comment-delimiter-face)
159 |   (forth-assert-face " →\\\n" font-lock-comment-face)
160 |   (forth-assert-face "a→\\b" nil)
161 |   (forth-assert-face "a→\\b " nil))
162 | 
163 | (ert-deftest forth-brace-colon-font-lock ()
164 |   (forth-assert-face "→{: :}" font-lock-comment-face)
165 |   (forth-assert-face "{: :→}" font-lock-comment-face)
166 |   (forth-assert-face "{: →a b :}" font-lock-comment-face)
167 |   (forth-assert-face "→{::}" nil)
168 |   (forth-assert-face "{: a b --
169 |                          →x y :}" font-lock-comment-face)
170 |   (forth-assert-face "t→{ 2 1+ -> 3 }t" nil))
171 | 
172 | (ert-deftest forth-string-font-lock ()
173 |   (forth-assert-face "→s\" ab\"" nil)
174 |   (forth-assert-face "s→\" ab\"" font-lock-string-face)
175 |   (forth-assert-face "abort→\" ab\"" font-lock-string-face)
176 |   (forth-assert-face ".→\" ab\"" font-lock-string-face)
177 |   (forth-assert-face "c→\" ab\"" font-lock-string-face)
178 |   (forth-assert-face "[char] \" →swap" nil)
179 |   (forth-assert-face "frob\" →ab\" " nil)
180 |   (forth-assert-face "s\" →a \n b " font-lock-string-face)
181 |   (forth-assert-face "s\" a \n →b " nil)
182 |   (forth-assert-face "→s\\\" ab\"" nil)
183 |   (forth-assert-face "s\\→\" ab\"" font-lock-string-face)
184 |   (forth-assert-face "s\\\" a→b\"" font-lock-string-face)
185 |   (forth-assert-face "s\\\" a\\\"→c\"" font-lock-string-face)
186 |   (forth-assert-face "s\\\" \\\\ →a \" b" font-lock-string-face)
187 |   (forth-assert-face "s\\\" \\\\ a \" →b" nil)
188 |   (forth-assert-face "s\\\" \\\" →a \" b" font-lock-string-face)
189 |   (forth-assert-face "s\\\" \\\" a \" →b" nil)
190 |   (forth-assert-face "s\\\" →a \n b " font-lock-string-face)
191 |   (forth-assert-face "s\\\" a \n →b " nil))
192 | 
193 | (ert-deftest forth-parsing-words-font-lock ()
194 |   (forth-assert-face "postpone ( →x " nil)
195 |   (forth-assert-face "' s\" →x "nil)
196 |   (forth-assert-face "case [char] ' →of exit endof " font-lock-keyword-face)
197 |   (forth-assert-face "case [char] ' →?of exit endof " font-lock-keyword-face)
198 |   (forth-assert-face "→postpone postpone" font-lock-keyword-face)
199 |   (forth-assert-face "postpone →postpone" nil)
200 |   (forth-assert-face "→literal" font-lock-keyword-face)
201 |   (forth-assert-face "postpone →literal" nil)
202 |   (forth-assert-face "[ 48 ] →literal" font-lock-keyword-face)
203 |   (forth-assert-face "→: frob ;" font-lock-keyword-face)
204 |   (forth-assert-face ": →frob ;" font-lock-function-name-face)
205 |   (forth-assert-face "constant →foo" font-lock-function-name-face)
206 |   (forth-assert-face "create →foo" font-lock-function-name-face)
207 |   (forth-assert-face "value →foo" font-lock-function-name-face)
208 |   (forth-assert-face "variable →foo" font-lock-function-name-face)
209 |   (forth-assert-face "synonym →foo bar" font-lock-function-name-face))
210 | 
211 | (ert-deftest forth-indent-colon-definition ()
212 |   (forth-should-indent
213 |    ": foo ( x y -- y x )
214 |    |  swap
215 |    |;")
216 |   ;; Open Firmware style
217 |   (let ((forth-smie-basic-indent 3))
218 |     (forth-should-indent
219 |      ": foo ( x y -- y x )
220 |      |   swap
221 |      |;")))
222 | 
223 | (ert-deftest forth-indent-if-then-else ()
224 |   (forth-should-indent
225 |    "x if
226 |    |  3 +
227 |    |then")
228 |   (forth-should-indent
229 |    "x if
230 |    |  3 +
231 |    |else
232 |    |  1+
233 |    |then")
234 |   (forth-should-indent
235 |    "x IF
236 |    |  3 +
237 |    |ELSE
238 |    |  1+
239 |    |THEN"))
240 | 
241 | (ert-deftest forth-indent-begin-while-repeat ()
242 |   (forth-should-indent
243 |    "begin
244 |    |  0>
245 |    |while
246 |    |  1-
247 |    |repeat")
248 |   (forth-should-indent
249 |    "begin
250 |    |  0>
251 |    |while
252 |    |  begin
253 |    |    foo
254 |    |  while
255 |    |    bar
256 |    |  repeat
257 |    |  1-
258 |    |repeat"))
259 | 
260 | ;; FIXME: this kind of code is indented poorly (difficult for SMIE)
261 | ;; |: foo ( )
262 | ;; |  begin
263 | ;; |    bar while
264 | ;; |    baz while
265 | ;; |again then then ;
266 | 
267 | (ert-deftest forth-indent-do ()
268 |   (forth-should-indent
269 |    "10 0 ?do
270 |    |  .
271 |    |loop")
272 |   (forth-should-indent
273 |    "10 0 ?do
274 |    |  . 2
275 |    |+loop"))
276 | 
277 | (ert-deftest forth-indent-case ()
278 |   (forth-should-indent
279 |    "x case
280 |    |  [char] f of
281 |    |    foo
282 |    |  endof
283 |    |  [char] b of bar
284 |    |              baz
285 |    |           endof
286 |    |  test ?of
287 |    |  drop exit
288 |    |endcase"))
289 | 
290 | (ert-deftest forth-indent-customization ()
291 |   (forth-should-indent
292 |    "\ -*- forth-smie-bnf-extensions: ((ext (\"?of\" words \"endof\"))) -*-
293 |    |x case
294 |    |  [char] f of
295 |    |    foo
296 |    |  endof
297 |    |  test ?of
298 |    |    bar
299 |    |  endof
300 |    |endcase"))
301 | 
302 | ;; This is an tricky case because SMIE thinks, depending on
303 | ;; `comment-start-skip` (which indirectly depends on `comment-start`
304 | ;; thru `comment-normalize-vars`), that (foo) is a comment.  But since
305 | ;; (foo) is not actually a comment this leads to an endless recursion.
306 | (ert-deftest forth-indent-\(foo\) ()
307 |   (forth-should-indent
308 |    ": foo
309 |    |  (foo) ;"))
310 | 
311 | (ert-deftest forth-indent-structure ()
312 |   (forth-should-indent
313 |    "BEGIN-STRUCTURE point
314 |    |  1 CELLS +FIELD p.x
315 |    |  1 CELLS +FIELD p.y
316 |    |END-STRUCTURE"))
317 | 
318 | (ert-deftest forth-indent-noname ()
319 |   (forth-should-indent
320 |    "1 2 :noname
321 |    |      swap
322 |    |    ;
323 |    |execute"))
324 | 
325 | (ert-deftest forth-indent-postpone ()
326 |   (forth-should-indent
327 |    ": foo
328 |    |  postpone :
329 |    |  42 postpone literal
330 |    |  postpone ;
331 |    |;")
332 |   (forth-should-indent
333 |    ": foo
334 |    |  POSTPONE :
335 |    |  42 POSTPONE literal
336 |    |  postpone ;
337 |    |;")
338 |   (forth-should-indent
339 |    ": foo
340 |    |  postpone if
341 |    |  if
342 |    |    postpone then
343 |    |  else
344 |    |    postpone then
345 |    |  then
346 |    |;")
347 |   (forth-should-indent
348 |    ": foo
349 |    |  ['] :
350 |    |  if
351 |    |    postpone ;
352 |    |  else
353 |    |    postpone recurse postpone ;
354 |    |  then
355 |    |;")
356 |   )
357 | 
358 | (ert-deftest forth-sexp-movements ()
359 |   (forth-assert-forward-sexp " ¹: foo bar ;² \ x")
360 |   (forth-assert-forward-sexp " ¹:noname foo bar ;² \ x")
361 |   (forth-assert-forward-sexp " ¹if drop exit else 1+ then² bar ")
362 |   (forth-assert-forward-sexp " : foo ¹postpone if² postpone then ;"))
363 | 
364 | ;; IDEA: give the filename in "include filename" string syntax.
365 | (ert-deftest forth-word-movements ()
366 |   (forth-assert-forward-word "¹include² /tmp/foo.fth \ bar")
367 |   (forth-assert-forward-word "include¹ /tmp²/foo.fth \ bar")
368 |   (forth-assert-forward-word "¹foo²-bar"))
369 | 
370 | (ert-deftest forth-spec-parsing ()
371 |   (should (equal (forth-spec--build-url "SWAP" 1994)
372 | 		 "http://lars.nocrew.org/dpans/dpans6.htm#6.1.2260"))
373 |   (should (string-match "core/ColonNONAME"
374 | 			(forth-spec--build-url ":NONAME" 2012)))
375 |   (should (string-match "memory/ALLOCATE"
376 | 			(forth-spec--build-url "ALLOCATE" 2012)))
377 |   (should (= (length (cdr (assoc 2012 forth-spec--index-cache)))
378 | 	     450)))
379 | 
380 | (ert-deftest forth-fill-comment ()
381 |   (forth-should-before/after
382 |    "\\ foo bar
383 |    |\\ baz→
384 |    |: frob ( x y -- z ) ;"
385 |    "\\ foo bar baz→
386 |    |: frob ( x y -- z ) ;"
387 |    #'fill-paragraph))
388 | 
389 | (ert-deftest forth-beginning-of-defun ()
390 |   (forth-should-before/after
391 |    ": foo bar ;
392 |    |: baz ( x -- )
393 |    |  if foo→ then ;"
394 |    ": foo bar ;
395 |    |→: baz ( x -- )
396 |    |  if foo then ;"
397 |    #'beginning-of-defun))
398 | 
399 | ;; FIXME: maybe insert "(  )" instead of "()".
400 | (ert-deftest forth-comment-dwim ()
401 |   (forth-should-before/after
402 |    ": frob
403 |    |  begin     ( x y )
404 |    |    swap→
405 |    |  again ;"
406 |    ": frob
407 |    |  begin     ( x y )
408 |    |    swap    ( → )
409 |    |  again ;"
410 |    (lambda ()
411 |      (call-interactively #'comment-dwim)))
412 |   (forth-should-region-before/after
413 |    "²: frob
414 |    |  begin     ( x y )
415 |    |    swap
416 |    |  again ;
417 |    |¹"
418 |    "→\\ : frob
419 |    |\\   begin     ( x y )
420 |    |\\     swap
421 |    |\\   again ;
422 |    |"
423 |    (lambda ()
424 |      (call-interactively #'comment-dwim)))
425 |   (forth-should-region-before/after
426 |    "¹\\ : frob
427 |    |\\   begin     ( x y )
428 |    |\\     swap
429 |    |\\   again ;
430 |    |²"
431 |    ": frob
432 |    |  begin     ( x y )
433 |    |    swap
434 |    |  again ;
435 |    |→"
436 |    (lambda ()
437 |      (call-interactively #'comment-dwim))))
438 | 
439 | (ert-deftest forth-completion-at-point ()
440 |   (forth-with-forth
441 |     (forth-should-before/after
442 |      "2c→"
443 |      "2Constant→"
444 |      #'completion-at-point)))
445 | 
446 | (ert-deftest forth-smie-backward-token ()
447 |   (forth-assert-backward-token "²foo¹" "foo")
448 |   (forth-assert-backward-token "²foo-bar¹" "foo-bar")
449 |   (forth-assert-backward-token "  ²foo-bar  ¹baz" "foo-bar")
450 |   (forth-assert-backward-token " ²?#!-+  ¹" "?#!-+")
451 |   (forth-assert-backward-token " ²foo ( x y ) ¹" "foo")
452 |   (forth-assert-backward-token " foo \ x ²y  ¹" "y")
453 |   (forth-assert-backward-token " ²postpone foo¹" '("postpone" "foo"))
454 |   (forth-assert-backward-token " ²[']   foo ¹" '("[']" "foo"))
455 |   (forth-assert-backward-token " ²[char]  : ¹" '("[char]" ":"))
456 |   ;; We're mostly interested in getting indentation inside colon
457 |   ;; definitions right, so here we don't treat ' as parsing word.
458 |   (forth-assert-backward-token " ' ²foo¹" "foo")
459 |   (forth-assert-backward-token " : ²foo¹" "foo"))
460 | 
461 | (ert-deftest forth-smie-forward-token ()
462 |   (forth-assert-forward-token "¹foo²" "foo")
463 |   (forth-assert-forward-token "¹foo-bar²" "foo-bar")
464 |   (forth-assert-forward-token "  ¹foo-bar²  baz" "foo-bar")
465 |   (forth-assert-forward-token " ¹?#!-+²  " "?#!-+")
466 |   (forth-assert-forward-token " ¹foo² ( x y )" "foo")
467 |   (forth-assert-forward-token " foo \ x ¹y² " "y")
468 |   (forth-assert-forward-token " ¹postpone foo²" '("postpone" "foo"))
469 |   (forth-assert-forward-token " ¹ [']   foo² " '("[']" "foo"))
470 |   (forth-assert-forward-token " ¹[char]  :² " '("[char]" ":"))
471 |   (forth-assert-forward-token " ¹'² foo" "'")
472 |   (forth-assert-forward-token " ¹:² foo" ":"))
473 | 


--------------------------------------------------------------------------------