Initial Commit
[packages] / xemacs-packages / prog-modes / lua-mode.el
1 ;;; lua-mode.el --- a major mode for editing Lua scripts
2
3 ;; FIXME: Update this version number and date
4 ;; $Id: lua-mode.el,v 1.26 2001/07/08 19:06:50 cvogler Exp $
5
6 ;; Copyright (C) 1997, 2001, 2004 Free Software Foundation, Inc.
7
8 ;; Author: 2004 various (support for Lua 5 and byte compilation)
9 ;;         2001 Christian Vogler <cvogler@gradient.cis.upenn.edu>
10 ;;         1997 Bret Mogilefsky <mogul-lua@gelatinous.com> starting from
11 ;;              tcl-mode by Gregor Schmid <schmid@fb3-s7.math.tu-berlin.de>
12 ;;              with tons of assistance from
13 ;;              Paul Du Bois <pld-lua@gelatinous.com> and
14 ;;              Aaron Smith <aaron-lua@gelatinous.com>.
15
16 ;; Keywords: languages, processes, tools
17
18 ;; This file is part of XEmacs.
19
20 ;; XEmacs is free software; you can redistribute it and/or modify it
21 ;; under the terms of the GNU General Public License as published by
22 ;; the Free Software Foundation; either version 2, or (at your option)
23 ;; any later version.
24
25 ;; XEmacs is distributed in the hope that it will be useful, but
26 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
27 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
28 ;; General Public License for more details.
29
30 ;; You should have received a copy of the GNU General Public License
31 ;; along with XEmacs; see the file COPYING.  If not, write to the Free
32 ;; Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
33 ;; 02111-1307, USA.
34
35 ;;; Synched up with:
36 ;;;   http://lua-users.org/files/wiki_insecure/editors/lua-mode.el (20040814)
37
38 ;;; Commentary:
39
40 ;; Special Thanks to Simon Marshall <simonm@mail.esrin.esa.it> for
41 ;; font-lock patches.
42
43 ;; Additional font-lock highlighting and indentation tweaks by
44 ;; Adam D. Moss <adam@gimp.org> <aspirin@icculus.org>
45
46 ;; This file was written with emacs using Jamie Lokier's folding mode
47 ;; That's what the funny ;;{{{ marks are there for
48
49 ;;{{{ Usage
50
51 ;; Lua-mode supports c-mode style formatting and sending of
52 ;; lines/regions/files to a lua interpreter. An interpreter (see
53 ;; variable `lua-default-application') will be started if you try to
54 ;; send some code and none is running. You can use the process-buffer
55 ;; (named after the application you chose) as if it were an
56 ;; interactive shell. See the documentation for `comint.el' for
57 ;; details.
58
59 ;;}}}
60 ;;{{{ Key-bindings
61
62 ;; To see all the keybindings for lua mode, look at `lua-setup-keymap'
63 ;; or start `lua-mode' and type `\C-h m'.
64 ;; The keybindings may seem strange, since I prefer to use them with
65 ;; lua-prefix-key set to nil, but since those keybindings are already used
66 ;; the default for `lua-prefix-key' is `\C-c', which is the conventional
67 ;; prefix for major-mode commands.
68
69 ;; You can customise the keybindings either by setting `lua-prefix-key'
70 ;; or by putting the following in your .emacs
71 ;;      (setq lua-mode-map (make-sparse-keymap))
72 ;; and
73 ;;      (define-key lua-mode-map <your-key> <function>)
74 ;; for all the functions you need.
75
76 ;;}}}
77 ;;{{{ Variables
78
79 ;; You may want to customize the following variables:
80 ;;
81 ;; lua-indent-level
82 ;; lua_always-show
83 ;;      lua-mode-map
84 ;;      lua-prefix-key
85 ;;      lua-mode-hook
86 ;; lua-default-application
87 ;; lua-default-command-switches
88
89 ;;}}}
90
91 ;;; Code:
92 (defconst lua-using-xemacs (string-match "XEmacs" emacs-version)
93   "Nil unless using XEmacs).")
94
95 ;; We need that !
96 (require 'comint)
97
98 ;;{{{ variables
99
100 ;; XEmacs addition
101 (defgroup lua nil
102   "Major mode for editing Lua Code."
103   :group 'languages)
104
105 ;; XEmacs change: defvar -> defcustom and default to non-full path to "lua".
106 (defcustom lua-default-application "lua"
107   "*Default application to run in lua subprocess."
108   :type 'string
109   :group 'lua)
110
111 ;; XEmacs change: defvar -> defcustom
112 (defcustom lua-default-command-switches '()
113   "*Command switches for `lua-default-application'.
114 Should be a list of strings."
115   :type '(repeat (string :tag "Switch"))
116   :group 'lua)
117
118 (defvar lua-process nil
119   "The active lua subprocess corresponding to current buffer.")
120
121 (defvar lua-process-buffer nil
122   "Buffer used for communication with lua subprocess for current buffer.")
123
124 ;; XEmacs change: defvar -> defcustom
125 (defcustom lua-always-show t
126   "*Non-nil means display `lua-process-buffer' after sending a command."
127   :type 'boolean
128   :group 'lua)
129
130 (defvar lua-mode-map nil
131   "Keymap used with `lua-mode'.")
132
133 (defvar lua-prefix-key "\C-c"
134   "Prefix for all `lua-mode' commands.")
135
136 ;; XEmacs change: defvar -> defcustom
137 (defcustom lua-mode-hook nil
138   "*Hooks called when lua mode fires up."
139   :type 'hook
140   :group 'lua)
141
142 (defvar lua-region-start (make-marker)
143   "Start of special region for lua communication.")
144
145 (defvar lua-region-end (make-marker)
146   "End of special region for lua communication.")
147
148 ;; XEmacs change: defvar -> defcustom
149 (defcustom lua-indent-level 3
150   "*Amount by which lua subexpressions are indented."
151   :type 'integer
152   :group 'lua)
153
154 (defvar lua-mode-menu (make-sparse-keymap "Lua")
155   "Keymap for `lua-mode's menu.")
156
157 (defvar lua-xemacs-menu
158   '(["Restart With Whole File" lua-restart-with-whole-file t]
159     ["Kill Process" lua-kill-process t]
160     ["Hide Process Buffer" lua-hide-process-buffer t]
161     ["Show Process Buffer" lua-show-process-buffer t]
162     ["Beginning Of Proc" lua-beginning-of-proc t]
163     ["End Of Proc" lua-end-of-proc t]
164     ["Set Lua-Region Start" lua-set-lua-region-start t]
165     ["Set Lua-Region End" lua-set-lua-region-end t]
166     ["Send Lua-Region" lua-send-lua-region t]
167     ["Send Current Line" lua-send-current-line t]
168     ["Send Region" lua-send-region t]
169     ["Send Proc" lua-send-proc t]
170     ["Send Buffer" lua-send-buffer t])
171   "XEmacs menu for Lua mode.")
172
173 ;; XEmacs change: pre-generate regexps, don't eval-on-compile
174 (defvar lua-font-lock-keywords
175   (list
176    ;;
177    ;; Function name declarations.
178    '("^[ \t]*\\<\\(\\(local[ \t]+\\)?function\\)\\>[ \t]+\\(\\(\\sw:\\|\\sw\\.\\|\\sw_\\|\\sw\\)+\\)"
179      (1 font-lock-keyword-face) (3 font-lock-function-name-face nil t))
180
181    ;; Highlight multi-line comment blocks; since font-lock-mode doesn't
182    ;; claim to handle the highlighting of multi-line expressions elegantly
183    ;; this works best with lazy-lock-mode if your Emacs supports it, e.g.
184    ;; try (setq font-lock-support-mode 'lazy-lock-mode) in your ~/.emacs
185
186    ;; Multi-line comment blocks.
187    `("--.*\\(\\[\\[\\(\\]?[^]]\\)*\\]\\]\\)"
188      (1 font-lock-comment-face t))
189
190    ;;
191    ;; Keywords.
192    ;; (concat "\\<"
193    ;;         (regexp-opt '("and" "break" "do" "else" "elseif" "end" "false"
194    ;;                       "for" "function" "if" "in" "local" "nil" "not"
195    ;;                       "or" "repeat" "return" "then" "true" "until"
196    ;;                       "while") t)
197    ;;         "\\>")
198
199    "\\<\\(and\\|break\\|do\\|e\\(lse\\(if\\)?\\|nd\\)\\|f\\(alse\\|or\\|unction\\)\\|i[fn]\\|local\\|n\\(il\\|ot\\)\\|or\\|re\\(peat\\|turn\\)\\|t\\(hen\\|rue\\)\\|until\\|while\\)\\>"
200
201    "Default expressions to highlight in Lua mode."))
202
203 (defvar lua-imenu-generic-expression
204 ;  '((nil "^[ \t]*function[ \t]+\\(\\(\\s_\\|\\sw\\)+\\)" 1)) ; Original
205   '((nil "^[ \t]*function[ \t]+\\(\\(\\sw:\\|\\sw_\\|\\sw\\.\\|\\sw\\)+\\)" 1)) ; Original
206   "Imenu generic expression for `lua-mode'.  See `imenu-generic-expression'.")
207
208 (defvar lua-mode-abbrev-table nil
209   "Abbreviation table used in `lua-mode' buffers.")
210
211 (define-abbrev-table 'lua-mode-abbrev-table
212   '(
213         ("end" "end" lua-indent-line 0)
214         ("else" "else" lua-indent-line 0)
215         ("elseif" "elseif" lua-indent-line 0)
216         ))
217
218 (defconst lua-indent-whitespace " \t"
219   "Character set that constitutes whitespace for indentation in lua.")
220
221 ;;}}}
222 ;;{{{ lua-mode
223
224 ;;;###autoload
225 (defun lua-mode ()
226   "Major mode for editing lua scripts.
227 The following keys are bound:
228 \\{lua-mode-map}
229 "
230   (interactive)
231   (let ((switches nil)
232                   s)
233     (kill-all-local-variables)
234     (setq major-mode 'lua-mode)
235     (setq mode-name "Lua")
236     (set (make-local-variable 'lua-process) nil)
237     (set (make-local-variable 'lua-process-buffer) nil)
238     (make-local-variable 'lua-default-command-switches)
239     (set (make-local-variable 'indent-line-function) 'lua-indent-line)
240     (set (make-local-variable 'comment-start) "--")
241     (set (make-local-variable 'comment-start-skip) "--")
242     (set (make-local-variable 'font-lock-defaults)
243                         '(lua-font-lock-keywords nil nil ((?_ . "w"))))
244     (set (make-local-variable 'imenu-generic-expression)
245                         lua-imenu-generic-expression)
246          (setq local-abbrev-table lua-mode-abbrev-table)
247          (abbrev-mode 1)
248     (make-local-variable 'lua-default-eval)
249     (or lua-mode-map
250                   (lua-setup-keymap))
251     (use-local-map lua-mode-map)
252     (set-syntax-table (copy-syntax-table))
253     (modify-syntax-entry ?+ ".")
254     (modify-syntax-entry ?- ". 12")
255     (modify-syntax-entry ?* ".")
256     (modify-syntax-entry ?/ ".")
257     (modify-syntax-entry ?^ ".")
258     (modify-syntax-entry ?. ".")
259     (modify-syntax-entry ?> ".")
260     (modify-syntax-entry ?< ".")
261     (modify-syntax-entry ?= ".")
262     (modify-syntax-entry ?~ ".")
263     (modify-syntax-entry ?\n ">")
264     (modify-syntax-entry ?\' "\"")
265     (modify-syntax-entry ?\" "\"")
266     ;; _ needs to be part of a word, or the regular expressions will
267     ;; incorrectly regognize end_ to be matched by "\\<end\\>"!
268     (modify-syntax-entry ?_ "w")
269     (if (and lua-using-xemacs
270              (featurep 'menubar)
271              current-menubar
272              (not (assoc "Lua" current-menubar)))
273         (progn
274           (set-buffer-menubar (copy-sequence current-menubar))
275           (add-menu nil "Lua" lua-xemacs-menu)))
276     ;; Append Lua menu to popup menu for XEmacs.
277     (if (and lua-using-xemacs (boundp 'mode-popup-menu))
278         (setq mode-popup-menu
279               (cons (concat mode-name " Mode Commands") lua-xemacs-menu)))
280     (run-hooks 'lua-mode-hook)))
281
282 ;; XEmacs change: make this autoload-only
283 ;;;###autoload(add-to-list 'auto-mode-alist '("\\.lua$" . lua-mode))
284
285 ;;}}}
286 ;;{{{ lua-setup-keymap
287
288 (defun lua-setup-keymap ()
289   "Set up keymap for lua mode.
290 If the variable `lua-prefix-key' is nil, the bindings go directly
291 to `lua-mode-map', otherwise they are prefixed with `lua-prefix-key'."
292   (setq lua-mode-map (make-sparse-keymap))
293   (define-key lua-mode-map [menu-bar lua-mode]
294     (cons "Lua" lua-mode-menu))
295   (define-key lua-mode-map "}" 'lua-electric-match)
296   (define-key lua-mode-map "]" 'lua-electric-match)
297   (define-key lua-mode-map ")" 'lua-electric-match)
298   (let ((map (if lua-prefix-key
299                                           (make-sparse-keymap)
300                                         lua-mode-map)))
301
302          ;; communication
303          (define-key map "\M-[" 'lua-beginning-of-proc)
304          (define-key map "\M-]" 'lua-end-of-proc)
305          (define-key map "\C-c" 'comment-region)
306          (if lua-prefix-key
307                   (define-key lua-mode-map lua-prefix-key map))
308          ))
309
310 ;;}}}
311 ;;{{{ indentation
312
313 ;;{{{ lua-electric-match
314
315 (defun lua-electric-match (arg)
316   "Insert character and adjust indentation."
317   (interactive "P")
318   (insert-char last-command-char (prefix-numeric-value arg))
319   (lua-indent-line)
320   (blink-matching-open))
321
322 ;;}}}
323
324 (defun lua-syntax-status ()
325   "Return the syntactic status of the character after the point."
326   (parse-partial-sexp (save-excursion (beginning-of-line) (point))
327                       (point)))
328
329 (defun lua-string-p ()
330   "Return true if the point is in a string."
331   (elt (lua-syntax-status) 3))
332
333 (defun lua-comment-p ()
334   "Return true if the point is in a comment."
335     (elt (lua-syntax-status) 4))
336
337 (defun lua-comment-or-string-p ()
338   "Return true if the point is in a comment or string."
339   (let ((parse-result (lua-syntax-status)))
340     (or (elt parse-result 3) (elt parse-result 4))))
341
342
343 ;;{{{ lua-indent-line
344
345 (defun lua-indent-line ()
346   "Indent current line as lua code.
347 Return the amount the indentation changed by."
348   (let ((indent (max 0 (- (lua-calculate-indentation nil)
349                           (lua-calculate-indentation-left-shift))))
350         beg shift-amt
351         (case-fold-search nil)
352         (pos (- (point-max) (point))))
353     (beginning-of-line)
354     (setq beg (point))
355     (skip-chars-forward lua-indent-whitespace)
356     (setq shift-amt (- indent (current-column)))
357     (when (not (zerop shift-amt))
358       (delete-region beg (point))
359       (indent-to indent))
360     ;; If initial point was within line's indentation,
361     ;; position after the indentation.  Else stay at same point in text.
362     (if (> (- (point-max) pos) (point))
363         (goto-char (- (point-max) pos)))
364     shift-amt
365     indent))
366
367 ;;}}}
368
369
370
371 (defun lua-find-regexp (direction regexp &optional limit ignore-p)
372   "Search for a regular expression in the direction specified.
373 DIRECTION is one of 'forward and 'backward.
374 By default, matches in comments and strings are ignored, but what to ignore is
375 configurable by specifying IGNORE-P.  If the REGEXP is found, return point
376 position, nil otherwise.
377 IGNORE-P returns true if the match at the current point position should be
378 ignored, nil otherwise."
379   (let ((ignore-func (or ignore-p 'lua-comment-or-string-p))
380         (search-func (if (eq direction 'forward)
381                          're-search-forward 're-search-backward))
382         (case-fold-search nil))
383     (catch 'found
384       (while (funcall search-func regexp limit t)
385         (if (not (funcall ignore-func))
386             (throw 'found (point)))))))
387
388
389 ;;{{{ lua-backwards-to-block-begin-or-end
390
391 ;; XEmacs change: pre-generate regexps, don't eval-on-compile
392 (defconst lua-block-regexp
393   (concat
394    "\\(\\<"
395    ;;(regexp-opt '("do" "function" "repeat" "then"
396    ;;              "else" "elseif" "end" "until") t)
397    "\\(do\\|e\\(?:lse\\(?:if\\)?\\|nd\\)\\|function\\|repeat\\|then\\|until\\)"
398    "\\>\\)\\|"
399    "\\([]()[{}]\\)"
400    ))
401
402 (defun lua-backwards-to-block-begin-or-end ()
403   "Move backwards to nearest block begin or end.
404 Return nil if not successful."
405   (interactive)
406   (lua-find-regexp 'backward lua-block-regexp))
407
408 ;;}}}
409
410 (defconst lua-block-token-alist
411   ;; The absence of "else" is deliberate. This construct in a way both
412   ;; opens and closes a block. As a result, it is difficult to handle
413   ;; cleanly. It is also ambiguous - if we are looking for the match
414   ;; of "else", should we look backward for "then/elseif" or forward
415   ;; for "end"?
416   ;; Maybe later we will find a way to handle it.
417   '(("do"       "\\<end\\>"                                   open)
418     ("function" "\\<end\\>"                                   open)
419     ("repeat"   "\\<until\\>"                                 open)
420     ("then"     "\\<\\(e\\(lseif\\|nd\\)\\)\\>"               open)
421     ("{"        "}"                                           open)
422     ("["        "]"                                           open)
423     ("("        ")"                                           open)
424     ("elseif"   "\\<then\\>"                                  close)
425     ("end"      "\\<\\(do\\|function\\|then\\)\\>"            close)
426     ("until"    "\\<repeat\\>"                                close)
427     ("}"        "{"                                           close)
428     ("]"        "\\["                                         close)
429     (")"        "("                                           close)))
430
431 ;; XEmacs change: pre-generate regexps, don't eval-on-compile
432 (defconst lua-indentation-modifier-regexp
433   ;; The absence of else is deliberate, since it does not modify the
434   ;; indentation level per se. It only may cause the line, in which the
435   ;; else is, to be shifted to the left.
436   (concat
437    "\\(\\<"
438    ;; n.b. "local function" is a bit of a hack, allowing only a single space
439    ;;(regexp-opt '("do" "local function" "function" "repeat" "then") t)
440    "\\(do\\|function\\|local function\\|repeat\\|then\\)"
441    "\\>\\|"
442    ;;(regexp-opt '("{" "(" "["))
443    "[([{]"
444    "\\)\\|\\(\\<"
445    ;;(regexp-opt '("elseif" "end" "until") t)
446    "\\(e\\(?:lseif\\|nd\\)\\|until\\)"
447    "\\>\\|"
448    ;;(regexp-opt '("]" ")" "}"))
449    "[])}]"
450    "\\)"))
451
452
453 (defun lua-find-matching-token-word (token search-start)
454   (let* ((token-info (assoc token lua-block-token-alist))
455          (match (car (cdr token-info)))
456          (match-type (car (cdr (cdr token-info))))
457          (search-direction (if (eq match-type 'open) 'forward 'backward)))
458     ;; if we are searching forward from the token at the current point
459     ;; (i.e. for a closing token), need to step one character forward
460     ;; first, or the regexp will match the opening token.
461     (if (eq match-type 'open) (forward-char 1))
462     (if search-start (goto-char search-start))
463     (catch 'found
464       (while (lua-find-regexp search-direction lua-indentation-modifier-regexp)
465         ;; have we found a valid matching token?
466         (let ((found-token (match-string 0))
467               (found-pos (match-beginning 0)))
468           (if (string-match match found-token)
469               (throw 'found found-pos))
470             ;; no - then there is a nested block. If we were looking for
471             ;; a block begin token, found-token must be a block end
472             ;; token; likewise, if we were looking for a block end token,
473             ;; found-token must be a block begin token, otherwise there
474             ;; is a grammatical error in the code.
475             (if (not (and
476                       (eq (car (cdr (cdr (assoc found-token lua-block-token-alist))))
477                           match-type)
478                       (lua-find-matching-token-word found-token nil)))
479               (throw 'found nil)))))))
480
481
482 (defun lua-goto-matching-block-token (&optional search-start parse-start)
483   "Find block begion/end token matching the one at the point.
484 This function moves the point to the token that matches the one
485 at the current point.  Return the point position of the first character of
486 the matching token if successful, nil otherwise."
487   (if parse-start (goto-char parse-start))
488   (let ((case-fold-search nil))
489     (if (looking-at lua-indentation-modifier-regexp)
490         (let ((position (lua-find-matching-token-word (match-string 0)
491                                                       search-start)))
492           (and position
493                (goto-char position))))))
494
495 ;; The following may be useful to speed up the search in the future.
496 ;      (let ((token-type (char-syntax (string-to-char token-to-match)))
497 ;           matching-pos)
498 ;       (cond ((eq token-type ?\()
499 ;              (setq matching-pos (scan-sexps (point) 1 (current-buffer) t))
500 ;              (when matching-pos (goto-char matching-pos)))
501
502 ;             ((eq token-type ?\))
503 ;              ;; need to move one char forward, because scan-sexps
504 ;              ;; expects the point to be one past the closing parenthesis
505 ;              (forward-char 1)
506 ;              (setq matching-pos (scan-sexps (point) -1 (current-buffer) t))
507 ;              (when matching-pos (goto-char matching-pos)))
508
509 ;             (t
510 ;              (lua-goto-matching-token-word token-to-match search-start)))))))
511
512
513
514 (defun lua-goto-matching-block (&optional noreport)
515   "Go to the keyword balancing the one under the point.
516 If the point is on a keyword/brace that starts a block, go to the
517 matching keyword that ends the block, and vice versa."
518   (interactive)
519   ;; search backward to the beginning of the keyword if necessary
520   (if (eq (char-syntax (following-char)) ?w)
521       (re-search-backward "\\<" nil t))
522   (let ((position (lua-goto-matching-block-token)))
523     (if (and (not position)
524              (not noreport))
525         (error "Not on a block control keyword or brace")
526       position)))
527
528
529 (defun lua-goto-nonblank-previous-line ()
530   "Put the point at the first previous line that is not blank.
531 Return the point, or nil if it reached the beginning of the buffer."
532   (catch 'found
533     (beginning-of-line)
534     (while t
535       (if (bobp) (throw 'found nil))
536       (forward-char -1)
537       (beginning-of-line)
538       (if (not (looking-at "\\s *\\(--.*\\)?$")) (throw 'found (point))))))
539
540 ;; XEmacs change: pre-generate regexps, don't eval-on-compile
541 (defconst lua-operator-class "-+*/^.=<>~")
542
543 ;; XEmacs change: pre-generate regexps, don't eval-on-compile
544 (defconst lua-cont-eol-regexp
545   (concat
546    "\\(\\<"
547    ;;(regexp-opt '("and" "or" "not" "in" "for" "while" "local" "function") t)
548    "\\(and\\|f\\(?:or\\|unction\\)\\|in\\|local\\|not\\|or\\|while\\)"
549    "\\>\\|"
550    "\\(^\\|[^" lua-operator-class "]\\)"
551    ;;(regexp-opt '("+" "-" "*" "/" "^" ".." "==" "=" "<" ">" "<=" ">=" "~=") t)
552    "\\(\\.\\.\\|<=\\|==\\|>=\\|~=\\|[*+/<=>^-]\\)"
553    "\\)"
554    "\\s *\\="))
555
556 ;; XEmacs change: pre-generate regexps, don't eval-on-compile
557 (defconst lua-cont-bol-regexp
558   (concat
559    "\\=\\s *"
560    "\\(\\<"
561    "\\(and\\|not\\|or\\)"
562    "\\>\\|"
563    ;;(regexp-opt '("+" "-" "*" "/" "^" ".." "==" "=" "<" ">" "<=" ">=" "~=") t)
564    "\\(\\.\\.\\|<=\\|==\\|>=\\|~=\\|[*+/<=>^-]\\)"
565    "\\($\\|[^" lua-operator-class "]\\)"
566    "\\)"))
567
568
569 (defun lua-last-token-continues-p ()
570   "Return true if the last token on this line is a continuation token."
571   (let (line-begin
572         line-end)
573     (save-excursion
574       (beginning-of-line)
575       (setq line-begin (point))
576       (end-of-line)
577       (setq line-end (point))
578       ;; we need to check whether the line ends in a comment and
579       ;; skip that one.
580       (while (lua-find-regexp 'backward "-" line-begin 'lua-string-p)
581         (if (looking-at "--")
582             (setq line-end (point))))
583       (goto-char line-end)
584       (re-search-backward lua-cont-eol-regexp line-begin t))))
585
586 (defun lua-first-token-continues-p ()
587   "Return true if the first token on this line is a continuation token."
588   (let (line-end)
589     (save-excursion
590       (end-of-line)
591       (setq line-end (point))
592       (beginning-of-line)
593       (re-search-forward lua-cont-bol-regexp line-end t))))
594
595
596 (defun lua-is-continuing-statement-p (&optional parse-start)
597   "Return non-nil if the line continues a statement.
598 More specifically, return the point in the line that is continued.
599 The criteria for a continuing statement are:
600
601 * the last token of the previous line is a continuing op,
602   OR the first token of the current line is a continuing op
603
604 AND
605
606 * the indentation modifier of the preceding line is nonpositive.
607
608 The latter is sort of a hack, but it is easier to use this criterion, instead
609 of reducing the indentation when a continued statement also starts a new
610 block. This is for aesthetic reasons: the indentation should be
611
612 dosomething(d +
613    e + f + g)
614
615 not
616
617 dosomething(d +
618       e + f + g)"
619   (let ((prev-line nil))
620     (save-excursion
621       (if parse-start (goto-char parse-start))
622       (save-excursion (setq prev-line (lua-goto-nonblank-previous-line)))
623       (and prev-line
624            (or (lua-first-token-continues-p)
625                (and (goto-char prev-line)
626                     ;; check last token of previous nonblank line
627                     (lua-last-token-continues-p)))
628            (<= (lua-calculate-indentation-block-modifier prev-line) 0)))))
629
630
631 (defun lua-make-indentation-info-pair ()
632   "This is a helper function to `lua-calculate-indentation-info'.
633 Don't use standalone."
634   (cond ((string-equal found-token "function")
635          ;; this is the location where we need to start searching for the
636          ;; matching opening token, when we encounter the next closing token.
637          ;; It is primarily an optimization to save some searchingt ime.
638          (cons 'absolute (+ (save-excursion (goto-char found-pos)
639                                             (current-column))
640                             lua-indent-level)))
641         ((string-equal found-token "(")
642          ;; this is the location where we need to start searching for the
643          ;; matching opening token, when we encounter the next closing token.
644          ;; It is primarily an optimization to save some searchingt ime.
645          (cons 'absolute (+ (save-excursion (goto-char found-pos)
646                                             (current-column))
647                             1)))
648         ((string-equal found-token "end")
649          (save-excursion
650            (lua-goto-matching-block-token nil found-pos)
651            (if (looking-at "\\<function\\>")
652                (cons 'absolute
653                      (+ (current-indentation)
654                         (lua-calculate-indentation-block-modifier
655                          nil (point))))
656              (cons 'relative (- lua-indent-level)))))
657         ((string-equal found-token ")")
658          (save-excursion
659            (lua-goto-matching-block-token nil found-pos)
660            (cons 'absolute
661                  (+ (current-indentation)
662                     (lua-calculate-indentation-block-modifier
663                      nil (point))))))
664         (t
665          (cons 'relative (if (nth 2 (match-data))
666                              ;; beginning of a block matched
667                              lua-indent-level
668                            ;; end of a block matched
669                            (- lua-indent-level))))))
670
671
672 (defun lua-calculate-indentation-info (&optional parse-start parse-end)
673   "For each block token on the line, computes how it affects the indentation.
674 The effect of each token can be either a shift relative to the current
675 indentation level, or indentation to some absolute column.  This information
676 is collected in a list of indentation info pairs, which denote absolute
677 and relative each, and the shift/column to indent to."
678   (let* ((line-end (save-excursion (end-of-line) (point)))
679          (search-stop (if parse-end (min parse-end line-end) line-end))
680          (indentation-info nil))
681     (if parse-start (goto-char parse-start))
682     (save-excursion
683       (beginning-of-line)
684       (while (lua-find-regexp 'forward lua-indentation-modifier-regexp
685                               search-stop)
686         (let ((found-token (match-string 0))
687               (found-pos (match-beginning 0))
688               (found-end (match-end 0))
689               (data (match-data)))
690           (setq indentation-info
691                 (cons (lua-make-indentation-info-pair) indentation-info)))))
692     indentation-info))
693
694
695 (defun lua-accumulate-indentation-info (info)
696   "Accumulate the indentation information previously calculated by
697 `lua-calculate-indentation-info'.  Return either the relative indentation
698 shift, or the absolute column to indent to."
699   (let ((info-list (reverse info))
700         (type 'relative)
701         (accu 0))
702     (mapcar (lambda (x)
703             (setq accu (if (eq 'absolute (car x))
704                            (progn (setq type 'absolute)
705                                   (cdr x))
706                          (+ accu (cdr x)))))
707           info-list)
708     (cons type accu)))
709
710 (defun lua-calculate-indentation-block-modifier (&optional parse-start
711                                                            parse-end)
712   "Return amount by which this line modifies the indentation.
713 Beginnings of blocks add lua-indent-level once each, and endings
714 of blocks subtract `lua-indent-level' once each.  This function is used
715 to determine how the indentation of the following line relates to this
716 one."
717   (if parse-start (goto-char parse-start))
718   (let ((case-fold-search nil)
719         (indentation-info (lua-accumulate-indentation-info
720                            (lua-calculate-indentation-info nil parse-end))))
721     (if (eq (car indentation-info) 'absolute)
722         (- (cdr indentation-info) (current-indentation))
723       (+ (lua-calculate-indentation-left-shift)
724          (cdr indentation-info)
725          (if (lua-is-continuing-statement-p) (- lua-indent-level) 0)))))
726
727 ;; XEmacs change: pre-generate regexps, don't eval-on-compile
728 (defconst lua-left-shift-regexp-1
729   (concat "\\("
730           "\\(\\<"
731           ;;(regexp-opt '("else" "elseif" "until") t)
732           "\\(else\\(?:if\\)?\\|until\\)"
733           "\\>\\)\\($\\|\\s +\\)"
734           "\\)"))
735
736 ;; XEmacs change: pre-generate regexps, don't eval-on-compile
737 (defconst lua-left-shift-regexp-2
738   (concat "\\(\\<"
739           "\\(end\\)"
740           "\\>\\)"))
741
742 ;; XEmacs change: pre-generate regexps, don't eval-on-compile
743 (defconst lua-left-shift-regexp
744   ;; ("else", "elseif", "until" followed by whitespace, or "end"/closing
745   ;; brackets followed by
746   ;; whitespace, punctuation, or closing parentheses)
747   (concat lua-left-shift-regexp-1
748           "\\|\\(\\("
749           lua-left-shift-regexp-2
750           "\\|\\("
751           ;;(regexp-opt '("]" "}" ")"))
752           "[])}]"
753           "\\)\\)\\($\\|\\(\\s \\|\\s.\\)*\\)"
754           "\\)"))
755
756 (defconst lua-left-shift-pos-1
757   2)
758
759 ;; XEmacs change: don't eval-on-compile
760 (defconst lua-left-shift-pos-2
761   (+ 3 (regexp-opt-depth lua-left-shift-regexp-1)))
762
763 ;; XEmacs change: don't eval-on-compile
764 (defconst lua-left-shift-pos-3
765   (+ lua-left-shift-pos-2 (regexp-opt-depth lua-left-shift-regexp-2)))
766
767
768 (defun lua-calculate-indentation-left-shift (&optional parse-start)
769   "Return amount, by which this line should be shifted left.
770 Look for an uninterrupted sequence of block-closing tokens that starts
771 at the beginning of the line.  For each of these tokens, shift indentation
772 to the left by the amount specified in `lua-indent-level'."
773   (let (line-begin
774         (indentation-modifier 0)
775         (case-fold-search nil)
776         (block-token nil))
777     (save-excursion
778       (if parse-start (goto-char parse-start))
779       (beginning-of-line)
780       (setq line-begin (point))
781       ;; Look for the block-closing token sequence
782       (skip-chars-forward lua-indent-whitespace)
783       (catch 'stop
784         (while (and (looking-at lua-left-shift-regexp)
785                     (not (lua-comment-or-string-p)))
786           (let ((last-token (or (match-string lua-left-shift-pos-1)
787                                 (match-string lua-left-shift-pos-2)
788                                 (match-string lua-left-shift-pos-3))))
789             (if (not block-token) (setq block-token last-token))
790             (if (not (string-equal block-token last-token)) (throw 'stop nil))
791             (setq indentation-modifier (+ indentation-modifier
792                                           lua-indent-level))
793                 (forward-char (length (match-string 0))))))
794       indentation-modifier)))
795
796
797 ;;{{{ lua-calculate-indentation
798
799 (defun lua-calculate-indentation (&optional parse-start)
800   "Return appropriate indentation for current line as Lua code.
801 In usual case return an integer: the column to indent to."
802   (let ((pos (point))
803         shift-amt)
804     (save-excursion
805       (if parse-start (setq pos (goto-char parse-start)))
806       (beginning-of-line)
807       (setq shift-amt (if (lua-is-continuing-statement-p) lua-indent-level 0))
808       (if (bobp)          ; If we're at the beginning of the buffer, no change.
809           (+ (current-indentation) shift-amt)
810         ;; This code here searches backwards for a "block beginning/end"
811         ;; It snarfs the indentation of that, plus whatever amount the
812         ;; line was shifted left by, because of block end tokens. It
813         ;; then adds the indentation modifier of that line to obtain the
814         ;; final level of indentation.
815         ;; Finally, if this line continues a statement from the
816         ;; previous line, add another level of indentation.
817         (if (lua-backwards-to-block-begin-or-end)
818             ;; now we're at the line with block beginning or end.
819             (max (+ (current-indentation)
820                     (lua-calculate-indentation-block-modifier)
821                     shift-amt)
822                  0)
823           ;; Failed to find a block begin/end.
824           ;; Just use the previous line's indent.
825           (goto-char pos)
826           (beginning-of-line)
827           (forward-line -1)
828           (+ (current-indentation) shift-amt))))))
829
830 ;;}}}
831
832 ;;}}}
833 ;;{{{ searching
834
835 ;;{{{ lua-beginning-of-proc
836
837 (defun lua-beginning-of-proc (&optional arg)
838   "Move backward to the beginning of a lua proc (or similar).
839 With argument, do it that many times.  Negative arg -N
840 means move forward to Nth following beginning of proc.
841 Return t unless search stops due to beginning or end of buffer."
842   (interactive "P")
843   (or arg
844       (setq arg 1))
845   (let ((found nil)
846                   (ret t))
847     (if (and (< arg 0)
848                                  (looking-at "^function[ \t]"))
849                   (forward-char 1))
850     (while (< arg 0)
851       (if (re-search-forward "^function[ \t]" nil t)
852                          (setq arg (1+ arg)
853                                          found t)
854                   (setq ret nil
855                                   arg 0)))
856     (if found
857                   (beginning-of-line))
858     (while (> arg 0)
859       (if (re-search-backward "^function[ \t]" nil t)
860                          (setq arg (1- arg))
861                   (setq ret nil
862                                   arg 0)))
863     ret))
864
865 ;;}}}
866 ;;{{{ lua-end-of-proc
867
868 (defun lua-end-of-proc (&optional arg)
869   "Move forward to next end of lua proc (or similar).
870 With argument, do it that many times.  Negative argument -N means move
871 back to Nth preceding end of proc.
872
873 This function just searches for a `end' at the beginning of a line."
874   (interactive "P")
875   (or arg
876       (setq arg 1))
877   (let ((found nil)
878         (ret t))
879     (if (and (< arg 0)
880              (not (bolp))
881              (save-excursion
882                (beginning-of-line)
883                (eq (following-char) ?})))
884         (forward-char -1))
885     (while (> arg 0)
886       (if (re-search-forward "^end" nil t)
887           (setq arg (1- arg)
888                 found t)
889         (setq ret nil
890               arg 0)))
891     (while (< arg 0)
892       (if (re-search-backward "^end" nil t)
893           (setq arg (1+ arg)
894                 found t)
895         (setq ret nil
896               arg 0)))
897     (if found
898         (end-of-line))
899     ret))
900
901 ;;}}}
902
903 ;;}}}
904
905 ;;{{{ communication with a inferior process via comint
906
907 ;;{{{ lua-start-process
908
909 (defun lua-start-process (name program &optional startfile &rest switches)
910   "Start a lua process named NAME, running PROGRAM."
911   (or switches
912       (setq switches lua-default-command-switches))
913   (setq lua-process-buffer (apply 'make-comint name program startfile switches))
914   (setq lua-process (get-buffer-process lua-process-buffer))
915   (save-excursion
916     (set-buffer lua-process-buffer))
917   )
918
919 ;;}}}
920 ;;{{{ lua-kill-process
921
922 (defun lua-kill-process ()
923   "Kill lua subprocess and its buffer."
924   (interactive)
925   (if lua-process-buffer
926       (kill-buffer lua-process-buffer)))
927
928 ;;}}}
929 ;;{{{ lua-set-lua-region-start
930
931 (defun lua-set-lua-region-start (&optional arg)
932   "Set start of region for use with `lua-send-lua-region'."
933   (interactive)
934   (set-marker lua-region-start (or arg (point))))
935
936 ;;}}}
937 ;;{{{ lua-set-lua-region-end
938
939 (defun lua-set-lua-region-end (&optional arg)
940   "Set end of region for use with `lua-send-lua-region'."
941   (interactive)
942   (set-marker lua-region-end (or arg (point))))
943
944 ;;}}}
945 ;;{{{ send line/region/buffer to lua-process
946
947 ;;{{{ lua-send-current-line
948
949 (defun lua-send-current-line ()
950   "Send current line to lua subprocess, found in `lua-process'.
951 If `lua-process' is nil or dead, start a new process first."
952   (interactive)
953   (let ((start (save-excursion (beginning-of-line) (point)))
954         (end (save-excursion (end-of-line) (point))))
955     (or (and lua-process
956              (eq (process-status lua-process) 'run))
957         (lua-start-process lua-default-application lua-default-application))
958     (comint-simple-send lua-process
959                       (concat lua-default-command-switches
960                                                   (buffer-substring start end) "
961 \n"))
962     (forward-line 1)
963     (if lua-always-show
964         (display-buffer lua-process-buffer))))
965
966 ;;}}}
967 ;;{{{ lua-send-region
968
969 (defun lua-send-region (start end)
970   "Send region to lua subprocess."
971   (interactive "r")
972   (or (and lua-process
973            (comint-check-proc lua-process-buffer))
974       (lua-start-process lua-default-application lua-default-application))
975   (comint-simple-send lua-process
976                               (buffer-substring start end))
977   (if lua-always-show
978       (display-buffer lua-process-buffer)))
979
980 ;;}}}
981 ;;{{{ lua-send-lua-region
982
983 (defun lua-send-lua-region ()
984   "Send preset lua region to lua subprocess."
985   (interactive)
986   (or (and lua-region-start lua-region-end)
987       (error "lua-region not set"))
988   (or (and lua-process
989            (comint-check-proc lua-process-buffer))
990       (lua-start-process lua-default-application lua-default-application))
991   (comint-simple-send lua-process
992                               (buffer-substring lua-region-start lua-region-end)
993 )
994   (if lua-always-show
995       (display-buffer lua-process-buffer)))
996
997 ;;}}}
998 ;;{{{ lua-send-proc
999
1000 (defun lua-send-proc ()
1001   "Send proc around point to lua subprocess."
1002   (interactive)
1003   (let (beg end)
1004     (save-excursion
1005       (lua-beginning-of-proc)
1006       (setq beg (point))
1007       (lua-end-of-proc)
1008       (setq end (point)))
1009     (or (and lua-process
1010              (comint-check-proc lua-process-buffer))
1011         (lua-start-process lua-default-application lua-default-application))
1012     (comint-simple-send lua-process
1013                                 (buffer-substring beg end))
1014     (if lua-always-show
1015         (display-buffer lua-process-buffer))))
1016
1017 ;;}}}
1018 ;;{{{ lua-send-buffer
1019
1020 ; This needs work... -Bret
1021 (defun lua-send-buffer ()
1022   "Send whole buffer to lua subprocess."
1023   (interactive)
1024   (or (and lua-process
1025            (comint-check-proc lua-process-buffer))
1026       (lua-start-process lua-default-application lua-default-application))
1027   (if (buffer-modified-p)
1028       (comint-simple-send lua-process
1029                            (buffer-substring (point-min) (point-max)))
1030     (comint-simple-send lua-process
1031                         (concat "dofile(\""
1032                                 (buffer-file-name) "\")\n")))
1033   (if lua-always-show
1034       (display-buffer lua-process-buffer)))
1035
1036 ;;}}}
1037
1038 ;;}}}
1039
1040 ;;{{{ lua-restart-with-whole-file
1041
1042 (defun lua-restart-with-whole-file ()
1043   "Restart lua subprocess and send whole file as input."
1044   (interactive)
1045   (lua-kill-process)
1046   (lua-start-process lua-default-application lua-default-application)
1047   (lua-send-buffer))
1048
1049 ;;}}}
1050 ;;{{{ lua-show-process-buffer
1051
1052 (defun lua-show-process-buffer ()
1053   "Make sure `lua-process-buffer' is being displayed."
1054   (interactive)
1055   (display-buffer lua-process-buffer))
1056
1057 ;;}}}
1058 ;;{{{ lua-hide-process-buffer
1059
1060 (defun lua-hide-process-buffer ()
1061   "Delete all windows that display `lua-process-buffer'."
1062   (interactive)
1063   (delete-windows-on lua-process-buffer))
1064
1065 ;;}}}
1066
1067 ;;}}}
1068
1069 ;;{{{ menu bar
1070
1071 (define-key lua-mode-menu [restart-with-whole-file]
1072   '("Restart With Whole File" .  lua-restart-with-whole-file))
1073 (define-key lua-mode-menu [kill-process]
1074   '("Kill Process" . lua-kill-process))
1075
1076 (define-key lua-mode-menu [hide-process-buffer]
1077   '("Hide Process Buffer" . lua-hide-process-buffer))
1078 (define-key lua-mode-menu [show-process-buffer]
1079   '("Show Process Buffer" . lua-show-process-buffer))
1080
1081 (define-key lua-mode-menu [end-of-proc]
1082   '("End Of Proc" . lua-end-of-proc))
1083 (define-key lua-mode-menu [beginning-of-proc]
1084   '("Beginning Of Proc" . lua-beginning-of-proc))
1085
1086 (define-key lua-mode-menu [send-lua-region]
1087   '("Send Lua-Region" . lua-send-lua-region))
1088 (define-key lua-mode-menu [set-lua-region-end]
1089   '("Set Lua-Region End" . lua-set-lua-region-end))
1090 (define-key lua-mode-menu [set-lua-region-start]
1091   '("Set Lua-Region Start" . lua-set-lua-region-start))
1092
1093 (define-key lua-mode-menu [send-current-line]
1094   '("Send Current Line" . lua-send-current-line))
1095 (define-key lua-mode-menu [send-region]
1096   '("Send Region" . lua-send-region))
1097 (define-key lua-mode-menu [send-proc]
1098   '("Send Proc" . lua-send-proc))
1099 (define-key lua-mode-menu [send-buffer]
1100   '("Send Buffer" . lua-send-buffer))
1101
1102 ;;}}}
1103
1104 (provide 'lua-mode)
1105
1106
1107 ;;{{{ Emacs local variables
1108
1109 ;; Local Variables:
1110 ;; folded-file: t
1111 ;; End:
1112
1113 ;;}}}
1114
1115 ;;; lua-mode.el ends here