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