pax_global_header00006660000000000000000000000064141020276430014511gustar00rootroot0000000000000052 comment=7ee3febab01aeacfd33357124e7f605e1e110d99 lua-mode-20210802/000077500000000000000000000000001410202764300134545ustar00rootroot00000000000000lua-mode-20210802/.travis.yml000066400000000000000000000014321410202764300155650ustar00rootroot00000000000000dist: xenial language: minimal sudo: no addons: apt: packages: - lua5.2 homebrew: update: true packages: - lua env: - EVM_EMACS=emacs-git-snapshot-travis-linux-xenial - EVM_EMACS=emacs-26.2-travis-linux-xenial - EVM_EMACS=emacs-26.1-travis-linux-xenial - EVM_EMACS=emacs-25.3-travis - EVM_EMACS=emacs-25.2-travis - EVM_EMACS=emacs-25.1-travis - EVM_EMACS=emacs-24.5-travis - EVM_EMACS=emacs-24.4-travis - EVM_EMACS=emacs-24.3-travis jobs: include: - os: osx env: - EVM_EMACS=emacs-26.1-travis matrix: allow_failures: - env: EVM_EMACS=emacs-git-snapshot-travis-linux-xenial fast_finish: true before_install: - source ./travis/before-install.sh install: - cask install script: - echo 'print(123)' | lua -i - make test lua-mode-20210802/AUTHORS000066400000000000000000000026061410202764300145300ustar00rootroot00000000000000Thanks to: - Thanks to xristos for subprocess buffer handling fixes (tiny change) - Thanks to Juergen Fuhrmann (tiny change) - Thanks to guoxx for imenu expression extension (tiny change). - Vedat Hallac for sharing some of his fixes and updates to core indentation logics. - Julien Danjou for a patch deriving lua-mode from prog-mode with define-derived-mode - Rafael Sanchez for patch adding lua-mode to interpreter-mode-alist. - Thanks to Leonardo Etcheverry for enabling narrow-to-defun and fixing lua-send-defun. - Thanks to Tobias Polzin for function indenting patch: Indent "(" like "{". - Thanks to Fabien for imenu patches. - Thanks to Simon Marshall and Olivier Andrieu for font-lock patches. - Additional font-lock highlighting and indentation tweaks by Adam D. Moss . - Juergen Hoetzel for hard work maintaining lua-mode during 2006 -- 2010. - Reuben Thomas for hard work maintaining lua-mode during 2010 -- 2011. - Rolando Pereira for adding support for goto keyword Ideas: - thanks to d87 for an idea of highlighting lua builtins lua-mode-20210802/COPYING000066400000000000000000000432541410202764300145170ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. lua-mode-20210802/Cask000066400000000000000000000003141410202764300142560ustar00rootroot00000000000000(source melpa) (source gnu) (package "lua-mode" "dev" "Major mode for editing Lua") (development (depends-on "buttercup" "1.9") (depends-on "cl-lib")) ;; Local Variables: ;; mode: emacs-lisp ;; End: lua-mode-20210802/Makefile000066400000000000000000000031701410202764300151150ustar00rootroot00000000000000# Makefile for lua-mode VERSION="$(shell sed -nre '/^;; Version:/ { s/^;; Version:[ \t]+//; p }' lua-mode.el)" DISTFILE = lua-mode-$(VERSION).zip # EMACS value may be overridden EMACS?=emacs EMACS_MAJOR_VERSION=$(shell $(EMACS) -batch -eval '(princ emacs-major-version)') LUA_MODE_ELC=lua-mode.$(EMACS_MAJOR_VERSION).elc EMACS_BATCH=$(EMACS) --batch -Q default: @echo version is $(VERSION) %.$(EMACS_MAJOR_VERSION).elc: %.elc mv $< $@ %.elc: %.el $(EMACS_BATCH) -f batch-byte-compile $< compile: $(LUA_MODE_ELC) dist: rm -f $(DISTFILE) && \ git archive --format=zip -o $(DISTFILE) --prefix=lua-mode/ HEAD .PHONY: test-compiled-nocask test-uncompiled-nocask test-compiled test-uncompiled # check both regular and compiled versions test-nocask: test-compiled-nocask test-uncompiled-nocask test: test-compiled test-uncompiled test-compiled-nocask: $(LUA_MODE_ELC) $(EMACS) -batch -l $(LUA_MODE_ELC) -l buttercup -f buttercup-run-discover test-uncompiled-nocask: $(EMACS) -batch -l lua-mode.el -l buttercup -f buttercup-run-discover test-compiled: $(LUA_MODE_ELC) EMACS=$(EMACS) cask exec buttercup -l $(LUA_MODE_ELC) test-uncompiled: EMACS=$(EMACS) cask exec buttercup -l lua-mode.el tryout: cask exec $(EMACS) -Q -l init-tryout.el test.lua tryout-nocask: $(EMACS) -Q -l init-tryout.el test.lua release: git fetch && \ git diff remotes/origin/master --exit-code && \ git tag -a -m "Release tag" rel-$(VERSION) && \ woger lua-l lua-mode lua-mode "release $(VERSION)" "Emacs major mode for editing Lua files" release-notes-$(VERSION) http://github.com/immerrr/lua-mode/ && \ git push origin master @echo 'Send update to ELPA!' lua-mode-20210802/NEWS000066400000000000000000000071531410202764300141610ustar00rootroot00000000000000* Release v20151025 ** allow setting lua-indent-level as file local variable (issue #108) ** add luadoc keyword fontification (issue #71) ** fix comments being spilled into the code (issue #25) ** add `run-lua' alias for `lua-start-process' (issue #97) ** skip shebang line when sending to inferior buffer (issue #61) ** add builtin functions and modules for Lua 5.3 (issue #90) ** fix lua-beginning-of-proc matching (issue #85) ** add `lua-documentation-function' to customize the way the documentation is shown, rename `lua-search-url-prefix' to `lua-documentation-url', auto-detect lua documentation installed in /usr/share/doc/lua (issue #82) ** fix some errors with `lua-kill-process' (issue #69) ** improve `next-error' integration in Lua subprocess buffer: "stdin:N:" entries are no longer highlighted and no longer prompt for "stdin" files * release v20140514 ** add support for Lua 5.2 goto statements ** when indenting, don't anchor to block-open tokens somefunc({ ^ don't indent next line relative to this brace ** fix several `indent-new-comment-line'-related bugs ** add support for local functions in imenu (issue #65) ** fix font lock of functions with underscores (issue #63) ** don't send shebang when sending lua buffer to subprocess (issue #61) ** fix interaction with electric-pair-mode (issue #54) ** rewrite lua-send-region to use "loadstring" rather than "dofile" - sending code to processes on remote hosts is now supported - stack traces for errors occurred in sent code point to proper lines in files - script path is preserved when sending code (issue #55) - no more hang ups when waiting for input (issue #48) or after sending code with no output (issue #60) ** increase consistency with Emacs ecosystem to improve user experience - fix character syntax hacks: '.' is now punctuation and '_' is now symbol - remove number highlighting - font-lock "nil", "true" and "false" as constants rather than keywords ** make builtin font-locking more stable, enable it after ".." operator ** add missing modulo operator (%) to line-continuation tokens ** fix interaction with electric-pair-mode (issue #54) ** when unindenting block-close tokens consider all of them, not just the first one x = foobar('arg1', function () print('foobar') end) ^ this line starts with two block-close tokens and is unindented accordingly * Release rel-20130419 ** highlight hash-bang line as comment ** make lua-mode-hook editable via customize ** fix several indentation bugs & quirks ** fix lua-send-proc not to send previous function when point is at the beginning of a function ** derive lua-mode from prog-mode for Emacs24 ** add font-locking for builtins and numeric constants ** fix a bug causing exponential complexity in a keyword matching regexp ** add more unindentation cases for block-closing tokens ** improve multiline highlighting via font-lock-syntactic-keywords This should make font-locking of multiline literals more fluent & stable. And it becomes customizable via standard font-lock configuration ** properly fontify variable definitions in 'local ...' & 'for ...' Also, perform some basic syntax verification in those lines. Multi-line constructs not supported yet. ** fix indentation for blocks starting on continued lines local foo = { bar, baz } ^ 1. these lines should be indented properly now ^ 2. the following lines should be unindented properly now ** extend imenu-generic-expression Now it matches 'foo = function(...)' function definitions lua-mode-20210802/README000066400000000000000000000005061410202764300143350ustar00rootroot00000000000000Lua-mode ======== Maintainer: immerrr lua-mode is an Emacs major mode for editing Lua files. For documentation, including installation instructions, please see lua-mode.el. Please send bug reports and suggestions to the maintainer, or use the trackers at github: http://github.com/immerrr/lua-mode lua-mode-20210802/README.md000066400000000000000000000114401410202764300147330ustar00rootroot00000000000000# Lua mode [![Build Status](https://travis-ci.org/immerrr/lua-mode.svg?branch=master)](https://travis-ci.org/immerrr/lua-mode) [![MELPA](https://melpa.org/packages/lua-mode-badge.svg)](https://melpa.org/#/lua-mode) [![MELPA Stable](https://stable.melpa.org/packages/lua-mode-badge.svg)](https://stable.melpa.org/#/lua-mode) **lua-mode** is a major mode for editing Lua sources in Emacs. If you have a problem or a suggestion about **lua-mode**, please, let me know about it via github's [Issue Tracker](https://github.com/immerrr/lua-mode/issues). ## INSTALLATION ### MELPA INSTALLATION **lua-mode**'s officially supported installation method is from [MELPA](https://melpa.org/#/) archive. To get started, enable installing packages from MELPA: ```lisp (require 'package) (add-to-list 'package-archives '("melpa" . "https://melpa.org/packages/") t) (package-initialize) ``` To fetch the list of packages you can do ``` package-refresh-contents ``` And after that **lua-mode** can be installed with ``` package-install "lua-mode" ``` Please, refer to [MELPA documentation](https://melpa.org/#/getting-started) and [Emacs documentation on packages](https://www.gnu.org/software/emacs/manual/html_node/emacs/Packages.html) for further information. ### EL-GET INSTALLATION [El-get](https://github.com/dimitri/el-get) is a package manager which greatly simplifies adding modules to your Emacs and keeping them up-to-date. Once you have **el-get** set up, **lua-mode** can also be installed with el-get-install "lua-mode" and updating is no more than el-get-update "lua-mode" Please, consult with [el-get documentation](https://github.com/dimitri/el-get/blob/master/README.md) for further information. ### MANUAL INSTALLATION To install, you need to make sure that `lua-mode.el` is on your load-path (and optionally byte-compile it) and to set up Emacs to automatically enable **lua-mode** for `*.lua` files or ones that contain lua hash-bang line (`#!/usr/bin/lua`). Putting this snippet to `.emacs` should be enough in most cases: ```lisp ;;;; This snippet enables lua-mode ;; This line is not necessary, if lua-mode.el is already on your load-path (add-to-list 'load-path "/path/to/directory/where/lua-mode-el/resides") (autoload 'lua-mode "lua-mode" "Lua editing mode." t) (add-to-list 'auto-mode-alist '("\\.lua$" . lua-mode)) (add-to-list 'interpreter-mode-alist '("lua" . lua-mode)) ``` ## FEATURES - syntactic indentation & highlighting (including multiline literals/comments) - evaluation of lines/regions/functions/files in Lua subprocess or direct interaction with its REPL - documentation lookup (using online/offline reference manual, e.g. [string.find](http://www.lua.org/manual/5.1/manual.html#pdf-string.find)) - [imenu](http://www.gnu.org/software/emacs/manual/html_node/emacs/Imenu.html) integration - [HideShow](http://www.gnu.org/software/emacs/manual/html_node/emacs/Hideshow.html) integration ## CUSTOMIZATION The following variables are available for customization (see more via `M-x customize-group lua`): - Var `lua-indent-level` (default `3`): indentation offset in spaces - Var `lua-indent-string-contents` (default `nil`): set to `t` if you like to have contents of multiline strings to be indented like comments - Var `lua-indent-nested-block-content-align` (default `t`) set to `nil` to stop aligning the content of nested blocks with the open parenthesis - Var `lua-indent-close-paren-align` (default `t`) set to `t` to align close parenthesis with the open parenthesis rather than with the beginning of the line - Var `lua-mode-hook`: list of functions to execute when lua-mode is initialized - Var `lua-documentation-url` (default `"http://www.lua.org/manual/5.1/manual.html#pdf-"`): base URL for documentation lookup - Var `lua-documentation-function` (default `browse-url`): function used to show documentation (`eww` is a viable alternative for Emacs 25) ## LUA SUBPROCESS CREATION - Var `lua-default-application` (default `"lua"`): command to start up the subprocess (REPL) - Var `lua-default-command-switches` (default `"-i"`): arguments to pass to the subprocess on startup (make sure `-i` is there if you expect working with Lua shell interactively) - Cmd `lua-start-process`: start new REPL process, usually happens automatically - Cmd `lua-kill-process`: kill current REPL process ## LUA SUBPROCESS INTERACTION - Cmd `lua-show-process-buffer`: switch to REPL buffer - Cmd `lua-hide-process-buffer`: hide window showing REPL buffer - Var `lua-always-show`: show REPL buffer after sending something - Cmd `lua-send-buffer`: send whole buffer - Cmd `lua-send-current-line`: send current line - Cmd `lua-send-defun`: send current top-level function - Cmd `lua-send-region`: send active region - Cmd `lua-restart-with-whole-file`: restart REPL and send whole buffer lua-mode-20210802/TODO000066400000000000000000000054631410202764300141540ustar00rootroot00000000000000# -*- mode: org -*- #+PROPERTY: COOKIE_DATA todo recursive * Useful resources - Lua5.1 - [[http://www.lua.org/manual/5.1/manual.html#8][bnf syntax]] - [[http://www.lua.org/manual/5.1/index.html#index][function index]] - Lua5.2 - [[http://www.lua.org/manual/5.2/manual.html#9][syntax]] - [[http://www.lua.org/manual/5.2/#index][function index]] * TODO Fontify function parameters as variable names * TODO Fontify variable names in line-continuation statements - local foo,bar,baz = xyz,xyyz,xyyz - function xyzzy( foo, bar, baz ) * TODO left-shift parenthesis that closes function parameter block local foobar = function( param1, param2, param3 ) dosmth() end * TODO issue #33 a = { } b = { } * TODO finish works in lua-compat branch for Emacs21/Emacs22 * TODO put text property 'lua-last-stmt-begin - continuation-line detection becomes a one-liner - multiline fontification becomes easier - beginning-of-defun is a one-liner - if property value is a marker, it will get updated on each edit, that's not necessary and might cause performance impact - if property value is an integer, it needs to be updated before use 1. `buffer-access-fontify-functions' / `buffer-access-fontified-property' 2. maintain `stmt-begin-up-to-date-pos' point - after-change function sets `stmt-begin-up-to-date-pos' to (line-beginning-position) - (defun get-stmt-beginning-pos (pos) ...) - (when (< stmt-begin-up-to-date-pos pos) ... (setq stmt-begin-up-to-date-pos pos)) - return property at position pos * TODO Support line-continuation statements [0/2] - [ ] assignments x,y = long_value, other_long_value - [ ] `for ... do' operators * TODO update site [0/2] ** TODO reuse section-aware template ** TODO add section for release downloading * TODO [#C] Improve lua-prefix-key machinery [0/2] - [ ] add docs - [ ] improve setting prefix-key Currently, prefix-key is parsed from a macro string (which may contain more than one key) and all keys but the first one are silently removed. Maybe there's a better way to do it. * DONE Fix braces/parens that reduce indent by const offset this causes wrong behavior when indented block was anchored to first line, e.g. my_func( hello, world ) * DONE lua-mark-all-multiline-literals [5/5] - [X] process --[[ as multiline comment - [X] process ---[[ as single-line comment distinguish by syntax state of last dash before square bracket - [X] don't recognize [[ in comments or literals - [X] extend region backwards if BEGIN is inside multiline literal - [X] don't change buffer-modified-p state * TODO [#C] Redo syntax engine using semantic/wisent lua-mode-20210802/init-tryout.el000066400000000000000000000007061410202764300163100ustar00rootroot00000000000000(load-file "lua-mode.el") (defmacro add-trace-for (fn) (let ((trace-fn-name (intern (concat "trace--" (symbol-name fn))))) `(progn (defun ,trace-fn-name (&rest args) (message "%s was called with: %S" #',fn args)) (add-function :before (symbol-function #',fn) #',trace-fn-name)))) ;; (add-trace-for font-lock-fontify-region) ;; (add-trace-for font-lock-unfontify-region) ;; (add-trace-for lua--propertize-multiline-bounds) lua-mode-20210802/lua-mode.el000066400000000000000000002600071410202764300155060ustar00rootroot00000000000000;;; lua-mode.el --- a major-mode for editing Lua scripts -*- lexical-binding: t -*- ;; Author: 2011-2013 immerrr ;; 2010-2011 Reuben Thomas ;; 2006 Juergen Hoetzel ;; 2004 various (support for Lua 5 and byte compilation) ;; 2001 Christian Vogler ;; 1997 Bret Mogilefsky starting from ;; tcl-mode by Gregor Schmid ;; with tons of assistance from ;; Paul Du Bois and ;; Aaron Smith . ;; ;; URL: http://immerrr.github.com/lua-mode ;; Version: 20210802 ;; Package-Requires: ((emacs "24.3")) ;; ;; This file is NOT part of Emacs. ;; ;; This program is free software; you can redistribute it and/or ;; modify it under the terms of the GNU General Public License ;; as published by the Free Software Foundation; either version 2 ;; of the License, or (at your option) any later version. ;; ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with this program; if not, write to the Free Software ;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ;; MA 02110-1301, USA. ;; Keywords: languages, processes, tools ;; This field is expanded to commit SHA and commit date during the ;; archive creation. ;; Revision: 7ee3feb (Mon, 2 Aug 2021 19:47:15 +0200) ;; ;;; Commentary: ;; lua-mode provides support for editing Lua, including automatic ;; indentation, syntactical font-locking, running interactive shell, ;; interacting with `hs-minor-mode' and online documentation lookup. ;; The following variables are available for customization (see more via ;; `M-x customize-group lua`): ;; - Var `lua-indent-level': ;; indentation offset in spaces ;; - Var `lua-indent-string-contents': ;; set to `t` if you like to have contents of multiline strings to be ;; indented like comments ;; - Var `lua-indent-nested-block-content-align': ;; set to `nil' to stop aligning the content of nested blocks with the ;; open parenthesis ;; - Var `lua-indent-close-paren-align': ;; set to `t' to align close parenthesis with the open parenthesis, ;; rather than with the beginning of the line ;; - Var `lua-mode-hook': ;; list of functions to execute when lua-mode is initialized ;; - Var `lua-documentation-url': ;; base URL for documentation lookup ;; - Var `lua-documentation-function': function used to ;; show documentation (`eww` is a viable alternative for Emacs 25) ;; These are variables/commands that operate on the Lua process: ;; - Var `lua-default-application': ;; command to start the Lua process (REPL) ;; - Var `lua-default-command-switches': ;; arguments to pass to the Lua process on startup (make sure `-i` is there ;; if you expect working with Lua shell interactively) ;; - Cmd `lua-start-process': start new REPL process, usually happens automatically ;; - Cmd `lua-kill-process': kill current REPL process ;; These are variables/commands for interaction with the Lua process: ;; - Cmd `lua-show-process-buffer': switch to REPL buffer ;; - Cmd `lua-hide-process-buffer': hide window showing REPL buffer ;; - Var `lua-always-show': show REPL buffer after sending something ;; - Cmd `lua-send-buffer': send whole buffer ;; - Cmd `lua-send-current-line': send current line ;; - Cmd `lua-send-defun': send current top-level function ;; - Cmd `lua-send-region': send active region ;; - Cmd `lua-restart-with-whole-file': restart REPL and send whole buffer ;; See "M-x apropos-command ^lua-" for a list of commands. ;; See "M-x customize-group lua" for a list of customizable variables. ;;; Code: (eval-when-compile (require 'cl-lib)) (require 'comint) (require 'newcomment) (require 'rx) ;; rx-wrappers for Lua (eval-when-compile ;; Silence compilation warning about `compilation-error-regexp-alist' defined ;; in compile.el. (require 'compile)) (eval-and-compile (if (fboundp #'rx-let) (progn ;; Emacs 27+ way of customizing rx (defvar lua--rx-bindings) (setq lua--rx-bindings '((symbol (&rest x) (seq symbol-start (or x) symbol-end)) (ws (* (any " \t"))) (ws+ (+ (any " \t"))) (lua-name (symbol (seq (+ (any alpha "_")) (* (any alnum "_"))))) (lua-funcname (seq lua-name (* ws "." ws lua-name) (opt ws ":" ws lua-name))) (lua-funcheader ;; Outer (seq ...) is here to shy-group the definition (seq (or (seq (symbol "function") ws (group-n 1 lua-funcname)) (seq (group-n 1 lua-funcname) ws "=" ws (symbol "function"))))) (lua-number (seq (or (seq (+ digit) (opt ".") (* digit)) (seq (* digit) (opt ".") (+ digit))) (opt (regexp "[eE][+-]?[0-9]+")))) (lua-assignment-op (seq "=" (or buffer-end (not (any "="))))) (lua-operator (or "+" "-" "*" "/" "%" "^" "#" "==" "~=" "<=" ">=" "<" ">" "=" ";" ":" "," "." ".." "...")) (lua-keyword-operator (symbol "and" "not" "or")) (lua-keyword (symbol "break" "do" "else" "elseif" "end" "for" "function" "goto" "if" "in" "local" "repeat" "return" "then" "until" "while")) (lua-up-to-9-variables (seq (group-n 1 lua-name) ws (? "," ws (group-n 2 lua-name) ws (? "," ws (group-n 3 lua-name) ws (? "," ws (group-n 4 lua-name) ws (? "," ws (group-n 5 lua-name) ws (? "," ws (group-n 6 lua-name) ws (? "," ws (group-n 7 lua-name) ws (? "," ws (group-n 8 lua-name) ws (? "," ws (group-n 9 lua-name) ws)))))))))))) (defmacro lua-rx (&rest regexps) (eval `(rx-let ,lua--rx-bindings (rx ,@regexps)))) (defun lua-rx-to-string (form &optional no-group) (rx-let-eval lua--rx-bindings (rx-to-string form no-group)))) (progn ;; Pre-Emacs 27 way of customizing rx (defvar lua-rx-constituents) (defvar rx-parent) (defun lua-rx-to-string (form &optional no-group) "Lua-specific replacement for `rx-to-string'. See `rx-to-string' documentation for more information FORM and NO-GROUP arguments." (let ((rx-constituents lua-rx-constituents)) (rx-to-string form no-group))) (defmacro lua-rx (&rest regexps) "Lua-specific replacement for `rx'. See `rx' documentation for more information about REGEXPS param." (cond ((null regexps) (error "No regexp")) ((cdr regexps) (lua-rx-to-string `(and ,@regexps) t)) (t (lua-rx-to-string (car regexps) t)))) (defun lua--new-rx-form (form) "Add FORM definition to `lua-rx' macro. FORM is a cons (NAME . DEFN), see more in `rx-constituents' doc. This function enables specifying new definitions using old ones: if DEFN is a list that starts with `:rx' symbol its second element is itself expanded with `lua-rx-to-string'. " (let ((form-definition (cdr form))) (when (and (listp form-definition) (eq ':rx (car form-definition))) (setcdr form (lua-rx-to-string (cadr form-definition) 'nogroup))) (push form lua-rx-constituents))) (defun lua--rx-symbol (form) ;; form is a list (symbol XXX ...) ;; Skip initial 'symbol (setq form (cdr form)) ;; If there's only one element, take it from the list, otherwise wrap the ;; whole list into `(or XXX ...)' form. (setq form (if (eq 1 (length form)) (car form) (append '(or) form))) (and (fboundp 'rx-form) ; Silence Emacs 27's byte-compiler. (rx-form `(seq symbol-start ,form symbol-end) rx-parent))) (setq lua-rx-constituents (copy-sequence rx-constituents)) (mapc 'lua--new-rx-form `((symbol lua--rx-symbol 1 nil) (ws . "[ \t]*") (ws+ . "[ \t]+") (lua-name :rx (symbol (regexp "[[:alpha:]_]+[[:alnum:]_]*"))) (lua-funcname :rx (seq lua-name (* ws "." ws lua-name) (opt ws ":" ws lua-name))) (lua-funcheader ;; Outer (seq ...) is here to shy-group the definition :rx (seq (or (seq (symbol "function") ws (group-n 1 lua-funcname)) (seq (group-n 1 lua-funcname) ws "=" ws (symbol "function"))))) (lua-number :rx (seq (or (seq (+ digit) (opt ".") (* digit)) (seq (* digit) (opt ".") (+ digit))) (opt (regexp "[eE][+-]?[0-9]+")))) (lua-assignment-op :rx (seq "=" (or buffer-end (not (any "="))))) (lua-operator :rx (or "+" "-" "*" "/" "%" "^" "#" "==" "~=" "<=" ">=" "<" ">" "=" ";" ":" "," "." ".." "...")) (lua-keyword-operator :rx (symbol "and" "not" "or")) (lua-keyword :rx (symbol "break" "do" "else" "elseif" "end" "for" "function" "goto" "if" "in" "local" "repeat" "return" "then" "until" "while")) (lua-up-to-9-variables :rx (seq (group-n 1 lua-name) ws (? "," ws (group-n 2 lua-name) ws (? "," ws (group-n 3 lua-name) ws (? "," ws (group-n 4 lua-name) ws (? "," ws (group-n 5 lua-name) ws (? "," ws (group-n 6 lua-name) ws (? "," ws (group-n 7 lua-name) ws (? "," ws (group-n 8 lua-name) ws (? "," ws (group-n 9 lua-name) ws))))))))))))))) ;; Local variables (defgroup lua nil "Major mode for editing Lua code." :prefix "lua-" :group 'languages) (defcustom lua-indent-level 3 "Amount by which Lua subexpressions are indented." :type 'integer :group 'lua :safe #'integerp) (defcustom lua-comment-start "-- " "Default value of `comment-start'." :type 'string :group 'lua) (defcustom lua-comment-start-skip "---*[ \t]*" "Default value of `comment-start-skip'." :type 'string :group 'lua) (defcustom lua-default-application "lua" "Default application to run in Lua process. Can be a string, where it denotes a command to be executed to start Lua process, or a (HOST . PORT) cons, that can be used to connect to Lua process running remotely." :type '(choice (string) (cons string integer)) :group 'lua) (defcustom lua-default-command-switches (list "-i") "Command switches for `lua-default-application'. Should be a list of strings." :type '(repeat string) :group 'lua) (make-variable-buffer-local 'lua-default-command-switches) (defcustom lua-always-show t "*Non-nil means display lua-process-buffer after sending a command." :type 'boolean :group 'lua) (defcustom lua-documentation-function 'browse-url "Function used to fetch the Lua reference manual." :type `(radio (function-item browse-url) ,@(when (fboundp 'eww) '((function-item eww))) ,@(when (fboundp 'w3m-browse-url) '((function-item w3m-browse-url))) (function :tag "Other function")) :group 'lua) (defcustom lua-documentation-url (or (and (file-readable-p "/usr/share/doc/lua/manual.html") "file:///usr/share/doc/lua/manual.html") "http://www.lua.org/manual/5.1/manual.html") "URL pointing to the Lua reference manual." :type 'string :group 'lua) (defvar lua-process nil "The active Lua process") (defvar lua-process-buffer nil "Buffer used for communication with the Lua process.") (defun lua--customize-set-prefix-key (prefix-key-sym prefix-key-val) (cl-assert (eq prefix-key-sym 'lua-prefix-key)) (set prefix-key-sym (if (and prefix-key-val (> (length prefix-key-val) 0)) ;; read-kbd-macro returns a string or a vector ;; in both cases (elt x 0) is ok (elt (read-kbd-macro prefix-key-val) 0))) (if (fboundp 'lua-prefix-key-update-bindings) (lua-prefix-key-update-bindings))) (defcustom lua-prefix-key "\C-c" "Prefix for all lua-mode commands." :type 'string :group 'lua :set 'lua--customize-set-prefix-key :get '(lambda (sym) (let ((val (eval sym))) (if val (single-key-description (eval sym)) "")))) (defvar lua-mode-menu (make-sparse-keymap "Lua") "Keymap for lua-mode's menu.") (defvar lua-prefix-mode-map (eval-when-compile (let ((result-map (make-sparse-keymap))) (mapc (lambda (key_defn) (define-key result-map (read-kbd-macro (car key_defn)) (cdr key_defn))) '(("C-l" . lua-send-buffer) ("C-f" . lua-search-documentation))) result-map)) "Keymap that is used to define keys accessible by `lua-prefix-key'. If the latter is nil, the keymap translates into `lua-mode-map' verbatim.") (defvar lua--electric-indent-chars (mapcar #'string-to-char '("}" "]" ")"))) (defvar lua-mode-map (let ((result-map (make-sparse-keymap))) (unless (boundp 'electric-indent-chars) (mapc (lambda (electric-char) (define-key result-map (read-kbd-macro (char-to-string electric-char)) #'lua-electric-match)) lua--electric-indent-chars)) (define-key result-map [menu-bar lua-mode] (cons "Lua" lua-mode-menu)) (define-key result-map [remap backward-up-list] 'lua-backward-up-list) ;; handle prefix-keyed bindings: ;; * if no prefix, set prefix-map as parent, i.e. ;; if key is not defined look it up in prefix-map ;; * if prefix is set, bind the prefix-map to that key (if lua-prefix-key (define-key result-map (vector lua-prefix-key) lua-prefix-mode-map) (set-keymap-parent result-map lua-prefix-mode-map)) result-map) "Keymap used in lua-mode buffers.") (defvar lua-electric-flag t "If t, electric actions (like automatic reindentation) will happen when an electric key like `{' is pressed") (make-variable-buffer-local 'lua-electric-flag) (defcustom lua-prompt-regexp "[^\n]*\\(>[\t ]+\\)+$" "Regexp which matches the Lua program's prompt." :type 'regexp :group 'lua) (defcustom lua-traceback-line-re ;; This regexp skips prompt and meaningless "stdin:N:" prefix when looking ;; for actual file-line locations. "^\\(?:[\t ]*\\|.*>[\t ]+\\)\\(?:[^\n\t ]+:[0-9]+:[\t ]*\\)*\\(?:\\([^\n\t ]+\\):\\([0-9]+\\):\\)" "Regular expression that describes tracebacks and errors." :type 'regexp :group 'lua) (defvar lua--repl-buffer-p nil "Buffer-local flag saying if this is a Lua REPL buffer.") (make-variable-buffer-local 'lua--repl-buffer-p) (defadvice compilation-find-file (around lua--repl-find-file (marker filename directory &rest formats) activate) "Return Lua REPL buffer when looking for \"stdin\" file in it." (if (and lua--repl-buffer-p (string-equal filename "stdin") ;; NOTE: this doesn't traverse `compilation-search-path' when ;; looking for filename. (not (file-exists-p (expand-file-name filename (when directory (expand-file-name directory)))))) (setq ad-return-value (current-buffer)) ad-do-it)) (defadvice compilation-goto-locus (around lua--repl-goto-locus (msg mk end-mk) activate) "When message points to Lua REPL buffer, go to the message itself. Usually, stdin:XX line number points to nowhere." (let ((errmsg-buf (marker-buffer msg)) (error-buf (marker-buffer mk))) (if (and (with-current-buffer errmsg-buf lua--repl-buffer-p) (eq error-buf errmsg-buf)) (progn (compilation-set-window (display-buffer (marker-buffer msg)) msg) (goto-char msg)) ad-do-it))) (defcustom lua-indent-string-contents nil "If non-nil, contents of multiline string will be indented. Otherwise leading amount of whitespace on each line is preserved." :group 'lua :type 'boolean :safe #'booleanp) (defcustom lua-indent-nested-block-content-align t "If non-nil, the contents of nested blocks are indented to align with the column of the opening parenthesis, rather than just forward by `lua-indent-level'." :group 'lua :type 'boolean :safe #'booleanp) (defcustom lua-indent-close-paren-align t "If non-nil, close parenthesis are aligned with their open parenthesis. If nil, close parenthesis are aligned to the beginning of the line." :group 'lua :type 'boolean :safe #'booleanp) (defcustom lua-jump-on-traceback t "*Jump to innermost traceback location in *lua* buffer. When this variable is non-nil and a traceback occurs when running Lua code in a process, jump immediately to the source code of the innermost traceback location." :type 'boolean :group 'lua) (defcustom lua-mode-hook nil "Hooks called when Lua mode fires up." :type 'hook :group 'lua) (defvar lua-region-start (make-marker) "Start of special region for Lua communication.") (defvar lua-region-end (make-marker) "End of special region for Lua communication.") (defvar lua-emacs-menu '(["Restart With Whole File" lua-restart-with-whole-file t] ["Kill Process" lua-kill-process t] ["Hide Process Buffer" lua-hide-process-buffer t] ["Show Process Buffer" lua-show-process-buffer t] ["Beginning Of Proc" lua-beginning-of-proc t] ["End Of Proc" lua-end-of-proc t] ["Set Lua-Region Start" lua-set-lua-region-start t] ["Set Lua-Region End" lua-set-lua-region-end t] ["Send Lua-Region" lua-send-lua-region t] ["Send Current Line" lua-send-current-line t] ["Send Region" lua-send-region t] ["Send Proc" lua-send-proc t] ["Send Buffer" lua-send-buffer t] ["Search Documentation" lua-search-documentation t]) "Emacs menu for Lua mode.") ;; the whole defconst is inside eval-when-compile, because it's later referenced ;; inside another eval-and-compile block (eval-and-compile (defconst lua--builtins (let* ((modules '("_G" "_VERSION" "assert" "collectgarbage" "dofile" "error" "getfenv" "getmetatable" "ipairs" "load" "loadfile" "loadstring" "module" "next" "pairs" "pcall" "print" "rawequal" "rawget" "rawlen" "rawset" "require" "select" "setfenv" "setmetatable" "tonumber" "tostring" "type" "unpack" "xpcall" "self" ("bit32" . ("arshift" "band" "bnot" "bor" "btest" "bxor" "extract" "lrotate" "lshift" "replace" "rrotate" "rshift")) ("coroutine" . ("create" "isyieldable" "resume" "running" "status" "wrap" "yield")) ("debug" . ("debug" "getfenv" "gethook" "getinfo" "getlocal" "getmetatable" "getregistry" "getupvalue" "getuservalue" "setfenv" "sethook" "setlocal" "setmetatable" "setupvalue" "setuservalue" "traceback" "upvalueid" "upvaluejoin")) ("io" . ("close" "flush" "input" "lines" "open" "output" "popen" "read" "stderr" "stdin" "stdout" "tmpfile" "type" "write")) ("math" . ("abs" "acos" "asin" "atan" "atan2" "ceil" "cos" "cosh" "deg" "exp" "floor" "fmod" "frexp" "huge" "ldexp" "log" "log10" "max" "maxinteger" "min" "mininteger" "modf" "pi" "pow" "rad" "random" "randomseed" "sin" "sinh" "sqrt" "tan" "tanh" "tointeger" "type" "ult")) ("os" . ("clock" "date" "difftime" "execute" "exit" "getenv" "remove" "rename" "setlocale" "time" "tmpname")) ("package" . ("config" "cpath" "loaded" "loaders" "loadlib" "path" "preload" "searchers" "searchpath" "seeall")) ("string" . ("byte" "char" "dump" "find" "format" "gmatch" "gsub" "len" "lower" "match" "pack" "packsize" "rep" "reverse" "sub" "unpack" "upper")) ("table" . ("concat" "insert" "maxn" "move" "pack" "remove" "sort" "unpack")) ("utf8" . ("char" "charpattern" "codepoint" "codes" "len" "offset"))))) (cl-labels ((module-name-re (x) (concat "\\(?1:\\_<" (if (listp x) (car x) x) "\\_>\\)")) (module-members-re (x) (if (listp x) (concat "\\(?:[ \t]*\\.[ \t]*" "\\_<\\(?2:" (regexp-opt (cdr x)) "\\)\\_>\\)?") ""))) (concat ;; common prefix: ;; - beginning-of-line ;; - or neither of [ '.', ':' ] to exclude "foo.string.rep" ;; - or concatenation operator ".." "\\(?:^\\|[^:. \t]\\|[.][.]\\)" ;; optional whitespace "[ \t]*" "\\(?:" ;; any of modules/functions (mapconcat (lambda (x) (concat (module-name-re x) (module-members-re x))) modules "\\|") "\\)")))) "A regexp that matches Lua builtin functions & variables. This is a compilation of 5.1, 5.2 and 5.3 builtins taken from the index of respective Lua reference manuals.") (defvar lua-font-lock-keywords `(;; highlight the hash-bang line "#!/foo/bar/lua" as comment ("^#!.*$" . font-lock-comment-face) ;; Builtin constants (,(lua-rx (symbol "true" "false" "nil")) . font-lock-constant-face) ;; Keywords (,(lua-rx (or lua-keyword lua-keyword-operator)) . font-lock-keyword-face) ;; Labels used by the "goto" statement ;; Highlights the following syntax: ::label:: (,(lua-rx "::" ws lua-name ws "::") . font-lock-constant-face) ;; Highlights the name of the label in the "goto" statement like ;; "goto label" (,(lua-rx (symbol (seq "goto" ws+ (group-n 1 lua-name)))) (1 font-lock-constant-face)) ;; Highlight Lua builtin functions and variables (,lua--builtins (1 font-lock-builtin-face) (2 font-lock-builtin-face nil noerror)) (,(lua-rx (symbol "for") ws+ lua-up-to-9-variables) (1 font-lock-variable-name-face) (2 font-lock-variable-name-face nil noerror) (3 font-lock-variable-name-face nil noerror) (4 font-lock-variable-name-face nil noerror) (5 font-lock-variable-name-face nil noerror) (6 font-lock-variable-name-face nil noerror) (7 font-lock-variable-name-face nil noerror) (8 font-lock-variable-name-face nil noerror) (9 font-lock-variable-name-face nil noerror)) (,(lua-rx (symbol "function") (? ws+ lua-funcname) ws "(" ws lua-up-to-9-variables) (1 font-lock-variable-name-face) (2 font-lock-variable-name-face nil noerror) (3 font-lock-variable-name-face nil noerror) (4 font-lock-variable-name-face nil noerror) (5 font-lock-variable-name-face nil noerror) (6 font-lock-variable-name-face nil noerror) (7 font-lock-variable-name-face nil noerror) (8 font-lock-variable-name-face nil noerror) (9 font-lock-variable-name-face nil noerror)) (,(lua-rx lua-funcheader) (1 font-lock-function-name-face)) ;; local x, y, z ;; local x = ..... ;; ;; NOTE: this is intentionally below funcheader matcher, so that in ;; ;; local foo = function() ... ;; ;; "foo" is fontified as function-name-face, and variable-name-face is not applied. (,(lua-rx (symbol "local") ws+ lua-up-to-9-variables) (1 font-lock-variable-name-face) (2 font-lock-variable-name-face nil noerror) (3 font-lock-variable-name-face nil noerror) (4 font-lock-variable-name-face nil noerror) (5 font-lock-variable-name-face nil noerror) (6 font-lock-variable-name-face nil noerror) (7 font-lock-variable-name-face nil noerror) (8 font-lock-variable-name-face nil noerror) (9 font-lock-variable-name-face nil noerror)) (,(lua-rx (or (group-n 1 "@" (symbol "author" "copyright" "field" "release" "return" "see" "usage" "description")) (seq (group-n 1 "@" (symbol "param" "class" "name")) ws+ (group-n 2 lua-name)))) (1 font-lock-keyword-face t) (2 font-lock-variable-name-face t noerror))) "Default expressions to highlight in Lua mode.") (defvar lua-imenu-generic-expression `(("Requires" ,(lua-rx (or bol ";") ws (opt (seq (symbol "local") ws)) (group-n 1 lua-name) ws "=" ws (symbol "require")) 1) (nil ,(lua-rx (or bol ";") ws (opt (seq (symbol "local") ws)) lua-funcheader) 1)) "Imenu generic expression for lua-mode. See `imenu-generic-expression'.") (defvar lua-sexp-alist '(("then" . "end") ("function" . "end") ("do" . "end") ("repeat" . "until"))) (defvar lua-mode-abbrev-table nil "Abbreviation table used in lua-mode buffers.") (define-abbrev-table 'lua-mode-abbrev-table '(("end" "end" lua-indent-line :system t) ("else" "else" lua-indent-line :system t) ("elseif" "elseif" lua-indent-line :system t))) (defvar lua-mode-syntax-table (with-syntax-table (copy-syntax-table) ;; main comment syntax: begins with "--", ends with "\n" (modify-syntax-entry ?- ". 12") (modify-syntax-entry ?\n ">") ;; main string syntax: bounded by ' or " (modify-syntax-entry ?\' "\"") (modify-syntax-entry ?\" "\"") ;; single-character binary operators: punctuation (modify-syntax-entry ?+ ".") (modify-syntax-entry ?* ".") (modify-syntax-entry ?/ ".") (modify-syntax-entry ?^ ".") (modify-syntax-entry ?% ".") (modify-syntax-entry ?> ".") (modify-syntax-entry ?< ".") (modify-syntax-entry ?= ".") (modify-syntax-entry ?~ ".") (syntax-table)) "`lua-mode' syntax table.") ;;;###autoload (define-derived-mode lua-mode prog-mode "Lua" "Major mode for editing Lua code." :abbrev-table lua-mode-abbrev-table :syntax-table lua-mode-syntax-table :group 'lua (setq-local font-lock-defaults '(lua-font-lock-keywords ;; keywords nil ;; keywords-only nil ;; case-fold nil ;; syntax-alist nil ;; syntax-begin )) (setq-local syntax-propertize-function 'lua--propertize-multiline-bounds) (setq-local parse-sexp-lookup-properties t) (setq-local indent-line-function 'lua-indent-line) (setq-local beginning-of-defun-function 'lua-beginning-of-proc) (setq-local end-of-defun-function 'lua-end-of-proc) (setq-local comment-start lua-comment-start) (setq-local comment-start-skip lua-comment-start-skip) (setq-local comment-use-syntax t) (setq-local fill-paragraph-function #'lua--fill-paragraph) (with-no-warnings (setq-local comment-use-global-state t)) (setq-local imenu-generic-expression lua-imenu-generic-expression) (when (boundp 'electric-indent-chars) ;; If electric-indent-chars is not defined, electric indentation is done ;; via `lua-mode-map'. (setq-local electric-indent-chars (append electric-indent-chars lua--electric-indent-chars))) ;; setup menu bar entry (XEmacs style) (if (and (featurep 'menubar) (boundp 'current-menubar) (fboundp 'set-buffer-menubar) (fboundp 'add-menu) (not (assoc "Lua" current-menubar))) (progn (set-buffer-menubar (copy-sequence current-menubar)) (add-menu nil "Lua" lua-emacs-menu))) ;; Append Lua menu to popup menu for Emacs. (if (boundp 'mode-popup-menu) (setq mode-popup-menu (cons (concat mode-name " Mode Commands") lua-emacs-menu))) ;; hideshow setup (unless (assq 'lua-mode hs-special-modes-alist) (add-to-list 'hs-special-modes-alist `(lua-mode ,(regexp-opt (mapcar 'car lua-sexp-alist) 'words) ;start ,(regexp-opt (mapcar 'cdr lua-sexp-alist) 'words) ;end nil lua-forward-sexp)))) ;;;###autoload (add-to-list 'auto-mode-alist '("\\.lua\\'" . lua-mode)) ;;;###autoload (add-to-list 'interpreter-mode-alist '("lua" . lua-mode)) (defun lua-electric-match (arg) "Insert character and adjust indentation." (interactive "P") (let (blink-paren-function) (self-insert-command (prefix-numeric-value arg))) (if lua-electric-flag (lua-indent-line)) (blink-matching-open)) ;; private functions (defun lua--fill-paragraph (&optional justify region) ;; Implementation of forward-paragraph for filling. ;; ;; This function works around a corner case in the following situations: ;; ;; <> ;; -- some very long comment .... ;; some_code_right_after_the_comment ;; ;; If point is at the beginning of the comment line, fill paragraph code ;; would have gone for comment-based filling and done the right thing, but it ;; does not find a comment at the beginning of the empty line before the ;; comment and falls back to text-based filling ignoring comment-start and ;; spilling the comment into the code. (save-excursion (while (and (not (eobp)) (progn (move-to-left-margin) (looking-at paragraph-separate))) (forward-line 1)) (let ((fill-paragraph-handle-comment t)) (fill-paragraph justify region)))) (defun lua-prefix-key-update-bindings () (let (old-cons) (if (eq lua-prefix-mode-map (keymap-parent lua-mode-map)) ;; if prefix-map is a parent, delete the parent (set-keymap-parent lua-mode-map nil) ;; otherwise, look for it among children (if (setq old-cons (rassoc lua-prefix-mode-map lua-mode-map)) (delq old-cons lua-mode-map))) (if (null lua-prefix-key) (set-keymap-parent lua-mode-map lua-prefix-mode-map) (define-key lua-mode-map (vector lua-prefix-key) lua-prefix-mode-map)))) (defun lua-set-prefix-key (new-key-str) "Changes `lua-prefix-key' properly and updates keymaps This function replaces previous prefix-key binding with a new one." (interactive "sNew prefix key (empty string means no key): ") (lua--customize-set-prefix-key 'lua-prefix-key new-key-str) (message "Prefix key set to %S" (single-key-description lua-prefix-key)) (lua-prefix-key-update-bindings)) (defun lua-string-p (&optional pos) "Returns true if the point is in a string." (save-excursion (elt (syntax-ppss pos) 3))) (defun lua--containing-double-hyphen-start-pos () "Return position of the beginning comment delimiter (--). Emacs syntax framework does not consider comment delimiters as part of the comment itself, but for this package it is useful to consider point as inside comment when it is between the two hyphens" (and (eql (char-before) ?-) (eql (char-after) ?-) (1- (point)))) (defun lua-comment-start-pos (&optional parsing-state) "Return position of comment containing current point. If point is not inside a comment, return nil." (unless parsing-state (setq parsing-state (syntax-ppss))) (and ;; Not a string (not (nth 3 parsing-state)) ;; Syntax-based comment (or (and (nth 4 parsing-state) (nth 8 parsing-state)) (lua--containing-double-hyphen-start-pos)))) (defun lua-comment-or-string-p (&optional pos) "Returns true if the point is in a comment or string." (save-excursion (let ((parse-result (syntax-ppss pos))) (or (elt parse-result 3) (lua-comment-start-pos parse-result))))) (defun lua-comment-or-string-start-pos (&optional pos) "Returns start position of string or comment which contains point. If point is not inside string or comment, return nil." (save-excursion (when pos (goto-char pos)) (or (elt (syntax-ppss pos) 8) (lua--containing-double-hyphen-start-pos)))) ;; They're propertized as follows: ;; 1. generic-comment ;; 2. generic-string ;; 3. equals signs (defconst lua-ml-begin-regexp "\\(?:\\(?1:-\\)-\\[\\|\\(?2:\\[\\)\\)\\(?3:=*\\)\\[") (defun lua-try-match-multiline-end (end) "Try to match close-bracket for multiline literal around point. Basically, detect form of close bracket from syntactic information provided at point and re-search-forward to it." (let ((comment-or-string-start-pos (lua-comment-or-string-start-pos))) ;; Is there a literal around point? (and comment-or-string-start-pos ;; It is, check if the literal is a multiline open-bracket (save-excursion (goto-char comment-or-string-start-pos) (looking-at lua-ml-begin-regexp)) ;; Yes it is, look for it matching close-bracket. Close-bracket's ;; match group is determined by match-group of open-bracket. (re-search-forward (format "]%s\\(?%s:]\\)" (match-string-no-properties 3) (if (match-beginning 1) 1 2)) end 'noerror)))) (defun lua-try-match-multiline-begin (limit) "Try to match multiline open-brackets. Find next opening long bracket outside of any string/comment. If none can be found before reaching LIMIT, return nil." (let (last-search-matched) (while ;; This loop will iterate skipping all multiline-begin tokens that are ;; inside strings or comments ending either at EOL or at valid token. (and (setq last-search-matched (re-search-forward lua-ml-begin-regexp limit 'noerror)) ;; Ensure --[[ is not inside a comment or string. ;; ;; This includes "---[[" sequence, in which "--" at the beginning ;; creates a single-line comment, and thus "-[[" is no longer a ;; multi-line opener. ;; ;; XXX: need to ensure syntax-ppss beyond (match-beginning 0) is ;; not calculated, or otherwise we'll need to flush the cache. (lua-comment-or-string-start-pos (match-beginning 0)))) last-search-matched)) (defun lua-match-multiline-literal-bounds (limit) ;; First, close any multiline literal spanning from previous block. This will ;; move the point accordingly so as to avoid double traversal. (or (lua-try-match-multiline-end limit) (lua-try-match-multiline-begin limit))) (defun lua--propertize-multiline-bounds (start end) "Put text properties on beginnings and ends of multiline literals. Intended to be used as a `syntax-propertize-function'." (save-excursion (goto-char start) (while (lua-match-multiline-literal-bounds end) (when (match-beginning 1) (put-text-property (match-beginning 1) (match-end 1) 'syntax-table (string-to-syntax "!"))) (when (match-beginning 2) (put-text-property (match-beginning 2) (match-end 2) 'syntax-table (string-to-syntax "|")))))) (defun lua-indent-line () "Indent current line for Lua mode. Return the amount the indentation changed by." (let (indent (case-fold-search nil) ;; save point as a distance to eob - it's invariant w.r.t indentation (pos (- (point-max) (point)))) (back-to-indentation) (if (lua-comment-or-string-p) (setq indent (lua-calculate-string-or-comment-indentation)) ;; just restore point position (setq indent (max 0 (lua-calculate-indentation)))) (when (not (equal indent (current-column))) (delete-region (line-beginning-position) (point)) (indent-to indent)) ;; If initial point was within line's indentation, ;; position after the indentation. Else stay at same point in text. (if (> (- (point-max) pos) (point)) (goto-char (- (point-max) pos))) indent)) (defun lua-calculate-string-or-comment-indentation () "This function should be run when point at (current-indentation) is inside string" (if (and (lua-string-p) (not lua-indent-string-contents)) ;; if inside string and strings aren't to be indented, return current indentation (current-indentation) ;; At this point, we know that we're inside comment, so make sure ;; close-bracket is unindented like a block that starts after ;; left-shifter. (let ((left-shifter-p (looking-at "\\s *\\(?:--\\)?\\]\\(?1:=*\\)\\]"))) (save-excursion (goto-char (lua-comment-or-string-start-pos)) (+ (current-indentation) (if (and left-shifter-p (looking-at (format "--\\[%s\\[" (match-string-no-properties 1)))) 0 lua-indent-level)))))) (defun lua--signum (x) "Return 1 if X is positive, -1 if negative, 0 if zero." ;; XXX: backport from cl-extras for Emacs24 (cond ((> x 0) 1) ((< x 0) -1) (t 0))) (defun lua--ensure-point-within-limit (limit backward) "Return non-nil if point is within LIMIT going forward. With BACKWARD non-nil, return non-nil if point is within LIMIT going backward. If point is beyond limit, move it onto limit." (if (= (lua--signum (- (point) limit)) (if backward 1 -1)) t (goto-char limit) nil)) (defun lua--escape-from-string (&optional backward) "Move point outside of string if it is inside one. By default, point is placed after the string, with BACKWARD it is placed before the string." (interactive) (let ((parse-state (syntax-ppss))) (when (nth 3 parse-state) (if backward (goto-char (nth 8 parse-state)) (parse-partial-sexp (point) (line-end-position) nil nil (syntax-ppss) 'syntax-table)) t))) (defun lua-find-regexp (direction regexp &optional limit) "Searches for a regular expression in the direction specified. Direction is one of 'forward and 'backward. Matches in comments and strings are ignored. If the regexp is found, returns point position, nil otherwise." (let ((search-func (if (eq direction 'forward) 're-search-forward 're-search-backward)) (case-fold-search nil)) (cl-loop always (or (null limit) (lua--ensure-point-within-limit limit (not (eq direction 'forward)))) always (funcall search-func regexp limit 'noerror) for match-beg = (match-beginning 0) for match-end = (match-end 0) while (or (lua-comment-or-string-p match-beg) (lua-comment-or-string-p match-end)) do (let ((parse-state (syntax-ppss))) (cond ;; Inside a string ((nth 3 parse-state) (lua--escape-from-string (not (eq direction 'forward)))) ;; Inside a comment ((nth 4 parse-state) (goto-char (nth 8 parse-state)) (when (eq direction 'forward) (forward-comment 1))))) finally return (point)))) (defconst lua-block-regexp (eval-when-compile (concat "\\(\\_<" (regexp-opt '("do" "function" "repeat" "then" "else" "elseif" "end" "until") t) "\\_>\\)\\|" (regexp-opt '("{" "(" "[" "]" ")" "}") t)))) (defconst lua-block-token-alist '(("do" "\\_" "\\_" middle-or-open) ("function" "\\_" nil open) ("repeat" "\\_" nil open) ("then" "\\_<\\(e\\(lse\\(if\\)?\\|nd\\)\\)\\_>" "\\_<\\(else\\)?if\\_>" middle) ("{" "}" nil open) ("[" "]" nil open) ("(" ")" nil open) ("if" "\\_" nil open) ("for" "\\_" nil open) ("while" "\\_" nil open) ("else" "\\_" "\\_" middle) ("elseif" "\\_" "\\_" middle) ("end" nil "\\_<\\(do\\|function\\|then\\|else\\)\\_>" close) ("until" nil "\\_" close) ("}" nil "{" close) ("]" nil "\\[" close) (")" nil "(" close)) "This is a list of block token information blocks. Each token information entry is of the form: KEYWORD FORWARD-MATCH-REGEXP BACKWARDS-MATCH-REGEXP TOKEN-TYPE KEYWORD is the token. FORWARD-MATCH-REGEXP is a regexp that matches all possible tokens when going forward. BACKWARDS-MATCH-REGEXP is a regexp that matches all possible tokens when going backwards. TOKEN-TYPE determines where the token occurs on a statement. open indicates that the token appears at start, close indicates that it appears at end, middle indicates that it is a middle type token, and middle-or-open indicates that it can appear both as a middle or an open type.") (defconst lua-indentation-modifier-regexp ;; The absence of else is deliberate, since it does not modify the ;; indentation level per se. It only may cause the line, in which the ;; else is, to be shifted to the left. (concat "\\(\\_<" (regexp-opt '("do" "function" "repeat" "then" "if" "else" "elseif" "for" "while") t) "\\_>\\|" (regexp-opt '("{" "(" "[")) "\\)\\|\\(\\_<" (regexp-opt '("end" "until") t) "\\_>\\|" (regexp-opt '("]" ")" "}")) "\\)") ) (defun lua-get-block-token-info (token) "Returns the block token info entry for TOKEN from lua-block-token-alist" (assoc token lua-block-token-alist)) (defun lua-get-token-match-re (token-info direction) "Returns the relevant match regexp from token info" (cond ((eq direction 'forward) (cadr token-info)) ((eq direction 'backward) (nth 2 token-info)) (t nil))) (defun lua-get-token-type (token-info) "Returns the relevant match regexp from token info" (nth 3 token-info)) (defun lua-backwards-to-block-begin-or-end () "Move backwards to nearest block begin or end. Returns nil if not successful." (interactive) (lua-find-regexp 'backward lua-block-regexp)) (defun lua-find-matching-token-word (token &optional direction) "Find matching open- or close-token for TOKEN in DIRECTION. Point has to be exactly at the beginning of TOKEN, e.g. with | being point {{ }|} -- (lua-find-matching-token-word \"}\" 'backward) will return -- the first { {{ |}} -- (lua-find-matching-token-word \"}\" 'backward) will find -- the second {. DIRECTION has to be either 'forward or 'backward." (let* ((token-info (lua-get-block-token-info token)) (match-type (lua-get-token-type token-info)) ;; If we are on a middle token, go backwards. If it is a middle or open, ;; go forwards (search-direction (or direction (if (or (eq match-type 'open) (eq match-type 'middle-or-open)) 'forward 'backward) 'backward)) (match (lua-get-token-match-re token-info search-direction)) maybe-found-pos) ;; if we are searching forward from the token at the current point ;; (i.e. for a closing token), need to step one character forward ;; first, or the regexp will match the opening token. (if (eq search-direction 'forward) (forward-char 1)) (catch 'found ;; If we are attempting to find a matching token for a terminating token ;; (i.e. a token that starts a statement when searching back, or a token ;; that ends a statement when searching forward), then we don't need to look ;; any further. (if (or (and (eq search-direction 'forward) (eq match-type 'close)) (and (eq search-direction 'backward) (eq match-type 'open))) (throw 'found nil)) (while (lua-find-regexp search-direction lua-indentation-modifier-regexp) ;; have we found a valid matching token? (let ((found-token (match-string 0)) (found-pos (match-beginning 0))) (let ((found-type (lua-get-token-type (lua-get-block-token-info found-token)))) (if (not (and match (string-match match found-token))) ;; no - then there is a nested block. If we were looking for ;; a block begin token, found-token must be a block end ;; token; likewise, if we were looking for a block end token, ;; found-token must be a block begin token, otherwise there ;; is a grammatical error in the code. (if (not (and (or (eq match-type 'middle) (eq found-type 'middle) (eq match-type 'middle-or-open) (eq found-type 'middle-or-open) (eq match-type found-type)) (goto-char found-pos) (lua-find-matching-token-word found-token search-direction))) (when maybe-found-pos (goto-char maybe-found-pos) (throw 'found maybe-found-pos))) ;; yes. ;; if it is a not a middle kind, report the location (when (not (or (eq found-type 'middle) (eq found-type 'middle-or-open))) (throw 'found found-pos)) ;; if it is a middle-or-open type, record location, but keep searching. ;; If we fail to complete the search, we'll report the location (when (eq found-type 'middle-or-open) (setq maybe-found-pos found-pos)) ;; Cannot use tail recursion. too much nesting on long chains of ;; if/elseif. Will reset variables instead. (setq token found-token) (setq token-info (lua-get-block-token-info token)) (setq match (lua-get-token-match-re token-info search-direction)) (setq match-type (lua-get-token-type token-info)))))) maybe-found-pos))) (defun lua-goto-matching-block-token (&optional parse-start direction) "Find block begion/end token matching the one at the point. This function moves the point to the token that matches the one at the current point. Returns the point position of the first character of the matching token if successful, nil otherwise. Optional PARSE-START is a position to which the point should be moved first. DIRECTION has to be 'forward or 'backward ('forward by default)." (if parse-start (goto-char parse-start)) (let ((case-fold-search nil)) (if (looking-at lua-indentation-modifier-regexp) (let ((position (lua-find-matching-token-word (match-string 0) direction))) (and position (goto-char position)))))) (defun lua-goto-matching-block (&optional noreport) "Go to the keyword balancing the one under the point. If the point is on a keyword/brace that starts a block, go to the matching keyword that ends the block, and vice versa. If optional NOREPORT is non-nil, it won't flag an error if there is no block open/close open." (interactive) ;; search backward to the beginning of the keyword if necessary (when (and (eq (char-syntax (following-char)) ?w) (not (looking-at "\\_<"))) (re-search-backward "\\_<" nil t)) (let ((position (lua-goto-matching-block-token))) (if (and (not position) (not noreport)) (error "Not on a block control keyword or brace") position))) (defun lua-skip-ws-and-comments-backward (&optional limit) "Move point back skipping all whitespace and comments. If LIMIT is given, stop at it or before. Return non-nil if moved point." (interactive) (unless (lua-string-p) (let ((start-pos (point)) (comment-start-pos (lua-comment-start-pos))) (setq limit (min (point) (or limit (point-min)))) (when comment-start-pos (goto-char (max limit comment-start-pos))) (when (< limit (point)) (forward-comment (- limit (point)))) (when (< (point) limit) (goto-char limit)) (when (/= start-pos (point)) (point))))) (defun lua-skip-ws-and-comments-forward (&optional limit) "Move point forward skipping all whitespace and comments. If LIMIT is given, stop at it or before. Return non-nil if moved point." (interactive) (unless (lua-string-p) (let ((start-pos (point)) (comment-start-pos (lua-comment-start-pos))) (setq limit (max (point) (or limit (point-max)))) ;; Escape from current comment. It is necessary to use "while" because ;; luadoc parameters have non-comment face, and parse-partial-sexp with ;; 'syntax-table flag will stop on them. (when comment-start-pos (goto-char comment-start-pos) (forward-comment 1)) (when (< (point) limit) (forward-comment (- limit (point)))) (when (< limit (point)) (goto-char limit)) (when (/= start-pos (point)) (point))))) (defun lua-forward-line-skip-blanks (&optional back) "Move 1 line forward/backward and skip all insignificant ws/comment lines. Moves point 1 line forward (or backward) skipping lines that contain no Lua code besides comments. The point is put to the beginning of the line. Returns final value of point as integer or nil if operation failed." (let ((start-pos (point))) (if back (progn (beginning-of-line) (lua-skip-ws-and-comments-backward)) (forward-line) (lua-skip-ws-and-comments-forward)) (beginning-of-line) (when (> (count-lines start-pos (point)) 0) (point)))) (eval-when-compile (defconst lua-operator-class "-+*/^.=<>~:&|")) (defconst lua-cont-eol-regexp (eval-when-compile (concat "\\(?:\\(?1:\\_<" (regexp-opt '("and" "or" "not" "in" "for" "while" "local" "function" "if" "until" "elseif" "return") t) "\\_>\\)\\|" "\\(?:^\\|[^" lua-operator-class "]\\)\\(?2:" (regexp-opt '("+" "-" "*" "/" "%" "^" ".." "==" "=" "<" ">" "<=" ">=" "~=" "." ":" "&" "|" "~" ">>" "<<" "~" ",") t) "\\)\\)" "\\s *\\=")) "Regexp that matches the ending of a line that needs continuation. This regexp starts from eol and looks for a binary operator or an unclosed block intro (i.e. 'for' without 'do' or 'if' without 'then') followed by an optional whitespace till the end of the line.") (defconst lua-cont-bol-regexp (eval-when-compile (concat "\\=\\s *" "\\(?:\\(?1:\\_<" (regexp-opt '("and" "or" "not" "in") t) "\\_>\\)\\|\\(?2:" (regexp-opt '("," "+" "-" "*" "/" "%" "^" ".." "==" "=" "<" ">" "<=" ">=" "~=" "." ":" "&" "|" "~" ">>" "<<" "~") t) "\\)\\(?:$\\|[^" lua-operator-class "]\\)" "\\)")) "Regexp that matches a line that continues previous one. This regexp means, starting from point there is an optional whitespace followed by Lua binary operator. Lua is very liberal when it comes to continuation line, so we're safe to assume that every line that starts with a binop continues previous one even though it looked like an end-of-statement.") (defun lua-last-token-continues-p () "Return non-nil if the last token on this line is a continuation token." (let ((line-begin (line-beginning-position)) return-value) (save-excursion (end-of-line) (lua-skip-ws-and-comments-backward line-begin) (setq return-value (and (re-search-backward lua-cont-eol-regexp line-begin t) (or (match-beginning 1) (match-beginning 2)))) (if (and return-value (string-equal (match-string-no-properties 0) "return")) ;; "return" keyword is ambiguous and depends on next token (unless (save-excursion (goto-char (match-end 0)) (forward-comment (point-max)) (and ;; Not continuing: at end of file (not (eobp)) (or ;; "function" keyword: it is a continuation, e.g. ;; ;; return ;; function() return 123 end ;; (looking-at (lua-rx (symbol "function"))) ;; Looking at semicolon or any other keyword: not continuation (not (looking-at (lua-rx (or ";" lua-keyword))))))) (setq return-value nil))) return-value))) (defun lua-first-token-continues-p () "Return non-nil if the first token on this line is a continuation token." (let ((line-end (line-end-position))) (save-excursion (beginning-of-line) (lua-skip-ws-and-comments-forward line-end) ;; if first character of the line is inside string, it's a continuation ;; if strings aren't supposed to be indented, `lua-calculate-indentation' won't even let ;; the control inside this function (and (re-search-forward lua-cont-bol-regexp line-end t) (or (match-beginning 1) (match-beginning 2)))))) (defun lua--backward-up-list-noerror () "Safe version of lua-backward-up-list that does not signal an error." (condition-case nil (lua-backward-up-list) (scan-error nil))) (defun lua-backward-up-list () "Goto starter/opener of the block that contains point." (interactive) (let ((start-pos (point)) end-pos) (or ;; Return parent block opener token if it exists. (cl-loop ;; Search indentation modifier backward, return nil on failure. always (lua-find-regexp 'backward lua-indentation-modifier-regexp) ;; Fetch info about the found token for token = (match-string-no-properties 0) for token-info = (lua-get-block-token-info token) for token-type = (lua-get-token-type token-info) ;; If the token is a close token, continue to skip its opener. If not ;; close, stop and return found token. while (eq token-type 'close) ;; Find matching opener to skip it and continue from beginning. ;; ;; Return nil on failure. always (let ((position (lua-find-matching-token-word token 'backward))) (and position (goto-char position))) finally return token-info) (progn (setq end-pos (point)) (goto-char start-pos) (signal 'scan-error (list "Block open token not found" ;; If start-pos == end-pos, the "obstacle" is current (if (eql start-pos end-pos) start-pos (match-beginning 0)) (if (eql start-pos end-pos) start-pos (match-end 0)))))))) (defun lua--continuation-breaking-line-p () "Return non-nil if looking at token(-s) that forbid continued line." (save-excursion (lua-skip-ws-and-comments-forward (line-end-position)) (looking-at (lua-rx (or (symbol "do" "while" "repeat" "until" "if" "then" "elseif" "else" "for" "local") lua-funcheader))))) (defun lua-is-continuing-statement-p-1 () "Return non-nil if current lined continues a statement. More specifically, return the point in the line that is continued. The criteria for a continuing statement are: * the last token of the previous line is a continuing op, OR the first token of the current line is a continuing op * the expression is not enclosed by a parentheses/braces/brackets" (let (prev-line continuation-pos parent-block-opener) (save-excursion (setq prev-line (lua-forward-line-skip-blanks 'back))) (and prev-line (not (lua--continuation-breaking-line-p)) (save-excursion (or ;; Binary operator or keyword that implies continuation. (and (setq continuation-pos (or (lua-first-token-continues-p) (save-excursion (and (goto-char prev-line) ;; check last token of previous nonblank line (lua-last-token-continues-p))))) (not ;; Operators/keywords does not create continuation inside some blocks: (and (setq parent-block-opener (car-safe (lua--backward-up-list-noerror))) (or ;; - inside parens/brackets (member parent-block-opener '("(" "[")) ;; - inside braces if it is a comma (and (eq (char-after continuation-pos) ?,) (equal parent-block-opener "{"))))) continuation-pos)))))) (defun lua-is-continuing-statement-p (&optional parse-start) "Returns non-nil if the line at PARSE-START should be indented as continuation line. This true is when the line : * is continuing a statement itself * starts with a 1+ block-closer tokens, an top-most block opener is on a continuation line " (save-excursion (if parse-start (goto-char parse-start)) ;; If line starts with a series of closer tokens, whether or not the line ;; is a continuation line is decided by the opener line, e.g. ;; ;; x = foo + ;; long_function_name( ;; long_parameter_1, ;; long_parameter_2, ;; long_parameter_3, ;; ) + long_function_name2({ ;; long_parameter_1, ;; long_parameter_2, ;; long_parameter_3, ;; }) ;; ;; Final line, "})" is a continuation line, but it is decided by the ;; opener line, ") + long_function_name2({", which in its turn is decided ;; by the "long_function_name(" line, which is a continuation line ;; because the line before it ends with a binary operator. (cl-loop ;; Go to opener line while (and (lua--goto-line-beginning-rightmost-closer) (lua--backward-up-list-noerror)) ;; If opener line is continuing, repeat. If opener line is not ;; continuing, return nil. always (lua-is-continuing-statement-p-1) ;; We get here if there was no opener to go to: check current line. finally return (lua-is-continuing-statement-p-1)))) (defun lua-make-indentation-info-pair (found-token found-pos) "Create a pair from FOUND-TOKEN and FOUND-POS for indentation calculation. This is a helper function to lua-calculate-indentation-info. Don't use standalone." (cond ;; function is a bit tricky to indent right. They can appear in a lot ot ;; different contexts. Until I find a shortcut, I'll leave it with a simple ;; relative indentation. ;; The special cases are for indenting according to the location of the ;; function. i.e.: ;; (cons 'absolute (+ (current-column) lua-indent-level)) ;; TODO: Fix this. It causes really ugly indentations for in-line functions. ((string-equal found-token "function") (cons 'relative lua-indent-level)) ;; block openers ((and lua-indent-nested-block-content-align (member found-token (list "{" "(" "["))) (save-excursion (let ((found-bol (line-beginning-position))) (forward-comment (point-max)) ;; If the next token is on this line and it's not a block opener, ;; the next line should align to that token. (if (and (zerop (count-lines found-bol (line-beginning-position))) (not (looking-at lua-indentation-modifier-regexp))) (cons 'absolute (current-column)) (cons 'relative lua-indent-level))))) ;; These are not really block starters. They should not add to indentation. ;; The corresponding "then" and "do" handle the indentation. ((member found-token (list "if" "for" "while")) (cons 'relative 0)) ;; closing tokens follow: These are usually taken care of by ;; lua-calculate-indentation-override. ;; elseif is a bit of a hack. It is not handled separately, but it needs to ;; nullify a previous then if on the same line. ((member found-token (list "until" "elseif")) (save-excursion (let* ((line-beginning (line-beginning-position)) (same-line (and (lua-goto-matching-block-token found-pos 'backward) (<= line-beginning (point))))) (if same-line (cons 'remove-matching 0) (cons 'relative 0))))) ;; else is a special case; if its matching block token is on the same line, ;; instead of removing the matching token, it has to replace it, so that ;; either the next line will be indented correctly, or the end on the same ;; line will remove the effect of the else. ((string-equal found-token "else") (save-excursion (let* ((line-beginning (line-beginning-position)) (same-line (and (lua-goto-matching-block-token found-pos 'backward) (<= line-beginning (point))))) (if same-line (cons 'replace-matching (cons 'relative lua-indent-level)) (cons 'relative lua-indent-level))))) ;; Block closers. If they are on the same line as their openers, they simply ;; eat up the matching indentation modifier. Otherwise, they pull ;; indentation back to the matching block opener. ((member found-token (list ")" "}" "]" "end")) (save-excursion (let* ((line-beginning (line-beginning-position)) (same-line (and (lua-goto-matching-block-token found-pos 'backward) (<= line-beginning (point)))) (opener-pos (point)) opener-continuation-offset) (if same-line (cons 'remove-matching 0) (back-to-indentation) (setq opener-continuation-offset (if (lua-is-continuing-statement-p-1) lua-indent-level 0)) ;; Accumulate indentation up to opener, including indentation. If ;; there were no other indentation modifiers until said opener, ;; ensure there is no continuation after the closer. `(multiple . ((absolute . ,(- (current-indentation) opener-continuation-offset)) ,@(when (/= opener-continuation-offset 0) (list (cons 'continued-line opener-continuation-offset))) ,@(delete nil (list (lua-calculate-indentation-info-1 nil opener-pos))) (cancel-continued-line . nil))))))) ((member found-token '("do" "then")) `(multiple . ((cancel-continued-line . nil) (relative . ,lua-indent-level)))) ;; Everything else. This is from the original code: If opening a block ;; (match-data 1 exists), then push indentation one level up, if it is ;; closing a block, pull it one level down. ('other-indentation-modifier (cons 'relative (if (nth 2 (match-data)) ;; beginning of a block matched lua-indent-level ;; end of a block matched (- lua-indent-level)))))) (defun lua-add-indentation-info-pair (pair info-list) "Add the given indentation info PAIR to the list of indentation INFO-LIST. This function has special case handling for two tokens: remove-matching, and replace-matching. These two tokens are cleanup tokens that remove or alter the effect of a previously recorded indentation info. When a remove-matching token is encountered, the last recorded info, i.e. the car of the list is removed. This is used to roll-back an indentation of a block opening statement when it is closed. When a replace-matching token is seen, the last recorded info is removed, and the cdr of the replace-matching info is added in its place. This is used when a middle-of the block (the only case is 'else') is seen on the same line the block is opened." (cond ( (eq 'multiple (car pair)) (let ((info-pair-elts (cdr pair))) (while info-pair-elts (setq info-list (lua-add-indentation-info-pair (car info-pair-elts) info-list) info-pair-elts (cdr info-pair-elts))) info-list)) ( (eq 'cancel-continued-line (car pair)) (if (eq (caar info-list) 'continued-line) (cdr info-list) info-list)) ( (eq 'remove-matching (car pair)) ;; Remove head of list (cdr info-list)) ( (eq 'replace-matching (car pair)) ;; remove head of list, and add the cdr of pair instead (cons (cdr pair) (cdr info-list))) ( (listp (cdr-safe pair)) (nconc pair info-list)) ( t ;; Just add the pair (cons pair info-list)))) (defun lua-calculate-indentation-info-1 (indentation-info bound) "Helper function for `lua-calculate-indentation-info'. Return list of indentation modifiers from point to BOUND." (while (lua-find-regexp 'forward lua-indentation-modifier-regexp bound) (let ((found-token (match-string 0)) (found-pos (match-beginning 0))) (setq indentation-info (lua-add-indentation-info-pair (lua-make-indentation-info-pair found-token found-pos) indentation-info)))) indentation-info) (defun lua-calculate-indentation-info (&optional parse-end) "For each block token on the line, computes how it affects the indentation. The effect of each token can be either a shift relative to the current indentation level, or indentation to some absolute column. This information is collected in a list of indentation info pairs, which denote absolute and relative each, and the shift/column to indent to." (let (indentation-info cont-stmt-pos) (while (setq cont-stmt-pos (lua-is-continuing-statement-p)) (lua-forward-line-skip-blanks 'back) (when (< cont-stmt-pos (point)) (goto-char cont-stmt-pos))) ;; calculate indentation modifiers for the line itself (setq indentation-info (list (cons 'absolute (current-indentation)))) (back-to-indentation) (setq indentation-info (lua-calculate-indentation-info-1 indentation-info (min parse-end (line-end-position)))) ;; and do the following for each continuation line before PARSE-END (while (and (eql (forward-line 1) 0) (<= (point) parse-end)) ;; handle continuation lines: (if (lua-is-continuing-statement-p) ;; if it's the first continuation line, add one level (unless (eq (car (car indentation-info)) 'continued-line) (push (cons 'continued-line lua-indent-level) indentation-info)) ;; if it's the first non-continued line, subtract one level (when (eq (car (car indentation-info)) 'continued-line) (push (cons 'stop-continued-line (- lua-indent-level)) indentation-info))) ;; add modifiers found in this continuation line (setq indentation-info (lua-calculate-indentation-info-1 indentation-info (min parse-end (line-end-position))))) indentation-info)) (defun lua-accumulate-indentation-info (reversed-indentation-info) "Accumulates the indentation information previously calculated by lua-calculate-indentation-info. Returns either the relative indentation shift, or the absolute column to indent to." (let (indentation-info (type 'relative) (accu 0)) ;; Aggregate all neighbouring relative offsets, reversing the INFO list. (cl-dolist (elt reversed-indentation-info) (if (and (eq (car elt) 'relative) (eq (caar indentation-info) 'relative)) (setcdr (car indentation-info) (+ (cdar indentation-info) (cdr elt))) (push elt indentation-info))) ;; Aggregate indentation info, taking 'absolute modifiers into account. (mapc (lambda (x) (let ((new-val (cdr x))) (if (eq 'absolute (car x)) (progn (setq type 'absolute accu new-val)) (setq accu (+ accu new-val))))) indentation-info) (cons type accu))) (defun lua-calculate-indentation-block-modifier (&optional parse-end) "Return amount by which this line modifies the indentation. Beginnings of blocks add lua-indent-level once each, and endings of blocks subtract lua-indent-level once each. This function is used to determine how the indentation of the following line relates to this one." (let (indentation-info) (save-excursion ;; First go back to the line that starts it all ;; lua-calculate-indentation-info will scan through the whole thing (let ((case-fold-search nil)) (setq indentation-info (lua-accumulate-indentation-info (lua-calculate-indentation-info parse-end))))) (if (eq (car indentation-info) 'absolute) (- (cdr indentation-info) (current-indentation)) (cdr indentation-info)))) (eval-when-compile (defconst lua--function-name-rx '(seq symbol-start (+ (any alnum "_")) (* "." (+ (any alnum "_"))) (? ":" (+ (any alnum "_"))) symbol-end) "Lua function name regexp in `rx'-SEXP format.")) (defconst lua--left-shifter-regexp (eval-when-compile (rx ;; This regexp should answer the following questions: ;; 1. is there a left shifter regexp on that line? ;; 2. where does block-open token of that left shifter reside? (or (seq (group-n 1 symbol-start "local" (+ blank)) "function" symbol-end) (seq (group-n 1 (eval lua--function-name-rx) (* blank)) (any "{(")) (seq (group-n 1 (or ;; assignment statement prefix (seq (* nonl) (not (any "<=>~")) "=" (* blank)) ;; return statement prefix (seq word-start "return" word-end (* blank)))) ;; right hand side (or "{" "function" "(" (seq (group-n 1 (eval lua--function-name-rx) (* blank)) (any "({"))))))) "Regular expression that matches left-shifter expression. Left-shifter expression is defined as follows. If a block follows a left-shifter expression, its contents & block-close token should be indented relative to left-shifter expression indentation rather then to block-open token. For example: -- 'local a = ' is a left-shifter expression -- 'function' is a block-open token local a = function() -- block contents is indented relative to left-shifter foobarbaz() -- block-end token is unindented to left-shifter indentation end The following left-shifter expressions are currently handled: 1. local function definition with function block, begin-end 2. function call with arguments block, () or {} 3. assignment/return statement with - table constructor block, {} - function call arguments block, () or {} block - function expression a.k.a. lambda, begin-end block.") (defun lua-point-is-after-left-shifter-p () "Check if point is right after a left-shifter expression. See `lua--left-shifter-regexp' for description & example of left-shifter expression. " (save-excursion (let ((old-point (point))) (back-to-indentation) (and (/= (point) old-point) (looking-at lua--left-shifter-regexp) (= old-point (match-end 1)))))) (defun lua--goto-line-beginning-rightmost-closer (&optional parse-start) (let (case-fold-search pos line-end-pos return-val) (save-excursion (if parse-start (goto-char parse-start)) (setq line-end-pos (line-end-position)) (back-to-indentation) (unless (lua-comment-or-string-p) (cl-loop while (and (<= (point) line-end-pos) (looking-at lua-indentation-modifier-regexp)) for token-info = (lua-get-block-token-info (match-string 0)) for token-type = (lua-get-token-type token-info) while (not (eq token-type 'open)) do (progn (setq pos (match-beginning 0) return-val token-info) (goto-char (match-end 0)) (forward-comment (line-end-position)))))) (when pos (progn (goto-char pos) return-val)))) (defun lua-calculate-indentation-override (&optional parse-start) "Return overriding indentation amount for special cases. If there's a sequence of block-close tokens starting at the beginning of the line, calculate indentation according to the line containing block-open token for the last block-close token in the sequence. If not, return nil." (let (case-fold-search rightmost-closer-info opener-info opener-pos) (save-excursion (when (and (setq rightmost-closer-info (lua--goto-line-beginning-rightmost-closer parse-start)) (setq opener-info (lua--backward-up-list-noerror)) ;; Ensure opener matches closer. (string-match (lua-get-token-match-re rightmost-closer-info 'backward) (car opener-info))) ;; Special case: "middle" tokens like for/do, while/do, if/then, ;; elseif/then: corresponding "end" or corresponding "else" must be ;; unindented to the beginning of the statement, which is not ;; necessarily the same as beginning of string that contains "do", e.g. ;; ;; while ( ;; foo and ;; bar) do ;; hello_world() ;; end (setq opener-pos (point)) (when (/= (- opener-pos (line-beginning-position)) (current-indentation)) (unless (or (and (string-equal (car opener-info) "do") (member (car (lua--backward-up-list-noerror)) '("while" "for"))) (and (string-equal (car opener-info) "then") (member (car (lua--backward-up-list-noerror)) '("if" "elseif")))) (goto-char opener-pos))) ;; (let (cont-stmt-pos) ;; (while (setq cont-stmt-pos (lua-is-continuing-statement-p)) ;; (goto-char cont-stmt-pos))) ;; Exception cases: when the start of the line is an assignment, ;; go to the start of the assignment instead of the matching item (if (and lua-indent-close-paren-align (member (car opener-info) '("{" "(" "[")) (not (lua-point-is-after-left-shifter-p))) (current-column) (current-indentation)))))) (defun lua-calculate-indentation () "Return appropriate indentation for current line as Lua code." (save-excursion (let ((cur-line-begin-pos (line-beginning-position))) (or ;; when calculating indentation, do the following: ;; 1. check, if the line starts with indentation-modifier (open/close brace) ;; and if it should be indented/unindented in special way (lua-calculate-indentation-override) (when (lua-forward-line-skip-blanks 'back) ;; the order of function calls here is important. block modifier ;; call may change the point to another line (let* ((modifier (lua-calculate-indentation-block-modifier cur-line-begin-pos))) (+ (current-indentation) modifier))) ;; 4. if there's no previous line, indentation is 0 0)))) (defvar lua--beginning-of-defun-re (lua-rx-to-string '(: bol (? (symbol "local") ws+) lua-funcheader)) "Lua top level (matches only at the beginning of line) function header regex.") (defun lua-beginning-of-proc (&optional arg) "Move backward to the beginning of a Lua proc (or similar). With argument, do it that many times. Negative arg -N means move forward to Nth following beginning of proc. Returns t unless search stops due to beginning or end of buffer." (interactive "P") (or arg (setq arg 1)) (while (and (> arg 0) (re-search-backward lua--beginning-of-defun-re nil t)) (setq arg (1- arg))) (while (and (< arg 0) (re-search-forward lua--beginning-of-defun-re nil t)) (beginning-of-line) (setq arg (1+ arg))) (zerop arg)) (defun lua-end-of-proc (&optional arg) "Move forward to next end of Lua proc (or similar). With argument, do it that many times. Negative argument -N means move back to Nth preceding end of proc. This function just searches for a `end' at the beginning of a line." (interactive "P") (or arg (setq arg 1)) (let ((found nil) (ret t)) (if (and (< arg 0) (not (bolp)) (save-excursion (beginning-of-line) (eq (following-char) ?}))) (forward-char -1)) (while (> arg 0) (if (re-search-forward "^end" nil t) (setq arg (1- arg) found t) (setq ret nil arg 0))) (while (< arg 0) (if (re-search-backward "^end" nil t) (setq arg (1+ arg) found t) (setq ret nil arg 0))) (if found (progn (beginning-of-line) (forward-line))) ret)) (defvar lua-process-init-code (mapconcat 'identity '("local loadstring = loadstring or load" "function luamode_loadstring(str, displayname, lineoffset)" " if lineoffset > 1 then" " str = string.rep('\\n', lineoffset - 1) .. str" " end" "" " local x, e = loadstring(str, '@'..displayname)" " if e then" " error(e)" " end" " return x()" "end") " ")) (defun lua-make-lua-string (str) "Convert string to Lua literal." (save-match-data (with-temp-buffer (insert str) (goto-char (point-min)) (while (re-search-forward "[\"'\\\t\\\n]" nil t) (cond ((string= (match-string 0) "\n") (replace-match "\\\\n")) ((string= (match-string 0) "\t") (replace-match "\\\\t")) (t (replace-match "\\\\\\&" t)))) (concat "'" (buffer-string) "'")))) ;;;###autoload (defalias 'run-lua #'lua-start-process) ;;;###autoload (defun lua-start-process (&optional name program startfile &rest switches) "Start a Lua process named NAME, running PROGRAM. PROGRAM defaults to NAME, which defaults to `lua-default-application'. When called interactively, switch to the process buffer." (interactive) (setq name (or name (if (consp lua-default-application) (car lua-default-application) lua-default-application))) (setq program (or program lua-default-application)) ;; don't re-initialize if there already is a lua process (unless (comint-check-proc (format "*%s*" name)) (setq lua-process-buffer (apply #'make-comint name program startfile (or switches lua-default-command-switches))) (setq lua-process (get-buffer-process lua-process-buffer)) (set-process-query-on-exit-flag lua-process nil) (with-current-buffer lua-process-buffer ;; enable error highlighting in stack traces (require 'compile) (setq lua--repl-buffer-p t) (make-local-variable 'compilation-error-regexp-alist) (setq compilation-error-regexp-alist (cons (list lua-traceback-line-re 1 2) compilation-error-regexp-alist)) (compilation-shell-minor-mode 1) (setq-local comint-prompt-regexp lua-prompt-regexp) ;; Don't send initialization code until seeing the prompt to ensure that ;; the interpreter is ready. (while (not (lua-prompt-line)) (accept-process-output (get-buffer-process (current-buffer))) (goto-char (point-max))) (lua-send-string lua-process-init-code))) ;; when called interactively, switch to process buffer (if (called-interactively-p 'any) (switch-to-buffer lua-process-buffer))) (defun lua-get-create-process () "Return active Lua process creating one if necessary." (lua-start-process) lua-process) (defun lua-kill-process () "Kill Lua process and its buffer." (interactive) (when (buffer-live-p lua-process-buffer) (kill-buffer lua-process-buffer) (setq lua-process-buffer nil))) (defun lua-set-lua-region-start (&optional arg) "Set start of region for use with `lua-send-lua-region'." (interactive) (set-marker lua-region-start (or arg (point)))) (defun lua-set-lua-region-end (&optional arg) "Set end of region for use with `lua-send-lua-region'." (interactive) (set-marker lua-region-end (or arg (point)))) (defun lua-send-string (str) "Send STR plus a newline to the Lua process. If `lua-process' is nil or dead, start a new process first." (unless (string-equal (substring str -1) "\n") (setq str (concat str "\n"))) (process-send-string (lua-get-create-process) str)) (defun lua-send-current-line () "Send current line to the Lua process, found in `lua-process'. If `lua-process' is nil or dead, start a new process first." (interactive) (lua-send-region (line-beginning-position) (line-end-position))) (defun lua-send-defun (pos) "Send the function definition around point to the Lua process." (interactive "d") (save-excursion (let ((start (if (save-match-data (looking-at "^function[ \t]")) ;; point already at the start of "function". ;; We need to handle this case explicitly since ;; lua-beginning-of-proc will move to the ;; beginning of the _previous_ function. (point) ;; point is not at the beginning of function, move ;; there and bind start to that position (lua-beginning-of-proc) (point))) (end (progn (lua-end-of-proc) (point)))) ;; make sure point is in a function definition before sending to ;; the process (if (and (>= pos start) (< pos end)) (lua-send-region start end) (error "Not on a function definition"))))) (defun lua-maybe-skip-shebang-line (start) "Skip shebang (#!/path/to/interpreter/) line at beginning of buffer. Return a position that is after Lua-recognized shebang line (1st character in file must be ?#) if START is at its beginning. Otherwise, return START." (save-restriction (widen) (if (and (eq start (point-min)) (eq (char-after start) ?#)) (save-excursion (goto-char start) (forward-line) (point)) start))) (defun lua-send-region (start end) (interactive "r") (setq start (lua-maybe-skip-shebang-line start)) (let* ((lineno (line-number-at-pos start)) (lua-file (or (buffer-file-name) (buffer-name))) (region-str (buffer-substring-no-properties start end)) (command ;; Print empty line before executing the code so that the first line ;; of output doesn't end up on the same line as current prompt. (format "print(''); luamode_loadstring(%s, %s, %s);\n" (lua-make-lua-string region-str) (lua-make-lua-string lua-file) lineno))) (lua-send-string command) (when lua-always-show (lua-show-process-buffer)))) (defun lua-prompt-line () (save-excursion (save-match-data (forward-line 0) (if (looking-at comint-prompt-regexp) (match-end 0))))) (defun lua-send-lua-region () "Send preset Lua region to Lua process." (interactive) (unless (and lua-region-start lua-region-end) (error "lua-region not set")) (lua-send-region lua-region-start lua-region-end)) (defalias 'lua-send-proc 'lua-send-defun) (defun lua-send-buffer () "Send whole buffer to Lua process." (interactive) (lua-send-region (point-min) (point-max))) (defun lua-restart-with-whole-file () "Restart Lua process and send whole file as input." (interactive) (lua-kill-process) (lua-send-buffer)) (defun lua-show-process-buffer () "Make sure `lua-process-buffer' is being displayed. Create a Lua process if one doesn't already exist." (interactive) (display-buffer (process-buffer (lua-get-create-process)))) (defun lua-hide-process-buffer () "Delete all windows that display `lua-process-buffer'." (interactive) (when (buffer-live-p lua-process-buffer) (delete-windows-on lua-process-buffer))) (defun lua--funcname-char-p (c) "Check if character C is part of a function name. Return nil if C is nil. See `lua-funcname-at-point'." (and c (string-match-p "\\`[A-Za-z_.]\\'" (string c)))) (defun lua-funcname-at-point () "Get current Name { '.' Name } sequence." (when (or (lua--funcname-char-p (char-before)) (lua--funcname-char-p (char-after))) (save-excursion (save-match-data (re-search-backward "\\`\\|[^A-Za-z_.]") ;; NOTE: `point' will be either at the start of the buffer or on a ;; non-symbol character. (re-search-forward "\\([A-Za-z_]+\\(?:\\.[A-Za-z_]+\\)*\\)") (match-string-no-properties 1))))) (defun lua-search-documentation () "Search Lua documentation for the word at the point." (interactive) (let ((url (concat lua-documentation-url "#pdf-" (lua-funcname-at-point)))) (funcall lua-documentation-function url))) (defun lua-toggle-electric-state (&optional arg) "Toggle the electric indentation feature. Optional numeric ARG, if supplied, turns on electric indentation when positive, turns it off when negative, and just toggles it when zero or left out." (interactive "P") (let ((num_arg (prefix-numeric-value arg))) (setq lua-electric-flag (cond ((or (null arg) (zerop num_arg)) (not lua-electric-flag)) ((< num_arg 0) nil) ((> num_arg 0) t)))) (message "%S" lua-electric-flag)) (defun lua-forward-sexp (&optional count) "Forward to block end" (interactive "p") ;; negative offsets not supported (cl-assert (or (not count) (>= count 0))) (save-match-data (let ((count (or count 1)) (block-start (mapcar 'car lua-sexp-alist))) (while (> count 0) ;; skip whitespace (skip-chars-forward " \t\n") (if (looking-at (regexp-opt block-start 'words)) (let ((keyword (match-string 1))) (lua-find-matching-token-word keyword 'forward)) ;; If the current keyword is not a "begin" keyword, then just ;; perform the normal forward-sexp. (forward-sexp 1)) (setq count (1- count)))))) ;; menu bar (define-key lua-mode-menu [restart-with-whole-file] '("Restart With Whole File" . lua-restart-with-whole-file)) (define-key lua-mode-menu [kill-process] '("Kill Process" . lua-kill-process)) (define-key lua-mode-menu [hide-process-buffer] '("Hide Process Buffer" . lua-hide-process-buffer)) (define-key lua-mode-menu [show-process-buffer] '("Show Process Buffer" . lua-show-process-buffer)) (define-key lua-mode-menu [end-of-proc] '("End Of Proc" . lua-end-of-proc)) (define-key lua-mode-menu [beginning-of-proc] '("Beginning Of Proc" . lua-beginning-of-proc)) (define-key lua-mode-menu [send-lua-region] '("Send Lua-Region" . lua-send-lua-region)) (define-key lua-mode-menu [set-lua-region-end] '("Set Lua-Region End" . lua-set-lua-region-end)) (define-key lua-mode-menu [set-lua-region-start] '("Set Lua-Region Start" . lua-set-lua-region-start)) (define-key lua-mode-menu [send-current-line] '("Send Current Line" . lua-send-current-line)) (define-key lua-mode-menu [send-region] '("Send Region" . lua-send-region)) (define-key lua-mode-menu [send-proc] '("Send Proc" . lua-send-proc)) (define-key lua-mode-menu [send-buffer] '("Send Buffer" . lua-send-buffer)) (define-key lua-mode-menu [search-documentation] '("Search Documentation" . lua-search-documentation)) (provide 'lua-mode) ;;; lua-mode.el ends here lua-mode-20210802/test/000077500000000000000000000000001410202764300144335ustar00rootroot00000000000000lua-mode-20210802/test/.nosearch000066400000000000000000000000001410202764300162240ustar00rootroot00000000000000lua-mode-20210802/test/indentation-tests/000077500000000000000000000000001410202764300201075ustar00rootroot00000000000000lua-mode-20210802/test/indentation-tests/README.md000066400000000000000000000030111410202764300213610ustar00rootroot00000000000000## Indentation Tests This directory contains indentation tests for `lua-mode`. Each `*.lua` file will be processed by `test-indentation.el` as follows: - the file itself will be added as a buttercup `describe` block - each span of code between comments will be added as `it` block that checks that the code is reindented as given in the file - last line of comment before Lua code span will be used as the name of `it` block - spans of code that have empty name will be called `section 1`, `section 2` and so on - spans of code that contain only whitespace will be skipped - if the name of the code span contains `XFAIL`, the test will be created as an expected failure (`xit` in buttercup) ### Example Here's an example: ```lua -- function call indentation function( 1, 2, 3, ) -- XXX: this is commented out for now -- while block indentation -- -- while true do -- print(123) -- end -- -- function literal indentation local x = function() return 1, 2, 3 end ``` It will create two tests, "function call indentation" and "function literal" indentation. The test called "while block indentation" will be ignored completely. ### Adding Configuration Parameters To add configuration parameters use Emacs syntax for Local Variables: ``` -- Local Variables: -- lua-indent-close-paren-align: nil -- lua-indent-only-use-last-opener: t -- End: ``` This can go anywhere in the file, but make sure that the code span after the local variables section has a name comment, otherwise it will use `End:` line as a name. lua-mode-20210802/test/indentation-tests/assignment-indentation.lua000066400000000000000000000051571410202764300253040ustar00rootroot00000000000000-- ensure is sane foo = 10 bar = 20 -- add continuation before = foo = 10 bar = 20 -- add continuation after = foo = 10 bar = 20 -- continuation after comma: 1 foo, baz = 10, 20 bar = 20 -- continuation after comma: 2 foo, baz = 10, 20 bar = 20 -- continuation after comma: 3 foo, baz = 10, 20 bar = 20 -- continuation after comma: 4 foo, baz = 10, 20 -- continuation after comma: 5 foo, baz = 10, 20 bar = 20 -- continuation after "local": 1 local x = 5 -- continuation after "local": 2 local x, y = 10, 20 -- continuation after "local": 3 local x, y = 10, 20 -- continuation after "local": 4 local x = 5 -- indentation of function call arguments in continuation part x = foo(123, 456) + bar( qux, quux) -- does not indent binary operators inside parentheses: alignment 1 x = (very_very_very_long_name() + another_very_very_very_long_name()) -- does not indent binary operators inside parentheses: alignment 2 x = (very_very_very_long_name() + another_very_very_very_long_name()) -- does not indent binary operators inside parentheses: indentation 1 x = ( very_very_very_long_name() + another_very_very_very_long_name() ) -- does not indent binary operators inside parentheses: indentation 2 x = ( very_very_very_long_name() + another_very_very_very_long_name() ) -- it unindents close paren for arithmetical expression a = ( foo + bar ) -- it unindents close paren for arithmetical expression: local local a = ( foo + bar ) -- it unindents close paren for function call a = myfunc( foo + bar ) -- it unindents close paren for function call: local local a = myfunc( foo + bar ) -- it unindents close brace for table ctor a = { foo, bar } -- it unindents close brace for table ctor: local local a = { foo, bar } -- XFAIL: it unindents close bracket for indexing a = myobj[ foo + bar ] -- XFAIL: it unindents close bracket for indexing: local local a = myobj[ foo + bar ] -- does not indent binary operators inside brackets: alignment 1 x = t[very_very_very_long_name() + another_very_very_very_long_name()] -- does not indent binary operators inside brackets: alignment 2 x = t[very_very_very_long_name() + another_very_very_very_long_name()] -- does not indent binary operators inside brackets: indentation 1 x = foo[ very_very_very_long_name() + another_very_very_very_long_name() ] -- does not indent binary operators inside brackets: indentation 2 x = foo[ very_very_very_long_name() + another_very_very_very_long_name() ] lua-mode-20210802/test/indentation-tests/continuation-lines.lua000066400000000000000000000042761410202764300244450ustar00rootroot00000000000000-- indentation if broken in the middle of \"foo.bar\" and \"qux:quux\" foo123 .bar:baz(xyz) foo123. bar:baz(xyz) foo123.bar :baz(xyz) foo123.bar: baz(xyz) foo123.bar .baz .qux :quux(xyz) -- indentation after return function foo() return 123 end -- indentation after return: blocks do return 123 end do return x + y end do return end foo = bar -- indentation after return: f1 function f1() if foo == bar then return else foo = bar end end -- indentation after return: f2 function f2() if foo == bar then return elseif foo != bar then foo = bar end end -- indentation after return: f3 function f3() repeat return until foo == bar end -- indentation after ellipsis function x(...) a, b = 1, ... return b end -- indentation in block-intros: while while foo do a = a + 1 end a = 0 -- indentation in block-intros: while 2 while foo do a = a + 1 end a = 0 -- indents expressions after return: basic function myfunc() return 123 end -- indents expressions after return: function literal function myfunc() return function() return 123 end end -- indents expressions after return: ellipsis function myfunc(...) return ... end -- does not indents keywords after return: end function myfunc() return end -- does not indents keywords after return: if/end function myfunc() if true then return end end -- does not indents keywords after return: if/else function myfunc() if true then return else print(123) end end -- does not indents keywords after return: if/elseif function myfunc() if true then return elseif false then print(123) end end -- does not indents keywords after return: repeat/until function myfunc() repeat return until true end -- does not indents keywords after return: semicolon 1 function myfunc() if true then return; end end -- does not indents keywords after return: semicolon 2 function myfunc() if true then return; hello_world() -- this is incorrect syntax, but it's fine else return hello_world() end end lua-mode-20210802/test/indentation-tests/do-block.lua000066400000000000000000000006241410202764300223060ustar00rootroot00000000000000-- works for do ... end blocks on separate lines do a = a + 1 end a = 0 -- works for do ... end blocks: single line do a = a + 1 end a = 0 -- works for do ... end blocks: body on the same line do a = a + 1 end a = 0 -- works for do ... end blocks: continuation inside body do a = a + 1 end a = 0 -- works for do ... end blocks: parentheses inside body do a = (a + 1) end a = 0 lua-mode-20210802/test/indentation-tests/for-equals-block.lua000066400000000000000000000013131410202764300237560ustar00rootroot00000000000000-- works for "for ... = ... do" block: 1 for y = 0, 10 do a = a + 1 end a = 0 -- works for "for ... = ... do" block: 2 for y = 0, 10 do a = a + 1 end a = 0 -- works for "for ... = ... do" block: 3 for y = 0, 10 do a = a + 1 end a = 0 -- works for "for ... = ... do" block: 4 for y = 0, 10 do a = a + 1 end a = 0 -- works for "for ... = ... do" block: 5 for y = 0, 10 do a = a + 1 end a = 0 -- works for "for ... = ... do" block: 6 for y = 0, 10 do a = a + 1 end a = 0 -- works for "for ... = ... do" block: 7 for y = foo( 1, 2), bar(3, 4) do a = a + 1 end a = 0 -- works for "for ... = ... do" block: single line for y = 0, 10 do a = a + 1 end a = 0 lua-mode-20210802/test/indentation-tests/for-in-block.lua000066400000000000000000000016701410202764300231000ustar00rootroot00000000000000-- works for "for .. in .. do" block: 1 for k, v in pairs(bar) do a = a + 1 end a = 0 -- works for "for .. in .. do" block: 2 for k, v in pairs(bar) do a = a + 1 end a = 0 -- works for "for .. in .. do" block: 3 for k, v in pairs(bar) do a = a + 1 end a = 0 -- works for "for .. in .. do" block: 4 for k, v in pairs(bar) do a = a + 1 end a = 0 -- works for "for .. in .. do" block: 5 for k, v in pairs(bar) do a = a + 1 end a = 0 -- works for "for .. in .. do" block: 6 for k, v in pairs(bar) do a = a + 1 end a = 0 -- works for "for .. in .. do" block: 7 for k, v in pairs(bar) do a = a + 1 end a = 0 -- works for "for .. in .. do" block: 8 for k, v in pairs(bar) do a = a + 1 end a = 0 -- works for "for .. in .. do" block: 9 for k, v in pairs(bar) do a = a + 1 end a = 0 -- works for "for .. in .. do" block: single line for k, v in pairs(bar) do a = a + 1 end a = 0 lua-mode-20210802/test/indentation-tests/function-call-arguments.lua000066400000000000000000000030701410202764300253530ustar00rootroot00000000000000-- THINGS TO TEST: -- parentheses vs braces (table ctor) -- close paren/brace: attached/detached -- alignment/indentation -- args in horizontal line vs args in column vs mixed -- one of params is a table/function literal/function call/single-line table/single-line function -- it works for single line case foobar(a, b, c) a = 0 -- it works for indenting all args on one line: close paren on separate line foobar( a, b, c ) a = 0 -- it works for indenting all args in a column: close paren on separate line foobar( a, b, c ) a = 0 -- it works for mixed arg indentation: close paren on separate line foobar( a, b, c, d ) a = 0 -- it works with table ctorfor single line case foobar{a, b, c} a = 0 -- it works with table ctor for indenting all args on one line: close paren on separate line foobar{ a, b, c } a = 0 -- it works with table ctor for indenting all args in a column: close paren on separate line foobar{ a, b, c } a = 0 -- it works with table ctor for mixed arg indentation: close paren on separate line foobar{ a, b, c, d } a = 0 -- it works for mixed arg indentation with table in the middle: close paren on separate line foobar( a, b, { foo = bar, qux = quux }, d ) a = 0 -- it works for mixed arg indentation with table first: close paren on separate line foobar( { foo = bar, qux = quux }, b, c, d ) a = 0 -- it works for mixed arg indentation with table last: close paren on separate line foobar( a, b, c, { foo = bar, qux = quux } ) a = 0 lua-mode-20210802/test/indentation-tests/goto-label.lua000066400000000000000000000041331410202764300226400ustar00rootroot00000000000000-- is sane ::foo:: ::bar:: ::baz:: a = 0 -- does not affect indentation when put on a separate line for z=1,10 do ::foo:: bar end a = 0 -- XFAIL: does not affect indentation before block modifiers ::foo:: for z=1,10 do bar end a = 0 -- does not affect indentation after block modifiers for z=1,10 do ::foo:: bar end a = 0 -- reindents according to luawiki examples: 1 for z=1,10 do ::foo:: for y=1,10 do ::bar for x=1,10 do if x^2 + y^2 == z^2 then print('found a Pythagorean triple:', x, y, z) goto done goto done2 end end ::done2:: end end ::done:: -- reindents according to luawiki examples: 2 for z=1,10 do for y=1,10 do for x=1,10 do if x^2 + y^2 == z^2 then print('found a Pythagorean triple:', x, y, z) print('now trying next z...') goto zcontinue end end end ::zcontinue:: end -- reindents according to luawiki examples: 3 for x=1,5 do ::redo:: print(x .. ' + 1 = ?') local y = tonumber(io.read'*l') if y ~= x + 1 then goto redo end end -- reindents according to luawiki examples: 4 ::a:: print 'A' if math.random() < 0.3 then goto c end ::b:: print 'B' if math.random() < 0.5 then goto a end ::c:: print 'C' if math.random() < 0.1 then goto a else goto b end -- reindents according to luawiki examples: 5 function fact_(n, ans) ::call:: if n == 0 then return ans else n, ans = n - 1, ans * n goto call end end print(fact_(5, 1)) --> 120 -- reindents according to luawiki examples: 6 function f() if not g() then goto fail end if not h() then goto cleanup_g end if not i() then goto cleanup_h end do return true end -- need do/end? ::cleanup_h:: undo_h() ::cleanup_g:: undo_g() ::fail:: return false end -- reindents according to luawiki examples: 7 ::redo:: for x=1,10 do for y=1,10 do if not f(x,y) then goto continue end if not g(x,y) then goto skip end if not h(x,y) then goto redo end ::continue:: end end ::skip:: print('foo') lua-mode-20210802/test/indentation-tests/if-elseif-else-block.lua000066400000000000000000000050331410202764300244740ustar00rootroot00000000000000-- works for if/then block: 1 if foo > bar then a = a + 1 end a = 0 -- works for if/then block: 2 if foo > bar then a = a + 1 end a = 0 -- works for if/then block: 3 if foo > bar then a = a + 1 end a = 0 -- works for if/then block: 4 if foo > bar then a = a + 1 end a = 0 -- works for if/then block: 5 if foo > bar then a = a + 1 end a = 0 -- works for if/then block: 6 if foo > bar then a = a + 1 end a = 0 -- works for if/then block: single line 1 if foo then a = a + 1 end a = 0 -- works for if/then block: single line 2 if foo then a = a + 1 end a = 0 -- works for if/then block: single line 3 if foo then a = a + 1 end a = 0 -- works for if/then block: single line 4 if foo then a = a + 1 end a = 0 -- works for if/else block: 1 if foo then a = a + 1 else a = a + 2 end a = 0 -- works for if/else block: 2 if foo then a = a + 1 else a = a + 2 end a = 0 -- works for if/else block: 3 if foo then a = a + 1 else a = a + 2 end a = 0 -- works for if/else block: 4 if foo then a = a + 1 else a = a + 2 end a = 0 -- works for if/else block: 5 if foo then a = a + 1 else a = a + 2 end a = 0 -- works for if/else block: single line 1 if foo + bar then a = a + 1 else a = a + 2 end a = 0 -- works for if/else block: single line 2 if foo + bar then a = a + 1 else a = a + 2 end a = 0 -- works for if/else block: single line 3 if foo + bar then a = a + 1 else a = a + 2 end a = 0 -- works for if/else block: single line 4 if foo + bar then a = a + 1 else a = a + 2 end a = 0 -- XFAIL: works for if/else block: single line 5 if foo + bar then a = a + 1 else a = a + 2 -- this line should be indented by 2 levels: else+continuation end a = 0 -- works for if/else block: single line 6 if foo + bar then a = a + 1 else a = a + 2 end a = 0 -- XFAIL: works for if/else block: parentheses in conditional if (foo + bar) then a = a + 1 else a = a + 2 end a = 0 -- works for if/elseif/else block: 1 if foo then a = a + 1 elseif bar then a = a + 2 elseif baz then a = a + 3 end a = 0 -- works for if/elseif/else block: 2 if foo then a = a + 1 elseif bar then a = a + 2 elseif baz then a = a + 3 else a = a + 4 end a = 0 -- XFAIL: works for if/elseif/else block: 3 if foo then a = a + 1 elseif bar then a = a + 2 elseif baz then a = a + 3 else a = a + 4 end a = 0 -- XFAIL: works for if/elseif/else block: 4 if foo then a = a + 1 elseif bar then a = a + 2 elseif baz then a = a + 3 else a = a + 4 end a = 0 lua-mode-20210802/test/indentation-tests/issue-33.lua000066400000000000000000000007121410202764300221650ustar00rootroot00000000000000-- don't accumulate indentation after the expression a = { } b = { } a = { table_elt_indented } a = a + 5 + 10 this_should_be_unindented() -- here foobar should be indented as simple continuation statement a = a + dosmth( ) + foobar a = do_smth( do_smth_arg ) b = { table_elt0_indented, table_elt1_indented } this_should_be_unindented_too = { } this_should_be_unindented_three = etc lua-mode-20210802/test/indentation-tests/only-use-last-opener.lua000066400000000000000000000022051410202764300246130ustar00rootroot00000000000000-- Local Variables: -- lua-indent-close-paren-align: nil -- lua-indent-only-use-last-opener: t -- End: -- XFAIL: one param, nested table on same line as opener foobar({ a, b, c }) -- XFAIL: two params, nested table on same line as opener foobar(a, { b, c }) foobar({}, { b, c }) -- XFAIL: two aligned params, nested table on next line foobar({}, {1, 2, 3}) -- XFAIL: two aligned table params, first has nested tables foobar({{}, {1, 2, 3}}, { 4,5,6 }) foobar({{}, {1, 2, 3}}, { 4,5,6 } ) -- XFAIL: one nested table containing another table foobar({ {4, 5, 6} }) -- XFAIL: nested table with indentation: nested table on separate line foobar( a, { b, c }) foobar( a, { b, c } ) -- XFAIL: nested table with alignment: nested table on separate line foobar(a, { b, c }) foobar(a, { b, c } ) -- nested table with indentation: params after nested table foobar( { a, b }, c, d) foobar( { a, b }, c, d ) lua-mode-20210802/test/indentation-tests/repeat-until-block.lua000066400000000000000000000012441410202764300243140ustar00rootroot00000000000000-- works for repeat ... until blocks: 1 repeat a = a + 1 until foo + bar a = 0 -- works for repeat ... until blocks: 2 repeat a = a + 1 until foo a = 0 -- works for repeat ... until blocks: 3 repeat a = a + 1 until not foo a = 0 -- works for repeat ... until blocks: 4 repeat a = a + 1 until not foo a = 0 -- works for repeat ... until blocks: single line repeat a = a + 1 until not foo a = 0 -- works for repeat ... until blocks: single line with continuation 1 repeat a = a + 1 until not foo a = 0 -- XFAIL: works for repeat ... until blocks: single line with continuation 1 repeat a = a + 1 until not foo a = 0 lua-mode-20210802/test/indentation-tests/smoke.lua000066400000000000000000000000561410202764300217310ustar00rootroot00000000000000function hello() print("Hello, world") end lua-mode-20210802/test/indentation-tests/while-block.lua000066400000000000000000000021101410202764300230040ustar00rootroot00000000000000-- works for while ... do ... end blocks: 1 while foo + bar do a = a + 1 end a = 0 -- works for while ... do ... end blocks: 2 while foo + bar do a = a + 1 end a = 0 -- works for while ... do ... end blocks: 3 while foo + bar do a = a + 1 end a = 0 -- works for while ... do ... end blocks: 4 while foo + bar do a = a + 1 end a = 0 -- works for while ... do ... end blocks: 5 while foo + bar do a = a + 1 end a = 0 -- works for while ... do ... end blocks: 6 while ( foo) do a = a + 1 end a = 0 -- works for while ... do ... end blocks: 7 while ( foo ) do a = a + 1 end a = 0 -- works for while ... do ... end blocks: 8 while ( foo ) do a = a + 1 end a = 0 -- works for while ... do ... end blocks: single line while foo + bar do a = a + 1 end a = 0 -- works for while ... do ... end blocks: single line with continuation in body while foo + bar do a = a + 1 end a = 0 -- works for while ... do ... end blocks: single line with parentheses in body while foo + bar do a = (a + 1) end a = 0 lua-mode-20210802/test/test-electric-mode.el000066400000000000000000000054651410202764300204600ustar00rootroot00000000000000;; -*- flycheck-disabled-checkers: (emacs-lisp-checkdoc) -*- (load (concat (file-name-directory (or load-file-name (buffer-file-name) default-directory)) "utils.el") nil 'nomessage 'nosuffix) (require 'lua-mode) (describe "Test electric mode" (it "works with curly braces" (with-lua-buffer (setq-local blink-matching-paren nil) (make-local-variable 'electric-indent-mode) (electric-indent-mode 1) (execute-kbd-macro (kbd "return SPC foo SPC { M-j")) (execute-kbd-macro (kbd "'baz' M-j")) (expect (current-indentation) :to-be lua-indent-level) (execute-kbd-macro (kbd "}")) (expect (current-indentation) :to-be 0))) (it "works with parentheses" (with-lua-buffer (setq-local blink-matching-paren nil) (make-local-variable 'electric-indent-mode) (electric-indent-mode 1) (execute-kbd-macro (kbd "return SPC foo SPC ( M-j")) (execute-kbd-macro (kbd "'baz' M-j")) (should (eq (current-indentation) lua-indent-level)) (execute-kbd-macro (kbd ")")) (should (eq (current-indentation) 0)))) (it "works with end" (with-lua-buffer (execute-kbd-macro (kbd "if SPC foo SPC then M-j")) (execute-kbd-macro (kbd "'baz' M-j")) (should (eq (current-indentation) lua-indent-level)) (abbrev-mode 1) (execute-kbd-macro (kbd "end M-j")) (beginning-of-line 0) (should (eq (current-indentation) 0)))) (it "works with else" (with-lua-buffer (execute-kbd-macro (kbd "if SPC foo SPC then M-j")) (execute-kbd-macro (kbd "'baz' M-j")) (should (eq (current-indentation) lua-indent-level)) (abbrev-mode 1) (execute-kbd-macro (kbd "else M-j")) (beginning-of-line 0) (should (eq (current-indentation) 0)))) (it "works with elseif" (with-lua-buffer (execute-kbd-macro (kbd "if SPC foo SPC then")) (newline-and-indent) (execute-kbd-macro (kbd "'baz'")) (newline-and-indent) (should (eq (current-indentation) lua-indent-level)) (abbrev-mode 1) (execute-kbd-macro (kbd "elseif")) (newline-and-indent) (beginning-of-line 0) (should (eq (current-indentation) 0))))) (when (fboundp 'electric-pair-mode) (describe "Electric pair mode" (it "skips parens when electric-pair-skip-self is t" (let ((old-mode (if electric-pair-mode 1 0))) (unwind-protect (with-lua-buffer (setq-local blink-matching-paren nil) (setq-local electric-pair-skip-self t) (setq-local lua-electric-flag t) (electric-pair-mode 1) (execute-kbd-macro "(") (should (string= (buffer-string) "()")) (execute-kbd-macro ")") (should (string= (buffer-string) "()"))) (electric-pair-mode old-mode)))))) lua-mode-20210802/test/test-fill.el000066400000000000000000000066551410202764300166740ustar00rootroot00000000000000;; -*- flycheck-disabled-checkers: (emacs-lisp-checkdoc) -*- (load (concat (file-name-directory (or load-file-name (buffer-file-name) default-directory)) "utils.el") nil 'nomessage 'nosuffix) (defun expect-filled-as (strs etalon &optional look-at) (let ((result-str (lua-buffer-strs (let ((fill-column 10)) (lua-insert-goto-<> strs) (execute-kbd-macro (kbd "M-q")) (when look-at (expect (point) :to-precede look-at)))))) (expect result-str :to-equal etalon))) (describe "Test fill-paragraph" (it "fills single-line comment" (expect-filled-as '("<>-- foo bar baz qux") '("-- foo bar" "-- baz qux") "-- foo bar")) (it "fills comment after code" (expect-filled-as '("<>foo -- bar baz") '("foo -- bar" " -- baz"))) (xit "fills multiline comment" ;; Right now it ends up with something like this: ;; ;; --[[ ab c ;; --d ]] (expect-filled-as '("<>--[[ ab c d ]]") '("--[[ ab c" " d ]]"))) (it "does not spill comments into code (issue #25)" (expect-filled-as '("<>" "-- foo bar baz qux" "foo_func()") '("" "-- foo bar" "-- baz qux" "foo_func()")))) (describe "Test fill-paragraph preserves point position" (it "doesn't move point if nothing has changed" (expect-filled-as '("<>-- foo bar") '("-- foo bar") "-- foo bar") (expect-filled-as '("-- <>foo bar") '("-- foo bar") "foo bar") (expect-filled-as '("-- foo <>bar") '("-- foo bar") "bar")) (it "doesn't move point in refilled region" (expect-filled-as '("--<> foo bar baz qux") '("-- foo bar" "-- baz qux") " foo bar\n") (expect-filled-as '("-- <>foo bar baz qux") '("-- foo bar" "-- baz qux") "foo bar\n") (expect-filled-as '("-- <> foo bar baz qux") '("-- foo" "-- bar" "-- baz" "-- qux") " foo\n") (expect-filled-as '("-- foo bar <>baz qux") '("-- foo bar" "-- baz qux") "baz qux") (expect-filled-as '("-- foo bar<> baz qux") '("-- foo bar" "-- baz qux") "\n-- baz qux") (expect-filled-as '("-- foo bar baz qux<>") '("-- foo bar" "-- baz qux") "$") ) (it "doesn't move point if nothing has changed (multi-line)" (expect-filled-as '("--[[ a <>b]]") '("--[[ a b]]") "b]]") (expect-filled-as '("--[[ a<>" " b" "]]") '("--[[ a" " b" "]]") "\n b\n]]") ) ) lua-mode-20210802/test/test-font-lock.el000066400000000000000000000226661410202764300176420ustar00rootroot00000000000000;; -*- flycheck-disabled-checkers: (emacs-lisp-checkdoc) -*- (load (concat (file-name-directory (or load-file-name (buffer-file-name) default-directory)) "utils.el") nil 'nomessage 'nosuffix) (require 'buttercup) (describe "Fontification of built-ins" (it "fontifies built-ins" (expect "table.sort(foobar)" :to-be-fontified-as '(("table" builtin "sort" builtin)))) (it "fontifies built-ins with spaces between members" (expect "\ table.sort(foobar) table .sort(foobar) table. sort(foobar)" :to-be-fontified-as '(("table" builtin "sort" builtin) ("table" builtin "sort" builtin) ("table" builtin "sort" builtin)))) (it "doesn't fontify things that look like built-ins" (expect "\ foo.table.sort(foobar) foo. table.sort(foobar) foo .table.sort(foobar) foo:table.sort(foobar) foo: table.sort(foobar) foo :table.sort(foobar) _table.sort(foobar) table_.sort(foobar)" :to-be-fontified-as '(nil nil nil nil nil nil nil nil nil))) (it "fontifies built-in class if method is not built-in" (expect "\ table ._sort(foobar) table. sort_(foobar)" :to-be-fontified-as '(("table" builtin) ("table" builtin)))) (it "fontifies built-ins after concatenation operator" (expect "a .. table.concat(foobar, delim)" :to-be-fontified-as '(("table" builtin "concat" builtin))))) (describe "Fontification of constants" (it "fontifies constants" (expect "a = { nil, true, false}" :to-be-fontified-as '(("nil" constant "true" constant "false" constant)))) (it "fontifies constants used as attributes" (expect "a = { nil, true, false}" :to-be-fontified-as '(("nil" constant "true" constant "false" constant))))) (describe "Fontification of keywords" (it "fontifies keywords" (expect "do foo(5) end" :to-be-fontified-as '(("do" keyword "end" keyword))) (expect "_do foo(5) end_" :to-be-fontified-as '(nil))) (it "fontifies keywords used as attributes" ;; Hint user that keywords cannot be used like that (expect "foo(5).end" :to-be-fontified-as '(("end" keyword))) (expect "foo(5):end" :to-be-fontified-as '(("end" keyword))))) (describe "Fontification of variables" (it "fontifies \"local foo, bar, baz = 1, 2, 3\"" (expect "local foo,bar , baz = 1, 2, 3" :to-be-fontified-as '(("local" keyword "foo" variable-name "bar" variable-name "baz" variable-name)))) (it "fontifies \"local foo, bar, baz\"" (expect "local foo,bar , baz" :to-be-fontified-as '(("local" keyword "foo" variable-name "bar" variable-name "baz" variable-name)))) (it "fontifies \"local x =\" at end of buffer" (expect "local x =" :to-be-fontified-as '(("local" keyword "x" variable-name)))) (it "fontifies local \"x =\" at end of line" ;; Issue #163 (expect "local x = foo = bar" :to-be-fontified-as '(("local" keyword "x" variable-name) () ()))) (it "does not fontify \"for\" inside strings" ;; Issue #157 (expect "local xx = [[ for abc def ]]" :to-be-fontified-as '(("local" keyword "xx" variable-name "[[" string) ("for abc def" string) ("]]" string)))) (it "fontifies \"for x123 =\"" (expect "for x123 =" :to-be-fontified-as '(("for" keyword "x123" variable-name)))) (it "fontifies \"for x, y, z\"" (expect "for x, y, z in " :to-be-fontified-as '(("for" keyword "x" variable-name "y" variable-name "z" variable-name "in" keyword))))) (describe "Fontification of function headers" (it "fontifies function (...) headers" (expect "function bar(x, y) end" :to-be-fontified-as '(("function" keyword "bar" function-name "x" variable-name "y" variable-name "end" keyword)))) (it "fontifies local function (...) headers" (expect "local function baz(x, y) end" :to-be-fontified-as '(("local" keyword "function" keyword "baz" function-name "x" variable-name "y" variable-name "end" keyword)))) (it "fontifies = function (...) headers" (expect "qux = function(x, y) end" :to-be-fontified-as '(("qux" function-name "function" keyword "x" variable-name "y" variable-name "end" keyword)))) (it "fontifies local = function (...) headers" (expect "local quux = function(x, y) end" :to-be-fontified-as '(("local" keyword "quux" function-name "function" keyword "x" variable-name "y" variable-name "end" keyword)))) (it "fontifies parameters in function literals" (expect "foo(function(x, y))" :to-be-fontified-as '(("function" keyword "x" variable-name "y" variable-name)))) (it "fontifies different variations of headers altogether" (expect ;; Check all defun variants, check embedded defuns "\ function foo() function bar() end local function baz() end qux = function() end local quux = function() end end" :to-be-fontified-as '(("function" keyword "foo" function-name) ("function" keyword "bar" function-name "end" keyword) ("local" keyword "function" keyword "baz" function-name "end" keyword) ("qux" function-name "function" keyword "end" keyword) ("local" keyword "quux" function-name "function" keyword "end" keyword) ("end" keyword)))) (it "fontifies headers inside tables" (expect "\ somefunc { function() end, foobar = function() end, [\"quxquux\"] = function() end }" :to-be-fontified-as '(nil ("function" keyword "end" keyword) ("foobar" function-name "function" keyword "end" keyword) ("\"quxquux\"" string "function" keyword "end" keyword) nil))) (it "does not fail on issue #59 again" (expect "\ local foo = function() ; end -- and local function foo() ; end" :to-be-fontified-as '(("local" keyword "foo" function-name "function" keyword) nil ("end" keyword) ("-- " comment-delimiter "and" comment) ("local" keyword "function" keyword "foo" function-name) nil ("end" keyword)))) (it "does not choke on function names with underscores" (expect ;; Check all defun variants, check embedded defuns "\ function foo() function bar_bar() end local function baz_baz() end qux_qux = function() end local quux_quux = function() end end" :to-be-fontified-as '(("function" keyword "foo" function-name) ("function" keyword "bar_bar" function-name "end" keyword) ("local" keyword "function" keyword "baz_baz" function-name "end" keyword) ("qux_qux" function-name "function" keyword "end" keyword) ("local" keyword "quux_quux" function-name "function" keyword "end" keyword) ("end" keyword))))) (describe "Fontification of goto labels" (it "fontifies simple goto labels" (expect "\ goto foo ::foo::" :to-be-fontified-as '(("goto" keyword "foo" constant) ("::foo::" constant)))) (it "fontifies ::labels:: written after code" (expect "\ local foo = 'test' ::f12o:: goto f12o" :to-be-fontified-as '(("local" keyword "foo" variable-name "'test'" string "::f12o::" constant) ("goto" keyword "f12o" constant)))) (it "fontifies labels with spaces before and after \"::\"" ;; With spaces after and before "::" (expect ":: foo ::" :to-be-fontified-as '((":: foo ::" constant)))) ;; Don't font lock labels when substring "goto" appears as a suffix ;; of another variable (it "does not fontify after symbols ending with \"goto\"" (expect "JUNKgoto foo" :to-be-fontified-as '(nil)))) (describe "Fontification of LuaDoc keywords" (it "works" (expect "\ -- @author foo baz -- @copyright foo baz -- @field foo baz -- @param foo baz -- @release foo baz -- @return foo baz -- @see foo baz -- @usage foo baz -- @class foo baz -- @description foo baz -- @name foo baz" :to-be-fontified-as '(("-- " comment-delimiter "@author" keyword " foo baz" comment) ("-- " comment-delimiter "@copyright" keyword " foo baz" comment) ("-- " comment-delimiter "@field" keyword " foo baz" comment) ("-- " comment-delimiter "@param" keyword " " comment "foo" variable-name " baz" comment) ("-- " comment-delimiter "@release" keyword " foo baz" comment) ("-- " comment-delimiter "@return" keyword " foo baz" comment) ("-- " comment-delimiter "@see" keyword " foo baz" comment) ("-- " comment-delimiter "@usage" keyword " foo baz" comment) ("-- " comment-delimiter "@class" keyword " " comment "foo" variable-name " baz" comment) ("-- " comment-delimiter "@description" keyword " foo baz" comment) ("-- " comment-delimiter "@name" keyword " " comment "foo" variable-name " baz" comment))))) lua-mode-20210802/test/test-funcname-at-point.el000066400000000000000000000017431410202764300212640ustar00rootroot00000000000000;;; test-funcname-at-point.el --- Test `lua-funcname-at-point' ;;; Commentary: ;; Ensure that `lua-funcname-at-point' works correctly in all intended ;; circumstances. ;;; Code: (describe "Test `lua-funcname-at-point'." (it "handles trailing periods" (with-temp-buffer (insert "table.insert.") (backward-char) (expect (lua-funcname-at-point) :to-equal "table.insert"))) (it "handles point being in the middle" (with-temp-buffer (insert "table.") (save-excursion (insert "insert.")) (expect (lua-funcname-at-point) :to-equal "table.insert"))) (it "handles point being at the start of the buffer" (with-temp-buffer (save-excursion (insert "table.insert.")) (expect (lua-funcname-at-point) :to-equal "table.insert"))) (it "handles identifiers before point" (with-temp-buffer (insert "table.insert.") (expect (lua-funcname-at-point) :to-equal "table.insert")))) ;;; test-funcname-at-point.el ends here lua-mode-20210802/test/test-generic.el000066400000000000000000000212441410202764300173510ustar00rootroot00000000000000;; -*- flycheck-disabled-checkers: (emacs-lisp-checkdoc) -*- (load (concat (file-name-directory (or load-file-name (buffer-file-name) default-directory)) "utils.el") nil 'nomessage 'nosuffix) (require 'imenu) (describe "lua-forward-sexp" (it "properly scans through curly braces" (with-lua-buffer (lua-insert-goto-<> '("local x = <>function() return {{}} end" "" "function foobar() end")) (lua-forward-sexp) (expect (looking-back (rx "x = function() return {{}} end") (line-beginning-position))))) (it "scans through then .. end block" (with-lua-buffer (lua-insert-goto-<> '("if foo <>then" " return bar" "--[[end here]] end")) (lua-forward-sexp) (expect (looking-back (rx "--[[end here]] end") (line-beginning-position)))))) (describe "Check that beginning-of-defun works with " (it "handles differed function headers" (with-lua-buffer (lua-insert-goto-<> '("function foobar()" "<>" "end")) (beginning-of-defun) (expect (looking-at (rx "function foobar()")))) (with-lua-buffer (lua-insert-goto-<> '("local function foobar()" "<>" "end")) (beginning-of-defun) (expect (looking-at "local function foobar()"))) (with-lua-buffer (lua-insert-goto-<> '("local foobar = function()" "<>" "end")) (beginning-of-defun) (expect (looking-at (rx "local foobar = function()")))) (with-lua-buffer (lua-insert-goto-<> '("foobar = function()" "<>" "end")) (beginning-of-defun) (expect (looking-at (rx "foobar = function()"))))) (it "accepts dots and colons" (with-lua-buffer (lua-insert-goto-<> '("foo.bar = function (x,y,z)" "<>" "end")) (beginning-of-defun) (expect (looking-at (rx "foo.bar = function (x,y,z)")))) (with-lua-buffer (lua-insert-goto-<> '("function foo.bar:baz (x,y,z)" "<>" "end")) (beginning-of-defun) (expect (looking-at (rx "function foo.bar:baz (x,y,z)")))))) (describe "lua-mode" (it "is derived from prog-mode" (with-lua-buffer (expect (derived-mode-p 'prog-mode))))) (describe "imenu integration" (it "indexes functions" (with-lua-buffer (insert "\ function foo() function bar() end local function baz() end qux = function() end local quux = function() end end ") (expect (mapcar 'car (funcall imenu-create-index-function)) :to-equal '("foo" "bar" "baz" "qux" "quux")))) (it "indexes require statements" (with-lua-buffer (insert "\ foo = require (\"foo\") local bar = require (\"bar\") ") (expect (mapcar (lambda (item) (cons (car item) (if (listp (cdr item)) (mapcar 'car (cdr item)) -1))) (funcall imenu-create-index-function)) :to-equal '(("Requires" . ("foo" "bar"))))))) (describe "lua-backward-up-list" (it "doesn't move point when no parent block open token exists" (expect "foo = bar<2><1>" :with-point-at "<1>" :after-executing (condition-case nil (lua-backward-up-list) (scan-error nil)) :to-end-up-at "<2>")) (it "doesn't move point when cannot skip intermediate close token" (expect "foo, bar = baz}, qux<2><1>" :with-point-at "<1>" :after-executing (condition-case nil (lua-backward-up-list) (scan-error nil)) :to-end-up-at "<2>")) (it "works for (" (expect "foo<2>(<1>" :with-point-at "<1>" :after-executing (lua-backward-up-list) :to-end-up-at "<2>")) (it "works for {" (expect "\ local foo = <2>{ 1, 2,<1> 3, }" :with-point-at "<1>" :after-executing (lua-backward-up-list) :to-end-up-at "<2>")) (it "works for else" (expect "if foo then 123 <2>else 456<1> end" :with-point-at "<1>" :after-executing (lua-backward-up-list) :to-end-up-at "<2>")) (it "works for if/else/end" (expect "if foo then 123 <2>else 456<1> end" :with-point-at "<1>" :after-executing (lua-backward-up-list) :to-end-up-at "<2>")) (it "works for do blocks" (expect "while foo <2>do print(123) <1>end" :with-point-at "<1>" :after-executing (lua-backward-up-list) :to-end-up-at "<2>")) (it "works for while/do" (expect "<2>while foo <1>do print(123) end" :with-point-at "<1>" :after-executing (lua-backward-up-list) :to-end-up-at "<2>")) (it "skips complete while/do block" (expect "<2>do while true do print(123) end <1>end" :with-point-at "<1>" :after-executing (lua-backward-up-list) :to-end-up-at "<2>")) (it "skips complete repeat/until block" (expect "<2>do repeat print(123) until foo <1>end" :with-point-at "<1>" :after-executing (lua-backward-up-list) :to-end-up-at "<2>")) (it "skips complete if/elseif/else/end block" (expect "<2>do if foo then bar() elseif baz() then qux() else quux() end <1>end" :with-point-at "<1>" :after-executing (lua-backward-up-list) :to-end-up-at "<2>")) (it "skips from else to previous then" (expect "if foo <2>then bar() <1>else baz() end" :with-point-at "<1>" :after-executing (lua-backward-up-list) :to-end-up-at "<2>")) (it "skips from end to previous else" (expect "if foo then bar() <2>else baz() <1>end" :with-point-at "<1>" :after-executing (lua-backward-up-list) :to-end-up-at "<2>"))) (describe "lua-goto-matching-block" (it "works for do...end block" (expect (lua-goto-matching-block) :to-move-point-from-1-to-2 "<2>do if true then print(123) end <1>end") (expect (lua-goto-matching-block) :to-move-point-from-1-to-2 "<2>do if true then print(123) end e<1>nd") (expect (lua-goto-matching-block) :to-move-point-from-1-to-2 "<2>do if true then print(123) end en<1>d") (expect (lua-goto-matching-block) :to-move-point-from-1-to-2 "<1>do if true then print(123) end <2>end") (expect (lua-goto-matching-block) :to-move-point-from-1-to-2 "d<1>o if true then print(123) end <2>end")) (it "works for repeat...until block" (expect (lua-goto-matching-block) :to-move-point-from-1-to-2 "<1>repeat if true then print(123) end <2>until true") (expect (lua-goto-matching-block) :to-move-point-from-1-to-2 "<2>repeat if true then print(123) end <1>until true")) (it "works for while...do...end block" (expect (lua-goto-matching-block) :to-move-point-from-1-to-2 "<1>while foo() do if true then print(123) end <2>end") (expect (lua-goto-matching-block) :to-move-point-from-1-to-2 "<2>while foo() do if true then print(123) end <1>end") (expect (lua-goto-matching-block) :to-move-point-from-1-to-2 "while foo() <1>do if true then print(123) end <2>end") ;; The next line is a valid statement that ensures ;; "lua-goto-matching-block" can distinguish between "while..do" and ;; "do..end" (expect (lua-goto-matching-block) :to-move-point-from-1-to-2 "<1>while false do print(123) <2>end do print(123) end") (expect (lua-goto-matching-block) :to-move-point-from-1-to-2 "while false do print(123) end <1>do print(123) <2>end")) (it "works for if..elseif..else..end block" (expect (lua-goto-matching-block) :to-move-point-from-1-to-2 "<1>if true then foo() elseif false then bar() else baz() <2>end") (expect (lua-goto-matching-block) :to-move-point-from-1-to-2 "<2>if true then foo() elseif false then bar() else baz() <1>end") (expect (lua-goto-matching-block) :to-move-point-from-1-to-2 "<2>if true then foo() elseif false then bar() <1>else baz() end") (expect (lua-goto-matching-block) :to-move-point-from-1-to-2 "<2>if true then foo() elseif false <1>then bar() else baz() end") (expect (lua-goto-matching-block) :to-move-point-from-1-to-2 "<2>if true then foo() <1>elseif false then bar() else baz() end") (expect (lua-goto-matching-block) :to-move-point-from-1-to-2 "<2>if true <1>then foo() elseif false then bar() else baz() end"))) lua-mode-20210802/test/test-indentation.el000066400000000000000000000142771410202764300202610ustar00rootroot00000000000000;; -*- flycheck-disabled-checkers: (emacs-lisp-checkdoc) -*- ;; -*- lexical-binding: t -*- (load (concat (file-name-directory (or load-file-name (buffer-file-name) default-directory)) "utils.el") nil 'nomessage 'nosuffix) (require 'buttercup) (require 'cl-lib) (defun lua--get-indentation-test-sections (file-path) (with-temp-buffer (insert-file-contents-literally file-path) (hack-local-variables) (let (results section-name (begin (point-min)) end cur-str (next-section-name "start")) (goto-char (point-min)) (while next-section-name ;; Scan towards the next comment or end of file, save the comment as ;; the name for the section that comes AFTER the current one. (setq next-section-name (when (re-search-forward "^--\\(.*\\)" nil 'noerror) (lua--string-trim (match-string-no-properties 1)))) ;; Record current section bounds and contents (setq end (if next-section-name (match-beginning 0) (point-max))) (setq cur-str (lua--string-trim (buffer-substring-no-properties begin end))) ;; Save current section to be returned (if (> (length cur-str) 0) (push (list (or section-name (format "section %d" (1+ (length results)))) cur-str file-local-variables-alist) results)) ;; Transition to the next iteration of the loop. (setq section-name next-section-name) (setq begin (point))) (nreverse results)))) (defun lua--indentation-test-make-it-or-xit-clause (x) (let ((it-or-xit (if (string-match "XFAIL" (car x)) 'xit 'it))) (eval `(,it-or-xit ,(format "%s" (car x)) (let ((lua-code ,(cadr x)) ,@(mapcar (lambda (alist-cons) (list (car alist-cons) (cdr alist-cons))) ;; cl-caddr here is to support Emacs<26 that don't have caddr. (cl-caddr x))) (expect lua-code :to-be-reindented-the-same-way)))))) (let* ((current-path (or load-file-name (buffer-file-name) default-directory)) (indentation-tests-dir (concat (file-name-directory current-path) "indentation-tests")) (indentation-tests (directory-files indentation-tests-dir nil ".*\.lua$" 'nosort))) (mapcar (lambda (test-file) (let ((file-path (expand-file-name test-file indentation-tests-dir))) (describe (format "Indentation test `%s'" test-file) (mapcar #'lua--indentation-test-make-it-or-xit-clause (lua--get-indentation-test-sections file-path))))) indentation-tests)) (describe "Continuation lines" (lua--parametrize-tests (binop) (("+") ("-") ("*") ("/") ("^") ("%") ("..") ("<") ("<=") (">") (">=") ("==") ("~=") ("and") ("or")) :it (format "are indented before/after binary operators: %s" binop) (expect (replace-regexp-in-string "BINOP" binop "\ a = foo BINOP bar" 'fixedcase) :to-be-reindented-the-same-way) (expect (replace-regexp-in-string "BINOP" binop "\ a = foo BINOP bar" 'fixedcase) :to-be-reindented-the-same-way)) ) ;; ( ;; (xit "are indented before/after unary operators" ;; (expect (lua--reindent-like "\ ;; foo = bar ;; -#some_str")) ;; (cl-dolist (unop '("-" "#" "not ")) ;; (expect (lua--reindent-like (replace-regexp-in-string "<>" unop "\ ;; foobar(qux, ;; <>quux)"))) ;; (expect (lua--reindent-like (replace-regexp-in-string "<>" unop "\ ;; foobar(qux, xyzzy ;; <>quux)"))) ;; (expect (lua--reindent-like (replace-regexp-in-string "<>" unop "\ ;; foobar( ;; <>quux)"))) ;; (expect (lua--reindent-like (replace-regexp-in-string "<>" unop "\ ;; x = {qux, ;; <>quux}"))) ;; (expect (lua--reindent-like (replace-regexp-in-string "<>" unop "\ ;; x = {qux; ;; <>quux}"))) ;; (expect (lua--reindent-like (replace-regexp-in-string "<>" unop "\ ;; x = {qux, xyzzy ;; <>quux}"))) ;; (expect (lua--reindent-like (replace-regexp-in-string "<>" unop "\ ;; x = { ;; <>quux ;; }")))))) (describe "Function indentation" (it "indents function call arguments" (expect "\ foobar( a, b, c)" :to-be-reindented-the-same-way) (expect "\ foobar( a, b, c)" :to-be-reindented-the-same-way) (expect "\ foobar( a, b, c )" :to-be-reindented-the-same-way) (expect "\ foobar(a, b, c)" :to-be-reindented-the-same-way) (expect "\ foobar{ a, b, c }" :to-be-reindented-the-same-way)) (it "indent blocks with lua-indent-nested-block-content-align" (let ((lua-indent-nested-block-content-align nil)) (expect "\ call_some_fn( something, { val = 5, another = 6, } )" :to-be-reindented-the-same-way) (expect "\ local def = { some_very_long_name = { fn = function() return true end } }" :to-be-reindented-the-same-way) )) (it "indent blocks with lua-indent-close-paren-align" (let ((lua-indent-close-paren-align nil)) (expect "\ local foo = setmetatable( { a = 4, b = 5, }, { __index = some_func, } )" :to-be-reindented-the-same-way) )) (it "indents nested tables with alternative block indenting" (let ((lua-indent-nested-block-content-align nil) (lua-indent-close-paren-align nil)) (expect "\ foobar({ a, b, c })" :to-be-reindented-the-same-way) (expect "\ foobar(a, { b, c })" :to-be-reindented-the-same-way) (expect "\ foobar( a, { b, c })" :to-be-reindented-the-same-way) (expect "\ foobar( a, { b, c } )" :to-be-reindented-the-same-way) (expect "\ foobar(a, { b, c })" :to-be-reindented-the-same-way) (expect "\ foobar(a, { b, c } )" :to-be-reindented-the-same-way) (expect "\ foobar( { a, b }, c, d )" :to-be-reindented-the-same-way) ))) (ert-deftest lua-indentation-keywords-with-special-characters () (expect "\ do foobar = _do end" :to-be-reindented-the-same-way)) lua-mode-20210802/test/test-inferior-process.el000066400000000000000000000140701410202764300212250ustar00rootroot00000000000000;; -*- flycheck-disabled-checkers: (emacs-lisp-checkdoc) -*- (load (concat (file-name-directory (or load-file-name (buffer-file-name) default-directory)) "utils.el") nil 'nomessage 'nosuffix) (require 'cl-lib) (require 'comint) (describe "Hiding process buffer does not switch current window" (it "when process is active" (with-lua-buffer (let ((cur-buf (current-buffer))) (expect (get-buffer-window cur-buf)) (lua-start-process) (lua-hide-process-buffer) (expect (get-buffer-window cur-buf))))) (it "and does not signal when process is already killed" (with-lua-buffer (let ((cur-buf (current-buffer))) (lua-start-process) (lua-kill-process) (lua-hide-process-buffer) (expect (get-buffer-window cur-buf))))) (it "when process is not started" (with-lua-buffer (let ((cur-buf (current-buffer))) (expect lua-process-buffer :to-be nil) (lua-hide-process-buffer) (expect (get-buffer-window cur-buf)))))) (describe "Compilation minor mode" (it "sets comint-prompt-regexp in process buffer" (with-lua-buffer (lua-start-process) (with-current-buffer lua-process-buffer (expect "" :not :to-match comint-prompt-regexp) (expect "> " :to-match comint-prompt-regexp)) (expect comint-prompt-regexp :to-equal "^")) (expect comint-prompt-regexp :to-equal "^"))) (require 'compile) (if (fboundp 'compilation--loc->file-struct) (defun get-error-file (err-info) (caar (compilation--loc->file-struct (compilation--message->loc (compilation-next-error 0))))) (defun get-error-file (err-info) (caar (nth 2 (car err-info))))) (describe "Fontification in compilation buffer" (xit "fontifies runtime error messages" (with-lua-buffer (insert "\ function bar() error(123) end function foo() bar() end ") (rename-buffer "test-send-runtime-error.lua" 'unique) ;; By default non-nil compilation-message-face is appended to ;; compilation-error faces, let's simplify the checks. (let ((compilation-message-face nil)) (lua-send-buffer) (lua-send-string "foo()") ;; Make sure to wait enough to get all the output from the subprocess. (while (accept-process-output lua-process 0 200)) (with-current-buffer lua-process-buffer (expect (get-buffer-line-faces) :to-equal '(nil ;; motd line (not highlighted) nil ;; first prompt (also not highlighted) ("test-send-runtime-error.lua" compilation-error "2" compilation-line-number) ;; error message nil ;; stack traceback nil ;; in function error ("test-send-runtime-error.lua" compilation-error "2" compilation-line-number) ;; in 'bar' ("test-send-runtime-error.lua" compilation-error "6" compilation-line-number) ;; in 'foo' ("stdin" compilation-error "1" compilation-line-number) nil ;; in main chunk nil)))))) (xit "fontifies syntax error messages" (with-lua-buffer (rename-buffer "test-send-syntax-error.lua") (insert "\ function () end ") ;; By default non-nil compilation-message-face is appended to ;; compilation-error faces, let's simplify the checks. (let ((compilation-message-face nil)) (lua-send-buffer) (while (accept-process-output lua-process 0 200)) (with-current-buffer lua-process-buffer (expect (get-buffer-line-faces) :to-equal '(nil ;; motd line, no highlight nil ;; first prompt, also no highlight (;; "stdin" is being highlighted here because compilation mode ;; thinks it is some sort of "make: ..." message. This doesn't ;; happen in wildlife, because there's a default message face ;; (underline) that prevents this. In tests this is turned off, ;; see `(compilation-message-face nil)' above, to simplify ;; font-lock face checks. "stdin" font-lock-function-name-face "test-send-syntax-error.lua" compilation-error "1" compilation-line-number) ;; stacktrace with misc info, no font-lock nil nil ("stdin" compilation-error "1" compilation-line-number) ("stdin" compilation-error "1" compilation-line-number) nil nil)))))) ;; (it "does not ask for file on \"stdin:NN\" errors" ;; (let ((fname (make-temp-file "lua_mode_test" nil ".lua")) ;; buf) ;; (unwind-protect ;; (progn ;; (save-current-buffer ;; (setq buf (find-file fname)) ;; (insert "function () end") ;; ;; Make sure the buffer can be killed cleanly ;; (set-buffer-modified-p nil) ;; (lua-send-buffer) ;; (while (accept-process-output lua-process 0 200)) ;; (with-current-buffer lua-process-buffer ;; (font-lock-fontify-buffer)) ;; (cl-letf ;; (((symbol-function 'read-file-name) ;; (lambda (&rest args) ;; (error "read-file-name must not be called")))) ;; (expect (next-error) :to-be nil) ;; (with-current-buffer lua-process-buffer ;; (expect fname :to-equal ;; (get-error-file (compilation-next-error 0)))) ;; (expect (next-error) :to-be nil) ;; (with-current-buffer lua-process-buffer ;; (expect "stdin" :to-equal ;; (get-error-file (compilation-next-error 0))))))) ;; (when buf ;; (kill-buffer buf)) ;; (delete-file fname) ;; (kill-buffer "*lua*")))) ) (describe "String escaping" (it "Escapes literal tabs" (expect (string= (lua-make-lua-string "\ -- comment indented with a tab") "'\\t-- comment indented with a tab'")))) lua-mode-20210802/test/test-process.el000066400000000000000000000013501410202764300174070ustar00rootroot00000000000000;;; test-funcname-at-point.el --- Test the repl functions ;;; Commentary: ;; Test functions to interact with the REPL. ;;; Code: (describe "`lua-start-process'" (it "doesn't hang for an already-running process" ;; Acquire a *lua* repl buffer (save-current-buffer (call-interactively #'lua-start-process) ;; Input some text (with-current-buffer lua-process-buffer (insert "table.insert")) (switch-to-buffer (get-buffer-create "*scratch*")) ;; Try restarting the repl buffer (call-interactively #'lua-start-process) ;; `lua-start-process' shouldn't hang, and it should have switched back. (expect (current-buffer) :to-be lua-process-buffer)))) ;;; test-process.el ends here lua-mode-20210802/test/test-strings-and-comments.el000066400000000000000000000463341410202764300220200ustar00rootroot00000000000000;; -*- flycheck-disabled-checkers: (emacs-lisp-checkdoc) -*- (load (concat (file-name-directory (or load-file-name (buffer-file-name) default-directory)) "utils.el") nil 'nomessage 'nosuffix) (describe "Test indent-new-comment-line" (it "works with -- ..." (expect (lua-buffer-strs (lua-insert-goto-<> '("-- foobar <>")) (execute-kbd-macro (kbd "M-j"))) :to-equal '("-- foobar" "-- ")) (expect (lua-buffer-strs (lua-insert-goto-<> '("xyzzy -- foobar <>")) (execute-kbd-macro (kbd "M-j"))) :to-equal '("xyzzy -- foobar" "-- ")) (expect (lua-buffer-strs (lua-insert-goto-<> '("xyz<> xyzzy -- foobar")) (execute-kbd-macro (kbd "M-j"))) :to-equal '("xyz" "xyzzy -- foobar"))) (it "works with ---- ...." (expect (lua-buffer-strs (lua-insert-goto-<> '("---- foobar <>")) (execute-kbd-macro (kbd "M-j"))) :to-equal '("---- foobar" "---- ")) (expect (lua-buffer-strs (lua-insert-goto-<> '("xyzzy ---- foobar <>")) (execute-kbd-macro (kbd "M-j"))) :to-equal '("xyzzy ---- foobar" "---- "))) (it "doesn't recognize \"--\" inside strings and comments" (expect (lua-buffer-strs (lua-insert-goto-<> '("\"-- \" .. foobar <>")) (execute-kbd-macro (kbd "M-j"))) :to-equal '("\"-- \" .. foobar" "")) (expect (lua-buffer-strs (lua-insert-goto-<> '("'-- ' .. foobar <>")) (execute-kbd-macro (kbd "M-j"))) :to-equal '("'-- ' .. foobar" "")) (expect (lua-buffer-strs (lua-insert-goto-<> '("[[-- ]] .. foobar <>")) (execute-kbd-macro (kbd "M-j"))) :to-equal '("[[-- ]] .. foobar" "")) (expect (lua-buffer-strs (lua-insert-goto-<> '("--[[-- ]] .. foobar <>")) (execute-kbd-macro (kbd "M-j"))) :to-equal '("--[[-- ]] .. foobar" "")) (expect (lua-buffer-strs (lua-insert-goto-<> '("---[[-- ]] .. foobar <>")) (execute-kbd-macro (kbd "M-j"))) :to-equal '("---[[-- ]] .. foobar" "---"))) (it "works when the comment is empty" (expect (lua-buffer-strs (lua-insert-goto-<> '("-- <>")) (execute-kbd-macro (kbd "M-j"))) :to-equal '("--" "--")) ;; Let's make sure that whitespace is optional. (expect (lua-buffer-strs (lua-insert-goto-<> '("--<>")) (execute-kbd-macro (kbd "M-j"))) :to-equal '("--" "--")))) (describe "lua-comment-start-pos" ;; Single-line comments (it "returns beginning of single-line comment if inside" (with-lua-buffer (lua-insert-goto-<> '("-- <>")) (expect (lua-comment-start-pos) :to-equal 1))) (it "returns beginning of single-line comment if between delimiters" (with-lua-buffer (lua-insert-goto-<> '("-<>- ")) (expect (lua-comment-start-pos) :to-equal 1))) (it "returns nil if before delimiters" (with-lua-buffer (lua-insert-goto-<> '("<>-- ")) (expect (lua-comment-start-pos) :to-equal nil))) (it "returns nil if before single-line comment" (with-lua-buffer (lua-insert-goto-<> '("<>" "-- ")) (expect (lua-comment-start-pos) :to-equal nil))) (it "returns nil if after single-line comment" (with-lua-buffer (lua-insert-goto-<> '("--" "<>")) (expect (lua-comment-start-pos) :to-equal nil))) ;; Single-line comments + strings (it "returns nil if inside single-line string" (with-lua-buffer (lua-insert-goto-<> '("'--<>'")) (expect (lua-comment-start-pos) :to-equal nil))) (it "returns nil if inside multi-line string" (with-lua-buffer (lua-insert-goto-<> '("[[--<>]]")) (expect (lua-comment-start-pos) :to-equal nil))) ;; Multi-line comments (it "returns beginning of multi-line comment if inside 1" (with-lua-buffer (lua-insert-goto-<> '("--[[<> ]]")) (expect (lua-comment-start-pos) :to-equal 1))) (it "returns beginning of multi-line comment if inside 2" (with-lua-buffer (lua-insert-goto-<> '("--[[<>" "]]")) (expect (lua-comment-start-pos) :to-equal 1))) (it "returns beginning of multi-line comment if inside 3" (with-lua-buffer (lua-insert-goto-<> '("--[[" "<>]]")) (expect (lua-comment-start-pos) :to-equal 1))) (it "returns beginning of multi-line comment if between delimiters 1" (with-lua-buffer (lua-insert-goto-<> '("-<>-[[ ]]")) (expect (lua-comment-start-pos) :to-equal 1))) (it "returns beginning of single-line comment if between delimiters 2" (with-lua-buffer (lua-insert-goto-<> '("--<>[[ ]]")) (expect (lua-comment-start-pos) :to-equal 1))) (it "returns beginning of multi-line comment if between delimiters 3" (with-lua-buffer (lua-insert-goto-<> '("--[<>[ ]]")) (expect (lua-comment-start-pos) :to-equal 1))) (it "returns beginning of multi-line comment if between delimiters 4" (with-lua-buffer (lua-insert-goto-<> '("--[=<>[ ]]")) (expect (lua-comment-start-pos) :to-equal 1))) (it "returns beginning of multi-line comment if between delimiters 5" (with-lua-buffer (lua-insert-goto-<> '("--[[ ]<>]")) (expect (lua-comment-start-pos) :to-equal 1))) (it "returns nil if before multi-line opener" (with-lua-buffer (lua-insert-goto-<> '("<>--[[ ]]")) (expect (lua-comment-start-pos) :to-equal nil))) (it "returns nil if after multi-line closer" (with-lua-buffer (lua-insert-goto-<> '("--[[ ]]<>")) (expect (lua-comment-start-pos) :to-equal nil))) (it "returns beginning of multi-line comment if after multi-line closer with different opener" (with-lua-buffer (lua-insert-goto-<> '("--[==[ ]]<>")) (expect (lua-comment-start-pos) :to-equal 1))) ;; Multi-line comments with strings (it "returns nil if multi-line opener is inside string 1" (with-lua-buffer (lua-insert-goto-<> '("'--[[' <>]]")) (expect (lua-comment-start-pos) :to-equal nil))) (it "returns nil if multi-line opener is inside string 2" (with-lua-buffer (lua-insert-goto-<> '("'--[[' ]]<>")) (expect (lua-comment-start-pos) :to-equal nil))) (it "returns nil if multi-line opener is inside multi-line string 1" (with-lua-buffer (lua-insert-goto-<> '("[[--[[]] <>]]")) (expect (lua-comment-start-pos) :to-equal nil))) (it "returns nil if multi-line opener is inside multi-line string 2" (with-lua-buffer (lua-insert-goto-<> '("[[--[[]] ]]<>")) (expect (lua-comment-start-pos) :to-equal nil)))) (describe "lua-comment-or-string-start-p/-pos" (lua--parametrize-tests (strings expected-result) (;; single-line strings: single-quote (("<>'foo'") nil) (("'<>foo'") 1) (("'foo<>'") 1) (("'foo'<>") nil) ;; single-line strings: double-quote (("<>\"foo\"") nil) (("\"<>foo\"") 1) (("\"foo<>\"") 1) (("\"foo\"<>") nil) ;; multi-line strings (("<>[[foo]]") nil) (("[[<>foo]]") 1) (("[<>[foo]]") 1) (("[=<>[foo]=]") 1) (("[<>=[foo]=]") 1) (("[[foo<>]]") 1) (("[[foo]<>]") 1) (("[[foo]<>=]") 1) (("[[foo]=<>]") 1) (("[[foo]]<>") nil) ;; single-line comments (("foo <>-- bar") nil) (("foo -<>- bar") 5) (("foo --<> bar") 5) (("foo -- <>bar") 5) (("foo -- bar<>") 5) ;; multi-line comments (("foo <>--[[ bar ]]") nil) (("foo -<>-[[ bar ]]") 5) (("foo --<>[[ bar ]]") 5) (("foo --[<>[ bar ]]") 5) (("foo --[[<> bar ]]") 5) (("foo --[[ bar <>]]") 5) (("foo --[[ bar ]<>]") 5) (("foo --[[ bar ]]<>") nil) (("foo --[==[ bar ]]<>") 5) ;; single-line comment containing multi-line comment (("foo <>---[[ bar ]]") nil) (("foo --<>-[[ bar ]]") 5) (("foo ---<>[[ bar ]]") 5) (("foo ---[<>[ bar ]]") 5) (("foo ---[[<> bar ]]") 5) (("foo ---[[ bar ]]<>") 5) ;; multi-line comment containing single-line comment (("foo --[[ -- bar ]]<>") nil) ;; string containing multi-line comment opener (("foo '--[[' <> bar ]]") nil) (("foo [[--[[]] <> bar ]]") nil) (("foo [[--[==[]] <> bar ]==]") nil) ;; single dash: not a comment (("foo = bar -<> baz") nil) (("foo = bar <>- baz") nil)) :it (format "returns %s for %S" (if expected-result (format "truthy/%S" expected-result) "nil") strings) (with-lua-buffer (lua-insert-goto-<> strings) (expect (lua-comment-or-string-start-pos) :to-equal expected-result) (if expected-result (expect (lua-comment-or-string-p) :to-be-truthy) (expect (lua-comment-or-string-p) :not :to-be-truthy))))) (describe "lua-skip-ws-and-comments-backward" (describe "doesn't move point" (lua--parametrize-tests (navigation-spec test-name) (("<>" "empty buffer") ("<> --[[]]foo" "at beginning of non-empty buffer") (" f<>oo" "in the middle of variable") (" foo<>" "at the end of variable") (" foo<>--" "between variable and comment") (" foo 'bar'<>" "at the end of single-quote string literal") (" foo [[bar]]<>" "at the end of multi-line string literal") (" foo '<>bar'" "inside string literal") (" foo (<>bar)" "inside function call literal") (" foo '-- <> bar'" "within whitespace inside single-line string literal") (" foo [[-- \n<> bar]]" "within whitespace inside multi-line string literal") ) :it (replace-regexp-in-string "\n" "\\\\n" (format "%s: %S" test-name navigation-spec)) (expect navigation-spec :with-point-at "<" :after-executing (lua-skip-ws-and-comments-backward) :to-end-up-at ">"))) (describe "moves point" (lua--parametrize-tests (navigation-spec test-name) (("<2> <1>" "skip whitespace at the beginning of buffer") ("foo<2> <1>" "skip ws after variable") ("foo()<2> <1>" "skip ws after function call") ("foo<2> \n\t\n<1>" "skip newlines/tabs/spaces after variable") ;; single-line comments ("foo<2> -- <1>" "escape single-line comment and skip ws") ("foo<2> -<1>-" "escape single-line comment delimiter") ("foo<2> -- '<1>'" "escape commented out string and skip ws") ("foo<2> -- [[<1>]]" "escape commented out string and skip ws") ("foo<2> -- \n<1>" "skip single-line comment and ws") ("foo<2> -- \n--\n--\n<1>" "skip several single-line comments and ws") ;; multi-line ("foo<2> --[[ <1> ]]" "escape multi-line comment and skip ws") ("foo<2> -<1>-[[ ]]" "escape multi-line comment delimiter and skip ws 1") ("foo<2> --<1>[[ ]]" "escape multi-line comment delimiter and skip ws 2") ("foo<2> --[<1>[ ]]" "escape multi-line comment delimiter and skip ws 3") ("foo<2> --[[ ]<1>]" "escape multi-line comment delimiter and skip ws 4") ("foo<2> --[[ \n\n ]]\n\n--[[ ]]<1>" "skip multi-line comments and ws") ;; luadoc keywords ("foo<2> --[[ @see foo <1>]]" "escape multi-line comment with luadoc keyword 1") ("foo<2> --[[ @s<1>ee foo ]]" "escape multi-line comment with luadoc keyword 2") ("foo<2> --[[ <1>@see foo ]]" "escape multi-line comment with luadoc keyword 3") ("foo<2> -- @see foo <1>" "escape single-line comment with luadoc keyword 1") ("foo<2> -- @s<1>ee foo " "escape single-line comment with luadoc keyword 2") ("foo<2> -- <1>@see foo " "escape single-line comment with luadoc keyword 3") ) :it (replace-regexp-in-string "\n" "\\\\n" (format "%s: %S" test-name navigation-spec)) (expect navigation-spec :with-point-at "<1>" :after-executing (lua-skip-ws-and-comments-backward) :to-end-up-at "<2>"))) (describe "respects limit" (lua--parametrize-tests (limit navigation-spec test-name) ((3 " <2> <1>" "respect limit in whitespace") (100 " <2><1> " "don't move if limit is beyond point") (5 "-- <2> <1>" "respect limit when escaping single-line comment") (5 "--[[<2> <1>]]" "respect limit when escaping multi-line comment") (5 " <2>-- <1>" "respect limit when escaping multi-line comment") (5 " <2>--[[ <1>]]" "respect limit when escaping multi-line comment") (5 "-- <2>@see x <1>" "respect limit when escaping single-line luadoc comment") (5 "--[[<2>@see x <1>]]" "respect limit when escaping multi-line luadoc comment") ) :it (replace-regexp-in-string "\n" "\\\\n" (format "%s: limit=%S %S" test-name limit navigation-spec)) (expect navigation-spec :with-point-at "<1>" :after-executing (lua-skip-ws-and-comments-backward limit) :to-end-up-at "<2>")))) (describe "lua-skip-ws-and-comments-forward" (describe "doesn't move point" (lua--parametrize-tests (navigation-spec test-name) (("<>" "empty buffer") (" --[[]]<>" "at end of non-empty buffer") (" f<>oo " "in the middle of variable") (" <>foo " "at the beginning of variable") (" --[[]]<>foo " "between variable and comment") (" foo <>'bar'" "at the end of single-quote string literal") (" foo <>[[bar]]" "at the end of multi-line string literal") (" foo 'bar<>'" "inside string literal") (" foo (bar<>)" "inside function call literal") (" foo '-- <> bar'" "within whitespace inside single-line string literal") (" foo [[-- \n<>\n bar]]" "within whitespace inside multi-line string literal") ) :it (replace-regexp-in-string "\n" "\\\\n" (format "%s: %S" test-name navigation-spec)) (expect navigation-spec :with-point-at "<" :after-executing (lua-skip-ws-and-comments-forward) :to-end-up-at ">"))) (describe "moves point" (lua--parametrize-tests (navigation-spec test-name) (("<1> <2>" "skip whitespace at the end of buffer") ("<1> <2>bar" "skip ws before variable") ("foo<1> <2>()" "skip ws before function call") ("<1> \n\t\n<2>foo" "skip newlines/tabs/spaces before variable") ;; single-line comments ("foo -- <1>\n <2>bar" "escape single-line comment and skip ws") ("foo -<1>- \n <2>bar" "escape single-line comment delimiter") ("foo -- '<1>' \n <2>bar" "escape commented out string and skip ws") ("foo -- [[<1>]] \n <2>bar" "escape commented out string and skip ws") ("foo <1>-- \n \n <2>bar" "skip single-line comment and ws") ("foo <1>-- \n--\n--\n \n <2>bar" "skip several single-line comments and ws") ;; multi-line ("foo --[[ <1> ]] <2>bar" "escape multi-line comment and skip ws") ("foo -<1>-[[ ]] <2>bar" "escape multi-line comment delimiter and skip ws 1") ("foo --<1>[[ ]] <2>bar" "escape multi-line comment delimiter and skip ws 2") ("foo --[<1>[ ]] <2>bar" "escape multi-line comment delimiter and skip ws 3") ("foo --[[ ]<1>] <2>bar" "escape multi-line comment delimiter and skip ws 4") ("foo <1>--[[ \n\n ]]\n\n--[[ ]] <2>bar" "skip multi-line comments and ws") ;; luadoc keywords ("foo --[[ @see foo <1>]] <2>bar" "escape multi-line comment with luadoc keyword 1") ("foo --[[ @s<1>ee foo ]] <2>bar" "escape multi-line comment with luadoc keyword 2") ("foo --[[ <1>@see foo ]] <2>bar" "escape multi-line comment with luadoc keyword 3") ("foo -- @see foo<1> \n <2>bar" "escape single-line comment with luadoc keyword 1") ("foo -- @s<1>ee foo \n <2>bar" "escape single-line comment with luadoc keyword 2") ("foo -- <1>@see foo \n <2>bar" "escape single-line comment with luadoc keyword 3") ) :it (replace-regexp-in-string "\n" "\\\\n" (format "%s: %S" test-name navigation-spec)) (expect navigation-spec :with-point-at "<1>" :after-executing (lua-skip-ws-and-comments-forward) :to-end-up-at "<2>"))) (describe "respects limit" (lua--parametrize-tests (limit navigation-spec test-name) ((6 " <1> <2> " "in whitespace") (1 " <2><1> " "don't move if limit is before point") (8 "-- <1> <2> \n" "when escaping single-line comment 1") (8 "-- <1> \n<2> " "when escaping single-line comment 2") (8 "-- <1> <2>\n " "when escaping single-line comment 3") (8 "--[[<1> <2> ]] \n" "when escaping multi-line comment 1") (8 "--[[<1> ]<2>] \n" "when escaping multi-line comment 1") (8 "--[[<1> <2> ]] \n" "when escaping multi-line comment 1") (7 "-- <1>@s<2>ee x " "when escaping single-line luadoc comment") (8 "-- <1>@se<2>e x " "when escaping single-line luadoc comment") (9 "-- <1>@see<2> x " "when escaping single-line luadoc comment") (7 "--[[<1>@s<2>ee x]] " "when escaping multi-line luadoc comment") (8 "--[[<1>@se<2>e x]] " "when escaping multi-line luadoc comment") (9 "--[[<1>@see<2> x]] " "when escaping multi-line luadoc comment") ) :it (replace-regexp-in-string "\n" "\\\\n" (format "%s: limit=%S %S" test-name limit navigation-spec)) (expect navigation-spec :with-point-at "<1>" :after-executing (lua-skip-ws-and-comments-forward limit) :to-end-up-at "<2>")))) (describe "lua-find-regexp" (it "does not match open-bracket that is part of multiline string opener: forward" (with-lua-buffer (lua-insert-goto-<> '("<>foo = [[ bar ]]")) (expect (lua-find-regexp 'forward "\\[") :not :to-be-truthy))) (it "does not match open-bracket that is part of multiline string opener: backward" (with-lua-buffer (lua-insert-goto-<> '("foo = [[ bar ]]<>")) (expect (lua-find-regexp 'backward "\\[") :not :to-be-truthy))) (it "does not match close-bracket that is part of multiline string closer: forward" (with-lua-buffer (lua-insert-goto-<> '("<>foo = [[ bar ]]")) (expect (lua-find-regexp 'forward "]") :not :to-be-truthy))) (it "does not match close-bracket that is part of multiline string closer: backward" (with-lua-buffer (lua-insert-goto-<> '("<>foo = [[ bar ]]")) (expect (lua-find-regexp 'backward "]") :not :to-be-truthy))) (it "does not match minus that is part of comment starter: forward" (with-lua-buffer (lua-insert-goto-<> '("<>foo = [[ bar ]] -- baz")) (expect (lua-find-regexp 'forward "-") :not :to-be-truthy))) (it "does not match minus that is part of comment starter: backward" (with-lua-buffer (lua-insert-goto-<> '("<>foo = [[ bar ]] -- baz")) (expect (lua-find-regexp 'backward "-") :not :to-be-truthy)))) lua-mode-20210802/test/utils.el000066400000000000000000000237621410202764300161270ustar00rootroot00000000000000;; -*- flycheck-disabled-checkers: (emacs-lisp-checkdoc) -*- (require 'lua-mode) (require 'buttercup) (defun to-be-fontified-as (text faces) (let ((expected-faces (lua-mk-font-lock-faces faces)) (result-faces (lua-get-line-faces text)) (lineno 1)) (when (/= (length expected-faces) (length result-faces)) (buttercup-fail "\ Fontification check failed for: %S Text contains %d lines, face list contains %d lines" text (length result-faces) (length expected-faces))) (while expected-faces (unless (equal (car expected-faces) (car result-faces)) (buttercup-fail "\ Fontification check failed on line %d for: %S Expected faces: %S Actual faces: %S" lineno text (car expected-faces) (car result-faces))) (setq expected-faces (cdr expected-faces) result-faces (cdr result-faces) lineno (1+ lineno))) (cons t "Fontification check passed"))) (buttercup-define-matcher :to-be-fontified-as (text faces) (to-be-fontified-as (funcall text) (funcall faces))) (buttercup-define-matcher :to-precede (pos regexp) (save-excursion (goto-char (funcall pos)) (let* ((precedes (looking-at (funcall regexp))) (substr-begin (min (point-max) (funcall pos))) (substr-end (min (point-max) (+ (funcall pos) 100))) (found-after (format "%S" (buffer-substring-no-properties substr-begin substr-end )))) (goto-char substr-end) (when (eobp) (setq found-after (concat found-after " (end-of-buffer)"))) (cons precedes (format "Expected %s to see after point at %s: %S. Found: %s" (if precedes "NOT" "") (funcall pos) (funcall regexp) found-after))))) (defun get-str-faces (str) "Find contiguous spans of non-default faces in STR. E.g. for properly fontified Lua string \"local x = 100\" it should return '(\"local\" font-lock-keyword-face \"x\" font-lock-variable-name-face \"100\" font-lock-constant-face) " (let* ((pos 0) (prop (or (get-text-property pos 'face str) (get-text-property pos 'font-lock-face str))) (nextpos 0) newprop result) (while nextpos (setq nextpos (next-property-change nextpos str)) (setq newprop (when nextpos (or (get-text-property nextpos 'face str) (get-text-property nextpos 'font-lock-face str)))) (when (not (equal prop newprop)) (when (listp prop) (when (eq (car-safe (last prop)) 'default) (setq prop (butlast prop))) (when (= 1 (length prop)) (setq prop (car prop))) (when (symbolp prop) (when (eq prop 'default) (setq prop nil)))) (when prop (push (substring-no-properties str pos nextpos) result) (push prop result)) (setq prop newprop pos nextpos))) (nreverse result))) (defun lua-fontify-str (str) "Return string fontified according to lua-mode's rules" (with-temp-buffer (lua-mode) (insert str) (font-lock-fontify-buffer) (buffer-string))) (defun get-buffer-line-faces () (font-lock-fontify-buffer) (mapcar 'get-str-faces (split-string (buffer-string) "\n" nil))) (defun lua-get-line-faces (str) "Find contiguous spans of non-default faces in each line of STR. The result is a list of lists." (mapcar 'get-str-faces (split-string (lua-fontify-str str) "\n" nil))) (defun lua-mk-font-lock-faces (sym) "Decorate symbols with font-lock-%s-face recursively. This is a mere typing/reading aid for lua-mode's font-lock tests." (or (cond ((symbolp sym) (intern-soft (format "font-lock-%s-face" (symbol-name sym)))) ((listp sym) (mapcar 'lua-mk-font-lock-faces sym))) sym)) (defmacro should-lua-font-lock-equal (strs faces) `(should (equal (lua-get-line-faces ,strs) (lua-mk-font-lock-faces ,faces)))) ;; suppress fontification messages in emacs23 output (setq font-lock-verbose nil) (defun lua-join-lines (strs) (mapconcat (lambda (x) (concat x "\n")) strs "")) (defmacro with-lua-buffer (&rest body) (declare (debug (&rest form))) `(with-temp-buffer ;; font-lock is not activated if buffer name is temporary (starts with a ;; space) and if `noninteractive' is non-nil. Ensure tests that use ;; font-lock still work. (rename-buffer "temp-buffer.lua" t) (let (noninteractive) (lua-mode) (font-lock-mode 1)) (set (make-local-variable 'lua-process) nil) (set (make-local-variable 'lua-process-buffer) nil) (pop-to-buffer (current-buffer)) (unwind-protect (progn ,@body) (when (buffer-live-p lua-process-buffer) (lua-kill-process))))) (defun lua-get-indented-strs (strs) (let ((indent-tabs-mode nil) (font-lock-verbose nil)) (butlast (split-string (with-lua-buffer (let ((inhibit-message t)) (insert (replace-regexp-in-string "^\\s *" "" (lua-join-lines strs))) (font-lock-fontify-buffer) (indent-region (point-min) (point-max)) (buffer-substring-no-properties (point-min) (point-max)))) "\n" nil)))) (defun lua-insert-goto-<> (strs) "Insert sequence of strings and put point in place of \"<>\"." (insert (lua-join-lines strs)) (goto-char (point-min)) (re-search-forward "<>") (replace-match "") ;; Inserted text may contain multiline constructs which will only be ;; recognized after fontification. (font-lock-fontify-buffer)) (defmacro lua-buffer-strs (&rest body) `(butlast (split-string (with-lua-buffer (progn ,@body) (buffer-substring-no-properties (point-min) (point-max))) "\n" nil))) (defun lua--reindent-like (str) (let ((strs (split-string str "\n"))) (equal strs (lua-get-indented-strs strs)))) (defun with-point-at-matcher (&rest args) (let* (lua-code origin-placeholder (origin-marker (make-marker)) target-placeholder (target-marker (make-marker)) body last-elt result message ) (cl-dolist (elt args) (cond ((eq last-elt :lua-code) (setq lua-code (funcall elt) last-elt nil)) ((eq last-elt :with-point-at) (setq origin-placeholder (funcall elt) last-elt nil)) ((eq last-elt :to-end-up-at) (setq target-placeholder (funcall elt) last-elt nil)) ((eq last-elt :after-executing) ;; No funcall here, funcall when the buffer is set up. (setq body elt last-elt nil)) (t (setq last-elt (if (functionp elt) (funcall elt) elt))))) (with-lua-buffer (insert lua-code) (goto-char (point-min)) (set-marker target-marker (search-forward target-placeholder)) (replace-match "") (goto-char (point-min)) (set-marker origin-marker (search-forward origin-placeholder)) (replace-match "") (funcall body) (setq result (equal (point) (marker-position target-marker))) (setq message (if result (format "Expected point not to be here:\n\n%s|%s" (buffer-substring-no-properties (point-min) (point)) (buffer-substring-no-properties (point) (point-max))) (format "Expected point to be here:\n============\n%s|%s\n============\n\nInstead it was here:\n============\n%s|%s\n============" (buffer-substring-no-properties (point-min) (marker-position target-marker)) (buffer-substring-no-properties (marker-position target-marker) (point-max)) (buffer-substring-no-properties (point-min) (point)) (buffer-substring-no-properties (point) (point-max))))) (cons result message)))) (buttercup-define-matcher :with-point-at (&rest args) (apply #'with-point-at-matcher `(:lua-code ,(car args) :with-point-at ,@(cdr args)))) ;;; Shortcut for with-point-at with <1> and <2> placeholders (buttercup-define-matcher :to-move-point-from-1-to-2 (code-block lua-code) (with-point-at-matcher :lua-code lua-code :with-point-at (lambda () "<1>") :after-executing code-block :to-end-up-at (lambda () "<2>"))) (defun lua--string-trim (string &optional trim-left trim-right) ;; Backport of string-trim for Emacs 24 that doesn't have subr-x lib. (let ((sub-start 0) sub-end) (or trim-left (setq trim-left "[ \t\n\r]+")) (or trim-right (setq trim-right "[ \t\n\r]+")) (save-match-data (when (string-match (concat "\\`" trim-left) string) (setq sub-start (match-end 0))) (when (string-match (concat trim-right "\\'") string sub-start) (setq sub-end (match-beginning 0)))) (if (or sub-start sub-end) (substring string sub-start sub-end) string))) (buttercup-define-matcher :to-be-reindented-the-same-way (str) (let* ((lines (split-string (funcall str) "\n")) (indented-lines (lua-get-indented-strs lines))) (buttercup--test-expectation (equal lines indented-lines) :expect-match-phrase (format "Indentation check failed:\n=========\nExpected:\n---------\n%s\n---------\nActual:\n---------\n%s\n=========" (lua--string-trim (mapconcat 'identity lines "\n")) (lua--string-trim (mapconcat 'identity indented-lines "\n"))) :expect-mismatch-phrase (format "Expected `%S' to not be reindented like that" lines)))) (defmacro lua--parametrize-tests (variables param-values it description-form &rest body) `(progn ,@(cl-loop for params in param-values for let-bindings = (cl-loop for var in variables for param in params collect `(,var (quote ,param))) for description = (eval `(let ,let-bindings ,description-form)) for test-body = `(let ,let-bindings ,@body) collect (macroexpand `(it ,description ,test-body))))) lua-mode-20210802/travis/000077500000000000000000000000001410202764300147645ustar00rootroot00000000000000lua-mode-20210802/travis/before-install.sh000077500000000000000000000017221410202764300202330ustar00rootroot00000000000000#!/bin/bash if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then if ! [[ "$EVM_EMACS" == "emacs-26.1-travis" ]]; then # FIXME: implement EVM_EMACS version translation. echo "Only Emacs-26.1 is supported for OSX builds" exit 1 fi set -x curl -fsSL https://emacsformacosx.com/emacs-builds/Emacs-26.1-universal.dmg -o /tmp/Emacs-26.1-universal.dmg && hdiutil attach /tmp/Emacs-26.1-universal.dmg && mkdir -p "$HOME/bin" && ln -s /Volumes/Emacs/Emacs.app/Contents/MacOS/Emacs "$HOME/bin/emacs" && export PATH="$HOME/bin:$PATH" && emacs --version && curl -fsSL https://raw.github.com/cask/cask/master/go -o /tmp/cask-bootstrap.py && python /tmp/cask-bootstrap.py && export PATH="$HOME/.cask/bin:$PATH" set +x else emacs --version curl -fsSkL https://gist.github.com/rejeep/ebcd57c3af83b049833b/raw > travis.sh && source ./travis.sh evm install "$EVM_EMACS" --use --skip fi