]> code.delx.au - gnu-emacs/blob - lisp/progmodes/opascal.el
e608ea8af0e259bba4701d813a34dc952d4ee090
[gnu-emacs] / lisp / progmodes / opascal.el
1 ;;; opascal.el --- major mode for editing Object Pascal source in Emacs -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 1998-1999, 2001-2013 Free Software Foundation, Inc.
4
5 ;; Authors: Ray Blaak <blaak@infomatch.com>,
6 ;; Simon South <ssouth@member.fsf.org>
7 ;; Maintainer: Simon South <ssouth@member.fsf.org>
8 ;; Keywords: languages
9
10 ;; This file is part of GNU Emacs.
11
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24
25 ;;; Commentary:
26
27 ;; To enter OPascal mode when you find an Object Pascal source file, one must
28 ;; override the auto-mode-alist to associate OPascal with .pas (and .dpr and
29 ;; .dpk) files. Emacs, by default, will otherwise enter Pascal mode. E.g.
30 ;;
31 ;; (autoload 'opascal-mode "opascal")
32 ;; (add-to-list 'auto-mode-alist
33 ;; '("\\.\\(pas\\|dpr\\|dpk\\)\\'" . opascal-mode))
34
35 ;; When you have entered OPascal mode, you may get more info by pressing
36 ;; C-h m.
37
38 ;; This OPascal mode implementation is fairly tolerant of syntax errors,
39 ;; relying as much as possible on the indentation of the previous statement.
40 ;; This also makes it faster and simpler, since there is less searching for
41 ;; properly constructed beginnings.
42
43 ;;; Code:
44
45 (defgroup opascal nil
46 "Major mode for editing OPascal source in Emacs."
47 :version "24.4"
48 :group 'languages)
49
50 (defconst opascal-debug nil
51 "True if in debug mode.")
52
53 (define-obsolete-variable-alias
54 'delphi-search-path 'opascal-search-path "24.4")
55 (defcustom opascal-search-path "."
56 "Directories to search when finding external units.
57 It is a list of directory strings. If only a single directory,
58 it can be a single string instead of a list. If a directory
59 ends in \"...\" then that directory is recursively searched."
60 :type 'string)
61
62 (define-obsolete-variable-alias
63 'delphi-indent-level 'opascal-indent-level "24.4")
64 (defcustom opascal-indent-level 3
65 "Indentation of OPascal statements with respect to containing block.
66 E.g.
67
68 begin
69 // This is an indent of 3.
70 end;"
71 :type 'integer)
72
73 (define-obsolete-variable-alias
74 'delphi-compound-block-indent 'opascal-compound-block-indent "24.4")
75 (defcustom opascal-compound-block-indent 0
76 "Extra indentation for blocks in compound statements. E.g.
77
78 // block indent = 0 vs // block indent = 2
79 if b then if b then
80 begin begin
81 end else begin end
82 end; else
83 begin
84 end;"
85 :type 'integer)
86
87 (define-obsolete-variable-alias
88 'delphi-case-label-indent 'opascal-case-label-indent "24.4")
89 (defcustom opascal-case-label-indent opascal-indent-level
90 "Extra indentation for case statement labels. E.g.
91
92 // case indent = 0 vs // case indent = 3
93 case value of case value of
94 v1: process_v1; v1: process_v1;
95 v2: process_v2; v2: process_v2;
96 else else
97 process_else; process_else;
98 end; end;"
99 :type 'integer)
100
101 (define-obsolete-variable-alias 'delphi-verbose 'opascal-verbose "24.4")
102 (defcustom opascal-verbose t ; nil
103 "If true then OPascal token processing progress is reported to the user."
104 :type 'boolean)
105
106 (define-obsolete-variable-alias
107 'delphi-tab-always-indents 'opascal-tab-always-indents "24.4")
108 (defcustom opascal-tab-always-indents tab-always-indent
109 "Non-nil means TAB in OPascal mode should always reindent the current line,
110 regardless of where in the line point is when the TAB command is used."
111 :type 'boolean)
112
113 (defconst opascal-directives
114 '(absolute abstract assembler automated cdecl default dispid dynamic
115 export external far forward index inline message name near nodefault
116 overload override pascal private protected public published read readonly
117 register reintroduce resident resourcestring safecall stdcall stored
118 virtual write writeonly)
119 "OPascal4 directives.")
120
121 (defconst opascal-keywords
122 (append
123 '(;; Keywords.
124 and array as asm at begin case class const constructor contains
125 destructor dispinterface div do downto else end except exports
126 file finalization finally for function goto if implementation implements
127 in inherited initialization interface is label library mod nil not
128 of object on or out package packed procedure program property
129 raise record repeat requires result self set shl shr then threadvar
130 to try type unit uses until var while with xor
131
132 ;; These routines should be keywords, if Borland had the balls.
133 break exit)
134
135 ;; We want directives to look like keywords.
136 opascal-directives)
137 "OPascal4 keywords.")
138
139 (defconst opascal-previous-terminators `(semicolon comma)
140 "Expression/statement terminators that denote a previous expression.")
141
142 (defconst opascal-comments
143 '(comment-single-line comment-multi-line-1 comment-multi-line-2)
144 "Tokens that represent comments.")
145
146 (defconst opascal-strings
147 '(string double-quoted-string)
148 "Tokens that represent string literals.")
149
150 (defconst opascal-whitespace `(space newline ,@opascal-comments)
151 "Tokens that are considered whitespace.")
152
153 (defconst opascal-routine-statements
154 '(procedure function constructor destructor property)
155 "Marks the start of a routine, or routine-ish looking expression.")
156
157 (defconst opascal-body-expr-statements '(if while for on)
158 "Statements that have either a single statement or a block as a body and also
159 are followed by an expression.")
160
161 (defconst opascal-expr-statements `(case ,@opascal-body-expr-statements)
162 "Expression statements contain expressions after their keyword.")
163
164 (defconst opascal-body-statements `(else ,@opascal-body-expr-statements)
165 "Statements that have either a single statement or a block as a body.")
166
167 (defconst opascal-expr-delimiters '(then do of)
168 "Expression delimiter tokens.")
169
170 (defconst opascal-binary-ops
171 '(plus minus equals not-equals times divides div mod and or xor)
172 "OPascal binary operations.")
173
174 (defconst opascal-visibilities '(public private protected published automated)
175 "Class visibilities.")
176
177 (defconst opascal-block-statements
178 '(begin try case repeat initialization finalization asm)
179 "Statements that contain multiple substatements.")
180
181 (defconst opascal-mid-block-statements
182 `(except finally ,@opascal-visibilities)
183 "Statements that mark mid sections of the enclosing block.")
184
185 (defconst opascal-end-block-statements `(end until)
186 "Statements that end block sections.")
187
188 (defconst opascal-match-block-statements
189 `(,@opascal-end-block-statements ,@opascal-mid-block-statements)
190 "Statements that match the indentation of the parent block.")
191
192 (defconst opascal-decl-sections '(type const var label resourcestring)
193 "Denotes the start of a declaration section.")
194
195 (defconst opascal-interface-types '(dispinterface interface)
196 "Interface types.")
197
198 (defconst opascal-class-types '(class object)
199 "Class types.")
200
201 (defconst opascal-composite-types
202 `(,@opascal-class-types ,@opascal-interface-types record)
203 "Types that contain declarations within them.")
204
205 (defconst opascal-unit-sections
206 '(interface implementation program library package)
207 "Unit sections within which the indent is 0.")
208
209 (defconst opascal-use-clauses `(uses requires exports contains)
210 "Statements that refer to foreign symbols.")
211
212 (defconst opascal-unit-statements
213 `(,@opascal-use-clauses ,@opascal-unit-sections initialization finalization)
214 "Statements indented at level 0.")
215
216 (defconst opascal-decl-delimiters
217 `(,@opascal-decl-sections ,@opascal-unit-statements
218 ,@opascal-routine-statements)
219 "Statements that a declaration statement should align with.")
220
221 (defconst opascal-decl-matchers
222 `(begin ,@opascal-decl-sections)
223 "Statements that should match to declaration statement indentation.")
224
225 (defconst opascal-enclosing-statements
226 `(,@opascal-block-statements ,@opascal-mid-block-statements
227 ,@opascal-decl-sections ,@opascal-use-clauses ,@opascal-routine-statements)
228 "Delimits an enclosing statement.")
229
230 (defconst opascal-previous-statements
231 `(,@opascal-unit-statements ,@opascal-routine-statements)
232 "Delimits a previous statement.")
233
234 (defconst opascal-previous-enclosing-statements
235 `(,@opascal-block-statements ,@opascal-mid-block-statements
236 ,@opascal-decl-sections)
237 "Delimits a previous enclosing statement.")
238
239 (defconst opascal-begin-enclosing-tokens
240 `(,@opascal-block-statements ,@opascal-mid-block-statements)
241 "Tokens that a begin token indents from.")
242
243 (defconst opascal-begin-previous-tokens
244 `(,@opascal-decl-sections ,@opascal-routine-statements)
245 "Tokens that a begin token aligns with, but only if not part of a nested
246 routine.")
247
248 (defconst opascal-space-chars "\000-\011\013- ") ; all except \n
249 (defconst opascal-non-space-chars (concat "^" opascal-space-chars))
250 (defconst opascal-spaces-re (concat "[" opascal-space-chars "]*"))
251 (defconst opascal-leading-spaces-re (concat "^" opascal-spaces-re))
252 (defconst opascal-word-chars "a-zA-Z0-9_")
253
254 (defvar opascal-mode-syntax-table
255 (let ((st (make-syntax-table)))
256 ;; Strings.
257 (modify-syntax-entry ?\" "\"" st)
258 (modify-syntax-entry ?\' "\"" st)
259 ;; Comments.
260 (modify-syntax-entry ?\{ "<" st)
261 (modify-syntax-entry ?\} ">" st)
262 (modify-syntax-entry ?\( "()1" st)
263 (modify-syntax-entry ?\) ")(4" st)
264 (modify-syntax-entry ?* ". 23b" st)
265 (modify-syntax-entry ?/ ". 12c" st)
266 (modify-syntax-entry ?\n "> c" st)
267 st))
268
269 (defmacro opascal-save-excursion (&rest forms)
270 ;; Executes the forms such that any movements have no effect, including
271 ;; searches.
272 `(save-excursion
273 (save-match-data
274 (let ((inhibit-point-motion-hooks t)
275 (deactivate-mark nil))
276 (progn ,@forms)))))
277
278 (defsubst opascal-is (element in-set)
279 ;; If the element is in the set, the element cdr is returned, otherwise nil.
280 (memq element in-set))
281
282 (defun opascal-string-of (start end)
283 ;; Returns the buffer string from start to end.
284 (buffer-substring-no-properties start end))
285
286 (defun opascal-looking-at-string (p s)
287 ;; True if point p marks the start of string s. s is not a regular
288 ;; expression.
289 (let ((limit (+ p (length s))))
290 (and (<= limit (point-max))
291 (string= s (opascal-string-of p limit)))))
292
293 (defun opascal-token-of (kind start end)
294 ;; Constructs a token from a kind symbol and its start/end points.
295 `[,kind ,start ,end])
296
297 (defsubst opascal-token-kind (token)
298 ;; Returns the kind symbol of the token.
299 (if token (aref token 0) nil))
300
301 (defun opascal-set-token-kind (token to-kind)
302 ;; Sets the kind symbol of the token.
303 (if token (aset token 0 to-kind)))
304
305 (defsubst opascal-token-start (token)
306 ;; Returns the start point of the token.
307 (if token (aref token 1) (point-min)))
308
309 (defsubst opascal-token-end (token)
310 ;; Returns the end point of the token.
311 (if token (aref token 2) (point-min)))
312
313 (defun opascal-set-token-start (token start)
314 ;; Sets the start point of the token.
315 (if token (aset token 1 start)))
316
317 (defun opascal-set-token-end (token end)
318 ;; Sets the end point of the token.
319 (if token (aset token 2 end)))
320
321 (defun opascal-token-string (token)
322 ;; Returns the string image of the token.
323 (if token
324 (opascal-string-of (opascal-token-start token) (opascal-token-end token))
325 ""))
326
327 (defun opascal-in-token (p token)
328 ;; Returns true if the point p is within the token's start/end points.
329 (and (<= (opascal-token-start token) p) (< p (opascal-token-end token))))
330
331 (defun opascal-column-of (p)
332 ;; Returns the column of the point p.
333 (save-excursion (goto-char p) (current-column)))
334
335 (defvar opascal-progress-last-reported-point nil
336 "The last point at which progress was reported.")
337
338 (defconst opascal-parsing-progress-step 16384
339 "Number of chars to process before the next parsing progress report.")
340 (defconst opascal-scanning-progress-step 2048
341 "Number of chars to process before the next scanning progress report.")
342
343 (defun opascal-progress-start ()
344 ;; Initializes progress reporting.
345 (setq opascal-progress-last-reported-point nil))
346
347 (defun opascal-progress-done (&rest msgs)
348 ;; Finalizes progress reporting.
349 (setq opascal-progress-last-reported-point nil)
350 (when opascal-verbose
351 (if (null msgs)
352 (message "")
353 (apply #'message msgs))))
354
355 (defun opascal-step-progress (p desc step-size)
356 ;; If enough distance has elapsed since the last reported point, then report
357 ;; the current progress to the user.
358 (cond ((null opascal-progress-last-reported-point)
359 ;; This is the first progress step.
360 (setq opascal-progress-last-reported-point p))
361
362 ((and opascal-verbose
363 (>= (abs (- p opascal-progress-last-reported-point)) step-size))
364 ;; Report the percentage complete.
365 (setq opascal-progress-last-reported-point p)
366 (message "%s %s ... %d%%"
367 desc (buffer-name) (/ (* 100 p) (point-max))))))
368
369 (defun opascal-next-line-start (&optional from-point)
370 ;; Returns the first point of the next line.
371 (let ((curr-point (point))
372 (next nil))
373 (if from-point (goto-char from-point))
374 (end-of-line)
375 (setq next (min (1+ (point)) (point-max)))
376 (goto-char curr-point)
377 next))
378
379 (defconst opascal--literal-start-re (regexp-opt '("//" "{" "(*" "'" "\"")))
380
381 (defun opascal-literal-kind (p)
382 ;; Returns the literal kind the point p is in (or nil if not in a literal).
383 (when (and (<= (point-min) p) (<= p (point-max)))
384 (save-excursion
385 (let ((ppss (syntax-ppss p)))
386 ;; We want to return non-nil when right in front
387 ;; of a comment/string.
388 (if (null (nth 8 ppss))
389 (when (looking-at opascal--literal-start-re)
390 (pcase (char-after)
391 (`?/ 'comment-single-line)
392 (`?\{ 'comment-multi-line-1)
393 (`?\( 'comment-multi-line-2)
394 (`?\' 'string)
395 (`?\" 'double-quoted-string)))
396 (if (nth 3 ppss) ;String.
397 (if (eq (nth 3 ppss) ?\")
398 'double-quoted-string 'string)
399 (pcase (nth 7 ppss)
400 (`2 'comment-single-line)
401 (`1 'comment-multi-line-2)
402 (_ 'comment-multi-line-1))))))))
403
404 (defun opascal-literal-start-pattern (literal-kind)
405 ;; Returns the start pattern of the literal kind.
406 (cdr (assoc literal-kind
407 '((comment-single-line . "//")
408 (comment-multi-line-1 . "{")
409 (comment-multi-line-2 . "(*")
410 (string . "'")
411 (double-quoted-string . "\"")))))
412
413 (defun opascal-literal-end-pattern (literal-kind)
414 ;; Returns the end pattern of the literal kind.
415 (cdr (assoc literal-kind
416 '((comment-single-line . "\n")
417 (comment-multi-line-1 . "}")
418 (comment-multi-line-2 . "*)")
419 (string . "'")
420 (double-quoted-string . "\"")))))
421
422 (defun opascal-literal-stop-pattern (literal-kind)
423 ;; Returns the pattern that delimits end of the search for the literal kind.
424 ;; These are regular expressions.
425 (cdr (assoc literal-kind
426 '((comment-single-line . "\n")
427 (comment-multi-line-1 . "}")
428 (comment-multi-line-2 . "\\*)")
429 ;; Strings cannot span lines.
430 (string . "['\n]")
431 (double-quoted-string . "[\"\n]")))))
432
433 (defun opascal-is-literal-end (p)
434 ;; True if the point p is at the end point of a (completed) literal.
435 (save-excursion
436 (and (null (nth 8 (syntax-ppss p)))
437 (nth 8 (syntax-ppss (1- p))))))
438
439 (defun opascal-literal-token-at (p)
440 "Return the literal token surrounding the point P, or nil if none."
441 (save-excursion
442 (let ((ppss (syntax-ppss p)))
443 (when (or (nth 8 ppss) (looking-at opascal--literal-start-re))
444 (let* ((new-start (or (nth 8 ppss) p))
445 (new-end (progn
446 (goto-char new-start)
447 (condition-case nil
448 (if (memq (char-after) '(?\' ?\"))
449 (forward-sexp 1)
450 (forward-comment 1))
451 (scan-error (goto-char (point-max))))
452 (point))))
453 (opascal-token-of (opascal-literal-kind p) new-start new-end))))))
454
455 (defun opascal-point-token-at (p kind)
456 ;; Returns the single character token at the point p.
457 (opascal-token-of kind p (1+ p)))
458
459 (defsubst opascal-char-token-at (p char kind)
460 ;; Returns the token at the point p that describes the specified character.
461 ;; If not actually over such a character, nil is returned.
462 (when (eq char (char-after p))
463 (opascal-token-of kind p (1+ p))))
464
465 (defun opascal-charset-token-at (p charset kind)
466 ;; Returns the token surrounding point p that contains only members of the
467 ;; character set.
468 (let ((currp (point))
469 (end nil)
470 (token nil))
471 (goto-char p)
472 (when (> (skip-chars-forward charset) 0)
473 (setq end (point))
474 (goto-char (1+ p))
475 (skip-chars-backward charset)
476 (setq token (opascal-token-of kind (point) end)))
477 (goto-char currp)
478 token))
479
480 (defun opascal-space-token-at (p)
481 ;; If point p is surrounded by space characters, then return the token of the
482 ;; contiguous spaces.
483 (opascal-charset-token-at p opascal-space-chars 'space))
484
485 (defun opascal-word-token-at (p)
486 ;; If point p is over a word (i.e. identifier characters), then return a word
487 ;; token. If the word is actually a keyword, then return the keyword token.
488 (let ((word (opascal-charset-token-at p opascal-word-chars 'word)))
489 (when word
490 (let* ((word-image (downcase (opascal-token-string word)))
491 (keyword (intern-soft word-image)))
492 (when (and (or keyword (string= "nil" word-image))
493 (opascal-is keyword opascal-keywords))
494 (opascal-set-token-kind word keyword))
495 word))))
496
497 (defun opascal-explicit-token-at (p token-string kind)
498 ;; If point p is anywhere in the token string then returns the resulting
499 ;; token.
500 (let ((token (opascal-charset-token-at p token-string kind)))
501 (when (and token (string= token-string (opascal-token-string token)))
502 token)))
503
504 (defun opascal-token-at (p)
505 ;; Returns the token from parsing text at point p.
506 (when (and (<= (point-min) p) (<= p (point-max)))
507 (cond ((opascal-char-token-at p ?\n 'newline))
508
509 ((opascal-literal-token-at p))
510
511 ((opascal-space-token-at p))
512
513 ((opascal-word-token-at p))
514
515 ((opascal-char-token-at p ?\( 'open-group))
516 ((opascal-char-token-at p ?\) 'close-group))
517 ((opascal-char-token-at p ?\[ 'open-group))
518 ((opascal-char-token-at p ?\] 'close-group))
519 ((opascal-char-token-at p ?\; 'semicolon))
520 ((opascal-char-token-at p ?. 'dot))
521 ((opascal-char-token-at p ?, 'comma))
522 ((opascal-char-token-at p ?= 'equals))
523 ((opascal-char-token-at p ?+ 'plus))
524 ((opascal-char-token-at p ?- 'minus))
525 ((opascal-char-token-at p ?* 'times))
526 ((opascal-char-token-at p ?/ 'divides))
527 ((opascal-char-token-at p ?: 'colon))
528
529 ((opascal-explicit-token-at p "<>" 'not-equals))
530
531 ((opascal-point-token-at p 'punctuation)))))
532
533 (defun opascal-current-token ()
534 ;; Returns the opascal source token under the current point.
535 (opascal-token-at (point)))
536
537 (defun opascal-next-token (token)
538 ;; Returns the token after the specified token.
539 (when token
540 (let ((next (opascal-token-at (opascal-token-end token))))
541 (if next
542 (opascal-step-progress (opascal-token-start next) "Scanning"
543 opascal-scanning-progress-step))
544 next)))
545
546 (defun opascal-previous-token (token)
547 ;; Returns the token before the specified token.
548 (when token
549 (let ((previous (opascal-token-at (1- (opascal-token-start token)))))
550 (if previous
551 (opascal-step-progress (opascal-token-start previous) "Scanning"
552 opascal-scanning-progress-step))
553 previous)))
554
555 (defun opascal-next-visible-token (token)
556 ;; Returns the first non-space token after the specified token.
557 (let (next-token)
558 (while (progn
559 (setq next-token (opascal-next-token token))
560 (opascal-is (opascal-token-kind next-token) '(space newline))))
561 next-token))
562
563 (defun opascal-group-start (from-token)
564 ;; Returns the token that denotes the start of the ()/[] group.
565 (let ((token (opascal-previous-token from-token))
566 (token-kind nil))
567 (catch 'done
568 (while token
569 (setq token-kind (opascal-token-kind token))
570 (cond
571 ;; Skip over nested groups.
572 ((eq 'close-group token-kind) (setq token (opascal-group-start token)))
573 ((eq 'open-group token-kind) (throw 'done token)))
574 (setq token (opascal-previous-token token)))
575 ;; Start not found.
576 nil)))
577
578 (defun opascal-group-end (from-token)
579 ;; Returns the token that denotes the end of the ()/[] group.
580 (let ((token (opascal-next-token from-token))
581 (token-kind nil))
582 (catch 'done
583 (while token
584 (setq token-kind (opascal-token-kind token))
585 (cond
586 ;; Skip over nested groups.
587 ((eq 'open-group token-kind) (setq token (opascal-group-end token)))
588 ((eq 'close-group token-kind) (throw 'done token)))
589 (setq token (opascal-next-token token)))
590 ;; end not found.
591 nil)))
592
593 (defun opascal-indent-of (token &optional offset)
594 ;; Returns the start column of the token, plus any offset.
595 (let ((indent (+ (opascal-column-of (opascal-token-start token))
596 (if offset offset 0))))
597 (when opascal-debug
598 (opascal-debug-log
599 (concat "\n Indent of: %S %S"
600 "\n column: %d indent: %d offset: %d")
601 token (opascal-token-string token)
602 (opascal-column-of (opascal-token-start token))
603 indent (if offset offset 0)))
604 indent))
605
606 (defun opascal-line-indent-of (from-token &optional offset &rest terminators)
607 ;; Returns the column of first non-space character on the token's line, plus
608 ;; any offset. We also stop if one of the terminators or an open ( or [ is
609 ;; encountered.
610 (let ((token (opascal-previous-token from-token))
611 (last-token from-token)
612 (kind nil))
613 (catch 'done
614 (while token
615 (setq kind (opascal-token-kind token))
616 (cond
617 ;; Skip over ()/[] groups.
618 ((eq 'close-group kind) (setq token (opascal-group-start token)))
619
620 ;; Stop at the beginning of the line or an open group.
621 ((opascal-is kind '(newline open-group)) (throw 'done nil))
622
623 ;; Stop at one of the specified terminators.
624 ((opascal-is kind terminators) (throw 'done nil)))
625 (unless (opascal-is kind opascal-whitespace) (setq last-token token))
626 (setq token (opascal-previous-token token))))
627 (opascal-indent-of last-token offset)))
628
629 (defun opascal-stmt-line-indent-of (from-token &optional offset)
630 ;; Like `opascal-line-indent-of' except is also stops on a use clause, and
631 ;; colons that precede statements (i.e. case labels).
632 (let ((token (opascal-previous-token from-token))
633 (last-token from-token)
634 (kind nil))
635 (catch 'done
636 (while token
637 (setq kind (opascal-token-kind token))
638 (cond
639 ((and (eq 'colon kind)
640 (opascal-is (opascal-token-kind last-token)
641 `(,@opascal-block-statements
642 ,@opascal-expr-statements)))
643 ;; We hit a label followed by a statement. Indent to the statement.
644 (throw 'done nil))
645
646 ;; Skip over ()/[] groups.
647 ((eq 'close-group kind) (setq token (opascal-group-start token)))
648
649 ((opascal-is kind `(newline open-group ,@opascal-use-clauses))
650 ;; Stop at the beginning of the line, an open group, or a use clause
651 (throw 'done nil)))
652 (unless (opascal-is kind opascal-whitespace) (setq last-token token))
653 (setq token (opascal-previous-token token))))
654 (opascal-indent-of last-token offset)))
655
656 (defun opascal-open-group-indent (token last-token &optional offset)
657 ;; Returns the indent relative to an unmatched ( or [.
658 (when (eq 'open-group (opascal-token-kind token))
659 (if last-token
660 (opascal-indent-of last-token offset)
661 ;; There is nothing following the ( or [. Indent from its line.
662 (opascal-stmt-line-indent-of token opascal-indent-level))))
663
664 (defun opascal-composite-type-start (token last-token)
665 ;; Returns true (actually the last-token) if the pair equals (= class), (=
666 ;; dispinterface), (= interface), (= object), or (= record), and nil
667 ;; otherwise.
668 (if (and (eq 'equals (opascal-token-kind token))
669 (opascal-is (opascal-token-kind last-token) opascal-composite-types))
670 last-token))
671
672 (defun opascal-is-simple-class-type (at-token limit-token)
673 ;; True if at-token is the start of a simple class type. E.g.
674 ;; class of TClass;
675 ;; class (TBaseClass);
676 ;; class;
677 (when (opascal-is (opascal-token-kind at-token) opascal-class-types)
678 (catch 'done
679 ;; Scan until the semi colon.
680 (let ((token (opascal-next-token at-token))
681 (token-kind nil)
682 (limit (opascal-token-start limit-token)))
683 (while (and token (<= (opascal-token-start token) limit))
684 (setq token-kind (opascal-token-kind token))
685 (cond
686 ;; A semicolon delimits the search.
687 ((eq 'semicolon token-kind) (throw 'done token))
688
689 ;; Skip over the inheritance list.
690 ((eq 'open-group token-kind) (setq token (opascal-group-end token)))
691
692 ;; Only allow "of" and whitespace, and an identifier
693 ((opascal-is token-kind `(of word ,@opascal-whitespace)))
694
695 ;; Otherwise we are not in a simple class declaration.
696 ((throw 'done nil)))
697 (setq token (opascal-next-token token)))))))
698
699 (defun opascal-block-start (from-token &optional stop-on-class)
700 ;; Returns the token that denotes the start of the block.
701 (let ((token (opascal-previous-token from-token))
702 (last-token nil)
703 (token-kind nil))
704 (catch 'done
705 (while token
706 (setq token-kind (opascal-token-kind token))
707 (cond
708 ;; Skip over nested blocks.
709 ((opascal-is token-kind opascal-end-block-statements)
710 (setq token (opascal-block-start token)))
711
712 ;; Regular block start found.
713 ((opascal-is token-kind opascal-block-statements)
714 (throw 'done
715 ;; As a special case, when a "case" block appears
716 ;; within a record declaration (to denote a variant
717 ;; part), the record declaration should be considered
718 ;; the enclosing block.
719 (if (eq 'case token-kind)
720 (let ((enclosing-token
721 (opascal-block-start token
722 'stop-on-class)))
723 (if
724 (eq 'record
725 (opascal-token-kind enclosing-token))
726 (if stop-on-class
727 enclosing-token
728 (opascal-previous-token enclosing-token))
729 token))
730 token)))
731
732 ;; A class/record start also begins a block.
733 ((opascal-composite-type-start token last-token)
734 (throw 'done (if stop-on-class last-token token)))
735 )
736 (unless (opascal-is token-kind opascal-whitespace)
737 (setq last-token token))
738 (setq token (opascal-previous-token token)))
739 ;; Start not found.
740 nil)))
741
742 (defun opascal-else-start (from-else)
743 ;; Returns the token of the if or case statement.
744 (let ((token (opascal-previous-token from-else))
745 (token-kind nil)
746 (semicolon-count 0))
747 (catch 'done
748 (while token
749 (setq token-kind (opascal-token-kind token))
750 (cond
751 ;; Skip over nested groups.
752 ((eq 'close-group token-kind) (setq token (opascal-group-start token)))
753
754 ;; Skip over any nested blocks.
755 ((opascal-is token-kind opascal-end-block-statements)
756 (setq token (opascal-block-start token)))
757
758 ((eq 'semicolon token-kind)
759 ;; Semicolon means we are looking for an enclosing if, unless we
760 ;; are in a case statement. Keep counts of the semicolons and decide
761 ;; later.
762 (setq semicolon-count (1+ semicolon-count)))
763
764 ((and (eq 'if token-kind) (= semicolon-count 0))
765 ;; We only can match an if when there have been no intervening
766 ;; semicolons.
767 (throw 'done token))
768
769 ((eq 'case token-kind)
770 ;; We have hit a case statement start.
771 (throw 'done token)))
772 (setq token (opascal-previous-token token)))
773 ;; No if or case statement found.
774 nil)))
775
776 (defun opascal-comment-content-start (comment)
777 ;; Returns the point of the first non-space character in the comment.
778 (let ((kind (opascal-token-kind comment)))
779 (when (opascal-is kind opascal-comments)
780 (opascal-save-excursion
781 (goto-char (+ (opascal-token-start comment)
782 (length (opascal-literal-start-pattern kind))))
783 (skip-chars-forward opascal-space-chars)
784 (point)))))
785
786 (defun opascal-comment-block-start (comment)
787 ;; Returns the starting comment token of a contiguous // comment block. If
788 ;; the comment is multiline (i.e. {...} or (*...*)), the original comment is
789 ;; returned.
790 (if (not (eq 'comment-single-line (opascal-token-kind comment)))
791 comment
792 ;; Scan until we run out of // comments.
793 (let ((prev-comment comment)
794 (start-comment comment))
795 (while (let ((kind (opascal-token-kind prev-comment)))
796 (cond ((eq kind 'space))
797 ((eq kind 'comment-single-line)
798 (setq start-comment prev-comment))
799 (t nil)))
800 (setq prev-comment (opascal-previous-token prev-comment)))
801 start-comment)))
802
803 (defun opascal-comment-block-end (comment)
804 ;; Returns the end comment token of a contiguous // comment block. If the
805 ;; comment is multiline (i.e. {...} or (*...*)), the original comment is
806 ;; returned.
807 (if (not (eq 'comment-single-line (opascal-token-kind comment)))
808 comment
809 ;; Scan until we run out of // comments.
810 (let ((next-comment comment)
811 (end-comment comment))
812 (while (let ((kind (opascal-token-kind next-comment)))
813 (cond ((eq kind 'space))
814 ((eq kind 'comment-single-line)
815 (setq end-comment next-comment))
816 (t nil)))
817 (setq next-comment (opascal-next-token next-comment)))
818 end-comment)))
819
820 (defun opascal-on-first-comment-line (comment)
821 ;; Returns true if the current point is on the first line of the comment.
822 (save-excursion
823 (let ((comment-start (opascal-token-start comment))
824 (current-point (point)))
825 (goto-char comment-start)
826 (end-of-line)
827 (and (<= comment-start current-point) (<= current-point (point))))))
828
829 (defun opascal-comment-indent-of (comment)
830 ;; Returns the correct indentation for the comment.
831 (let ((start-comment (opascal-comment-block-start comment)))
832 (if (and (eq start-comment comment)
833 (opascal-on-first-comment-line comment))
834 ;; Indent as a statement.
835 (opascal-enclosing-indent-of comment)
836 (save-excursion
837 (let ((kind (opascal-token-kind comment)))
838 (beginning-of-line)
839 (cond ((eq 'comment-single-line kind)
840 ;; Indent to the first comment in the // block.
841 (opascal-indent-of start-comment))
842
843 ((looking-at (concat opascal-leading-spaces-re
844 (opascal-literal-stop-pattern kind)))
845 ;; Indent multi-line comment terminators to the comment start.
846 (opascal-indent-of comment))
847
848 ;; Indent according to the comment's content start.
849 ((opascal-column-of (opascal-comment-content-start comment)))))))
850 ))
851
852 (defun opascal-is-use-clause-end (at-token last-token last-colon from-kind)
853 ;; True if we are after the end of a uses type clause.
854 (when (and last-token
855 (not last-colon)
856 (eq 'comma (opascal-token-kind at-token))
857 (eq 'semicolon from-kind))
858 ;; Scan for the uses statement, just to be sure.
859 (let ((token (opascal-previous-token at-token))
860 (token-kind nil))
861 (catch 'done
862 (while token
863 (setq token-kind (opascal-token-kind token))
864 (cond ((opascal-is token-kind opascal-use-clauses)
865 (throw 'done t))
866
867 ;; Whitespace, identifiers, strings, "in" keyword, and commas
868 ;; are allowed in use clauses.
869 ((or (opascal-is token-kind '(word comma in newline))
870 (opascal-is token-kind opascal-whitespace)
871 (opascal-is token-kind opascal-strings)))
872
873 ;; Nothing else is.
874 ((throw 'done nil)))
875 (setq token (opascal-previous-token token)))
876 nil))))
877
878 (defun opascal-is-block-after-expr-statement (token)
879 ;; Returns true if we have a block token trailing an expression delimiter (of
880 ;; presumably an expression statement).
881 (when (opascal-is (opascal-token-kind token) opascal-block-statements)
882 (let ((previous (opascal-previous-token token))
883 (previous-kind nil))
884 (while (progn
885 (setq previous-kind (opascal-token-kind previous))
886 (eq previous-kind 'space))
887 (setq previous (opascal-previous-token previous)))
888 (or (opascal-is previous-kind opascal-expr-delimiters)
889 (eq previous-kind 'else)))))
890
891 (defun opascal-previous-indent-of (from-token)
892 ;; Returns the indentation of the previous statement of the token.
893 (let ((token (opascal-previous-token from-token))
894 (token-kind nil)
895 (from-kind (opascal-token-kind from-token))
896 (last-colon nil)
897 (last-of nil)
898 (last-token nil))
899 (catch 'done
900 (while token
901 (setq token-kind (opascal-token-kind token))
902 (cond
903 ;; An open ( or [ always is an indent point.
904 ((eq 'open-group token-kind)
905 (throw 'done (opascal-open-group-indent token last-token)))
906
907 ;; Skip over any ()/[] groups.
908 ((eq 'close-group token-kind) (setq token (opascal-group-start token)))
909
910 ((opascal-is token-kind opascal-end-block-statements)
911 (if (eq 'newline (opascal-token-kind (opascal-previous-token token)))
912 ;; We can stop at an end token that is right up against the
913 ;; margin.
914 (throw 'done 0)
915 ;; Otherwise, skip over any nested blocks.
916 (setq token (opascal-block-start token))))
917
918 ;; Special case: if we encounter a ", word;" then we assume that we
919 ;; are in some kind of uses clause, and thus indent to column 0. This
920 ;; works because no other constructs are known to have that form.
921 ;; This fixes the irritating case of having indents after a uses
922 ;; clause look like:
923 ;; uses
924 ;; someUnit,
925 ;; someOtherUnit;
926 ;; // this should be at column 0!
927 ((opascal-is-use-clause-end token last-token last-colon from-kind)
928 (throw 'done 0))
929
930 ;; A previous terminator means we can stop. If we are on a directive,
931 ;; however, then we are not actually encountering a new statement.
932 ((and last-token
933 (opascal-is token-kind opascal-previous-terminators)
934 (not (opascal-is (opascal-token-kind last-token)
935 opascal-directives)))
936 (throw 'done (opascal-stmt-line-indent-of last-token 0)))
937
938 ;; Ignore whitespace.
939 ((opascal-is token-kind opascal-whitespace))
940
941 ;; Remember any "of" we encounter, since that affects how we
942 ;; indent to a case statement within a record declaration
943 ;; (i.e. a variant part).
944 ((eq 'of token-kind)
945 (setq last-of token))
946
947 ;; Remember any ':' we encounter (until we reach an "of"),
948 ;; since that affects how we indent to case statements in
949 ;; general.
950 ((eq 'colon token-kind)
951 (unless last-of (setq last-colon token)))
952
953 ;; A case statement delimits a previous statement. We indent labels
954 ;; specially.
955 ((eq 'case token-kind)
956 (throw 'done
957 (if last-colon (opascal-line-indent-of last-colon)
958 (opascal-line-indent-of token opascal-case-label-indent))))
959
960 ;; If we are in a use clause then commas mark an enclosing rather than
961 ;; a previous statement.
962 ((opascal-is token-kind opascal-use-clauses)
963 (throw 'done
964 (if (eq 'comma from-kind)
965 (if last-token
966 ;; Indent to first unit in use clause.
967 (opascal-indent-of last-token)
968 ;; Indent from use clause keyword.
969 (opascal-line-indent-of token opascal-indent-level))
970 ;; Indent to use clause keyword.
971 (opascal-line-indent-of token))))
972
973 ;; Assembly sections always indent in from the asm keyword.
974 ((eq token-kind 'asm)
975 (throw 'done (opascal-stmt-line-indent-of token opascal-indent-level)))
976
977 ;; An enclosing statement delimits a previous statement.
978 ;; We try to use the existing indent of the previous statement,
979 ;; otherwise we calculate from the enclosing statement.
980 ((opascal-is token-kind opascal-previous-enclosing-statements)
981 (throw 'done (if last-token
982 ;; Otherwise indent to the last token
983 (opascal-line-indent-of last-token)
984 ;; Just indent from the enclosing keyword
985 (opascal-line-indent-of token opascal-indent-level))))
986
987 ;; A class or record declaration also delimits a previous statement.
988 ((opascal-composite-type-start token last-token)
989 (throw
990 'done
991 (if (opascal-is-simple-class-type last-token from-token)
992 ;; c = class; or c = class of T; are previous statements.
993 (opascal-line-indent-of token)
994 ;; Otherwise c = class ... or r = record ... are enclosing
995 ;; statements.
996 (opascal-line-indent-of last-token opascal-indent-level))))
997
998 ;; We have a definite previous statement delimiter.
999 ((opascal-is token-kind opascal-previous-statements)
1000 (throw 'done (opascal-stmt-line-indent-of token 0)))
1001 )
1002 (unless (opascal-is token-kind opascal-whitespace)
1003 (setq last-token token))
1004 (setq token (opascal-previous-token token)))
1005 ;; We ran out of tokens. Indent to column 0.
1006 0)))
1007
1008 (defun opascal-section-indent-of (section-token)
1009 ;; Returns the indentation appropriate for begin/var/const/type/label
1010 ;; tokens.
1011 (let* ((token (opascal-previous-token section-token))
1012 (token-kind nil)
1013 (last-token nil)
1014 (nested-block-count 0)
1015 (expr-delimited nil)
1016 (last-terminator nil))
1017 (catch 'done
1018 (while token
1019 (setq token-kind (opascal-token-kind token))
1020 (cond
1021 ;; Always stop at unmatched ( or [.
1022 ((eq token-kind 'open-group)
1023 (throw 'done (opascal-open-group-indent token last-token)))
1024
1025 ;; Skip over any ()/[] groups.
1026 ((eq 'close-group token-kind) (setq token (opascal-group-start token)))
1027
1028 ((opascal-is token-kind opascal-end-block-statements)
1029 (if (eq 'newline (opascal-token-kind (opascal-previous-token token)))
1030 ;; We can stop at an end token that is right up against the
1031 ;; margin.
1032 (throw 'done 0)
1033 ;; Otherwise, skip over any nested blocks.
1034 (setq token (opascal-block-start token)
1035 nested-block-count (1+ nested-block-count))))
1036
1037 ;; Remember if we have encountered any forward routine declarations.
1038 ((eq 'forward token-kind)
1039 (setq nested-block-count (1+ nested-block-count)))
1040
1041 ;; Mark the completion of a nested routine traversal.
1042 ((and (opascal-is token-kind opascal-routine-statements)
1043 (> nested-block-count 0))
1044 (setq nested-block-count (1- nested-block-count)))
1045
1046 ;; Remember if we have encountered any statement terminators.
1047 ((eq 'semicolon token-kind) (setq last-terminator token))
1048
1049 ;; Remember if we have encountered any expression delimiters.
1050 ((opascal-is token-kind opascal-expr-delimiters)
1051 (setq expr-delimited token))
1052
1053 ;; Enclosing body statements are delimiting. We indent the compound
1054 ;; bodies specially.
1055 ((and (not last-terminator)
1056 (opascal-is token-kind opascal-body-statements))
1057 (throw 'done
1058 (opascal-stmt-line-indent-of token opascal-compound-block-indent)))
1059
1060 ;; An enclosing ":" means a label.
1061 ((and (eq 'colon token-kind)
1062 (opascal-is (opascal-token-kind section-token)
1063 opascal-block-statements)
1064 (not last-terminator)
1065 (not expr-delimited)
1066 (not (eq 'equals (opascal-token-kind last-token))))
1067 (throw 'done
1068 (opascal-stmt-line-indent-of token opascal-indent-level)))
1069
1070 ;; Block and mid block tokens are always enclosing
1071 ((opascal-is token-kind opascal-begin-enclosing-tokens)
1072 (throw 'done
1073 (opascal-stmt-line-indent-of token opascal-indent-level)))
1074
1075 ;; Declaration sections and routines are delimiters, unless they
1076 ;; are part of a nested routine.
1077 ((and (opascal-is token-kind opascal-decl-delimiters)
1078 (= 0 nested-block-count))
1079 (throw 'done (opascal-line-indent-of token 0)))
1080
1081 ;; Unit statements mean we indent right to the left.
1082 ((opascal-is token-kind opascal-unit-statements) (throw 'done 0))
1083 )
1084 (unless (opascal-is token-kind opascal-whitespace)
1085 (setq last-token token))
1086 (setq token (opascal-previous-token token)))
1087 ;; We ran out of tokens. Indent to column 0.
1088 0)))
1089
1090 (defun opascal-enclosing-indent-of (from-token)
1091 ;; Returns the indentation offset from the enclosing statement of the token.
1092 (let ((token (opascal-previous-token from-token))
1093 (from-kind (opascal-token-kind from-token))
1094 (token-kind nil)
1095 (stmt-start nil)
1096 (last-token nil)
1097 (equals-encountered nil)
1098 (before-equals nil)
1099 (expr-delimited nil))
1100 (catch 'done
1101 (while token
1102 (setq token-kind (opascal-token-kind token))
1103 (cond
1104 ;; An open ( or [ always is an indent point.
1105 ((eq 'open-group token-kind)
1106 (throw 'done
1107 (opascal-open-group-indent
1108 token last-token
1109 (if (opascal-is from-kind opascal-binary-ops)
1110 ;; Keep binary operations aligned with the open group.
1111 0
1112 opascal-indent-level))))
1113
1114 ;; Skip over any ()/[] groups.
1115 ((eq 'close-group token-kind) (setq token (opascal-group-start token)))
1116
1117 ;; Skip over any nested blocks.
1118 ((opascal-is token-kind opascal-end-block-statements)
1119 (setq token (opascal-block-start token)))
1120
1121 ;; An expression delimiter affects indentation depending on whether
1122 ;; the point is before or after it. Remember that we encountered one.
1123 ;; Also remember the last encountered token, since if it exists it
1124 ;; should be the actual indent point.
1125 ((opascal-is token-kind opascal-expr-delimiters)
1126 (setq expr-delimited token stmt-start last-token))
1127
1128 ;; With a non-delimited expression statement we indent after the
1129 ;; statement's keyword, unless we are on the delimiter itself.
1130 ((and (not expr-delimited)
1131 (opascal-is token-kind opascal-expr-statements))
1132 (throw 'done
1133 (cond ((opascal-is from-kind opascal-expr-delimiters)
1134 ;; We are indenting a delimiter. Indent to the statement.
1135 (opascal-stmt-line-indent-of token 0))
1136
1137 ((and last-token (opascal-is from-kind opascal-binary-ops))
1138 ;; Align binary ops with the expression.
1139 (opascal-indent-of last-token))
1140
1141 (last-token
1142 ;; Indent in from the expression.
1143 (opascal-indent-of last-token opascal-indent-level))
1144
1145 ;; Indent in from the statement's keyword.
1146 ((opascal-indent-of token opascal-indent-level)))))
1147
1148 ;; A delimited case statement indents the label according to
1149 ;; a special rule.
1150 ((eq 'case token-kind)
1151 (throw 'done
1152 (if stmt-start
1153 ;; We are not actually indenting to the case statement,
1154 ;; but are within a label expression.
1155 (opascal-stmt-line-indent-of
1156 stmt-start opascal-indent-level)
1157 ;; Indent from the case keyword.
1158 (opascal-stmt-line-indent-of
1159 token opascal-case-label-indent))))
1160
1161 ;; Body expression statements are enclosing. Indent from the
1162 ;; statement's keyword, unless we have a non-block statement following
1163 ;; it.
1164 ((opascal-is token-kind opascal-body-expr-statements)
1165 (throw 'done
1166 (opascal-stmt-line-indent-of
1167 (or stmt-start token) opascal-indent-level)))
1168
1169 ;; An else statement is enclosing, but it doesn't have an expression.
1170 ;; Thus we take into account last-token instead of stmt-start.
1171 ((eq 'else token-kind)
1172 (throw 'done (opascal-stmt-line-indent-of
1173 (or last-token token) opascal-indent-level)))
1174
1175 ;; We indent relative to an enclosing declaration section.
1176 ((opascal-is token-kind opascal-decl-sections)
1177 (throw 'done (opascal-indent-of (if last-token last-token token)
1178 opascal-indent-level)))
1179
1180 ;; In unit sections we indent right to the left.
1181 ((opascal-is token-kind opascal-unit-sections)
1182 (throw 'done
1183 ;; Handle specially the case of "interface", which can be used
1184 ;; to start either a unit section or an interface definition.
1185 (if (opascal-is token-kind opascal-interface-types)
1186 (progn
1187 ;; Find the previous non-whitespace token.
1188 (while (progn
1189 (setq last-token token
1190 token (opascal-previous-token token)
1191 token-kind (opascal-token-kind token))
1192 (and token
1193 (opascal-is token-kind
1194 opascal-whitespace))))
1195 ;; If this token is an equals sign, "interface" is being
1196 ;; used to start an interface definition and we should
1197 ;; treat it as a composite type; otherwise, we should
1198 ;; consider it the start of a unit section.
1199 (if (and token (eq token-kind 'equals))
1200 (opascal-line-indent-of last-token
1201 opascal-indent-level)
1202 0))
1203 0)))
1204
1205 ;; A previous terminator means we can stop.
1206 ((opascal-is token-kind opascal-previous-terminators)
1207 (throw 'done
1208 (cond ((and last-token
1209 (eq 'comma token-kind)
1210 (opascal-is from-kind opascal-binary-ops))
1211 ;; Align binary ops with the expression.
1212 (opascal-indent-of last-token))
1213
1214 (last-token
1215 ;; Indent in from the expression.
1216 (opascal-indent-of last-token opascal-indent-level))
1217
1218 ;; No enclosing expression; use the previous statement's
1219 ;; indent.
1220 ((opascal-previous-indent-of token)))))
1221
1222 ;; A block statement after an expression delimiter has its start
1223 ;; column as the expression statement. E.g.
1224 ;; if (a = b)
1225 ;; and (a != c) then begin
1226 ;; //...
1227 ;; end;
1228 ;; Remember it for when we encounter the expression statement start.
1229 ((opascal-is-block-after-expr-statement token)
1230 (throw 'done
1231 (cond (last-token (opascal-indent-of last-token opascal-indent-level))
1232
1233 ((+ (opascal-section-indent-of token) opascal-indent-level)))))
1234
1235 ;; Assembly sections always indent in from the asm keyword.
1236 ((eq token-kind 'asm)
1237 (throw 'done (opascal-stmt-line-indent-of token opascal-indent-level)))
1238
1239 ;; Stop at an enclosing statement and indent from it.
1240 ((opascal-is token-kind opascal-enclosing-statements)
1241 (throw 'done (opascal-stmt-line-indent-of
1242 (or last-token token) opascal-indent-level)))
1243
1244 ;; A class/record declaration is also enclosing.
1245 ((opascal-composite-type-start token last-token)
1246 (throw 'done
1247 (opascal-line-indent-of last-token opascal-indent-level)))
1248
1249 ;; A ":" we indent relative to its line beginning. If we are in a
1250 ;; parameter list, then stop also if we hit a ";".
1251 ((and (eq token-kind 'colon)
1252 (not expr-delimited)
1253 (not (opascal-is from-kind opascal-expr-delimiters))
1254 (not equals-encountered)
1255 (not (eq from-kind 'equals)))
1256 (throw 'done
1257 (if last-token
1258 (opascal-indent-of last-token opascal-indent-level)
1259 (opascal-line-indent-of token opascal-indent-level 'semicolon))))
1260
1261 ;; If the ":" was not processed above and we have token after the "=",
1262 ;; then indent from the "=". Ignore :=, however.
1263 ((and (eq token-kind 'colon) equals-encountered before-equals)
1264 (cond
1265 ;; Ignore binary ops for now. It would do, for example:
1266 ;; val := 1 + 2
1267 ;; + 3;
1268 ;; which is good, but also
1269 ;; val := Foo
1270 ;; (foo, args)
1271 ;; + 2;
1272 ;; which doesn't look right.
1273 ;;;; Align binary ops with the before token.
1274 ;;((opascal-is from-kind opascal-binary-ops)
1275 ;;(throw 'done (opascal-indent-of before-equals 0)))
1276
1277 ;; Assignments (:=) we skip over to get a normal indent.
1278 ((eq (opascal-token-kind last-token) 'equals))
1279
1280 ;; Otherwise indent in from the equals.
1281 ((throw 'done
1282 (opascal-indent-of before-equals opascal-indent-level)))))
1283
1284 ;; Remember any "=" we encounter if it has not already been processed.
1285 ((eq token-kind 'equals)
1286 (setq equals-encountered token
1287 before-equals last-token))
1288 )
1289 (unless (opascal-is token-kind opascal-whitespace)
1290 (setq last-token token))
1291 (setq token (opascal-previous-token token)))
1292 ;; We ran out of tokens. Indent to column 0.
1293 0)))
1294
1295 (defun opascal-corrected-indentation ()
1296 ;; Returns the corrected indentation for the current line.
1297 (opascal-save-excursion
1298 (opascal-progress-start)
1299 ;; Move to the first token on the line.
1300 (beginning-of-line)
1301 (skip-chars-forward opascal-space-chars)
1302 (let* ((token (opascal-current-token))
1303 (token-kind (opascal-token-kind token))
1304 (indent
1305 (cond ((eq 'close-group token-kind)
1306 ;; Indent to the matching start ( or [.
1307 (opascal-indent-of (opascal-group-start token)))
1308
1309 ((opascal-is token-kind opascal-unit-statements) 0)
1310
1311 ((opascal-is token-kind opascal-comments)
1312 ;; In a comment.
1313 (opascal-comment-indent-of token))
1314
1315 ((opascal-is token-kind opascal-decl-matchers)
1316 ;; Use a previous section/routine's indent.
1317 (opascal-section-indent-of token))
1318
1319 ((opascal-is token-kind opascal-match-block-statements)
1320 ;; Use the block's indentation.
1321 (let ((block-start
1322 (opascal-block-start token 'stop-on-class)))
1323 (cond
1324 ;; When trailing a body statement, indent to
1325 ;; the statement's keyword.
1326 ((opascal-is-block-after-expr-statement block-start)
1327 (opascal-section-indent-of block-start))
1328
1329 ;; Otherwise just indent to the block start.
1330 ((opascal-stmt-line-indent-of block-start 0)))))
1331
1332 ((eq 'else token-kind)
1333 ;; Find the start of the if or case statement.
1334 (opascal-stmt-line-indent-of (opascal-else-start token) 0))
1335
1336 ;; Otherwise indent in from enclosing statement.
1337 ((opascal-enclosing-indent-of
1338 (if token token (opascal-token-at (1- (point)))))))))
1339 (opascal-progress-done)
1340 indent)))
1341
1342 (defun opascal-indent-line ()
1343 "Indent the current line according to the current language construct.
1344 If before the indent, the point is moved to the indent."
1345 (interactive)
1346 (save-match-data
1347 (let ((marked-point (point-marker)) ; Maintain our position reliably.
1348 (line-start nil)
1349 (old-indent 0)
1350 (new-indent 0))
1351 (beginning-of-line)
1352 (setq line-start (point))
1353 (skip-chars-forward opascal-space-chars)
1354 (setq old-indent (current-column))
1355 (setq new-indent (opascal-corrected-indentation))
1356 (if (< marked-point (point))
1357 ;; If before the indent column, then move to it.
1358 (set-marker marked-point (point)))
1359 ;; Advance our marked point after inserted spaces.
1360 (set-marker-insertion-type marked-point t)
1361 (when (/= old-indent new-indent)
1362 (delete-region line-start (point))
1363 (insert (make-string new-indent ?\s)))
1364 (goto-char marked-point)
1365 (set-marker marked-point nil))))
1366
1367 (defvar opascal-mode-abbrev-table nil
1368 "Abbrev table in use in OPascal mode buffers.")
1369 (define-abbrev-table 'opascal-mode-abbrev-table ())
1370
1371 (defmacro opascal-ensure-buffer (buffer-var buffer-name)
1372 ;; Ensures there exists a buffer of the specified name in the specified
1373 ;; variable.
1374 `(when (not (buffer-live-p ,buffer-var))
1375 (setq ,buffer-var (get-buffer-create ,buffer-name))))
1376
1377 (defun opascal-log-msg (to-buffer the-msg)
1378 ;; Writes a message to the end of the specified buffer.
1379 (with-current-buffer to-buffer
1380 (save-selected-window
1381 (switch-to-buffer-other-window to-buffer)
1382 (goto-char (point-max))
1383 (set-window-point (get-buffer-window to-buffer) (point))
1384 (insert the-msg))))
1385
1386 ;; Debugging helpers:
1387
1388 (defvar opascal-debug-buffer nil
1389 "Buffer to write OPascal mode debug messages to. Created on demand.")
1390
1391 (defun opascal-debug-log (format-string &rest args)
1392 ;; Writes a message to the log buffer.
1393 (when opascal-debug
1394 (opascal-ensure-buffer opascal-debug-buffer "*OPascal Debug Log*")
1395 (opascal-log-msg opascal-debug-buffer
1396 (concat (format-time-string "%H:%M:%S " (current-time))
1397 (apply #'format (cons format-string args))
1398 "\n"))))
1399
1400 (defun opascal-debug-token-string (token)
1401 (let* ((image (opascal-token-string token))
1402 (has-newline (string-match "^\\([^\n]*\\)\n\\(.+\\)?$" image)))
1403 (when has-newline
1404 (setq image (concat (match-string 1 image)
1405 (if (match-beginning 2) "..."))))
1406 image))
1407
1408 (defun opascal-debug-show-current-token ()
1409 (interactive)
1410 (let ((token (opascal-current-token)))
1411 (opascal-debug-log "Token: %S %S" token (opascal-debug-token-string token))))
1412
1413 (defun opascal-debug-goto-point (p)
1414 (interactive "NGoto char: ")
1415 (goto-char p))
1416
1417 (defun opascal-debug-goto-next-token ()
1418 (interactive)
1419 (goto-char (opascal-token-start (opascal-next-token (opascal-current-token)))))
1420
1421 (defun opascal-debug-goto-previous-token ()
1422 (interactive)
1423 (goto-char
1424 (opascal-token-start (opascal-previous-token (opascal-current-token)))))
1425
1426 (defun opascal-debug-show-current-string (from to)
1427 (interactive "r")
1428 (opascal-debug-log "String: %S" (buffer-substring from to)))
1429
1430 (defun opascal-debug-tokenize-region (from to)
1431 (interactive)
1432 (opascal-save-excursion
1433 (opascal-progress-start)
1434 (goto-char from)
1435 (while (< (point) to)
1436 (goto-char (opascal-token-end (opascal-current-token)))
1437 (opascal-step-progress (point) "Tokenizing" opascal-scanning-progress-step))
1438 (opascal-progress-done "Tokenizing done")))
1439
1440 (defun opascal-debug-tokenize-buffer ()
1441 (interactive)
1442 (opascal-debug-tokenize-region (point-min) (point-max)))
1443
1444 (defun opascal-debug-tokenize-window ()
1445 (interactive)
1446 (opascal-debug-tokenize-region (window-start) (window-end)))
1447
1448
1449 (defun opascal-tab ()
1450 "Indent the region, when Transient Mark mode is enabled and the region is
1451 active. Otherwise, indent the current line or insert a TAB, depending on the
1452 value of `opascal-tab-always-indents' and the current line position."
1453 (interactive)
1454 (cond ((use-region-p)
1455 ;; If Transient Mark mode is enabled and the region is active, indent
1456 ;; the entire region.
1457 (indent-region (region-beginning) (region-end)))
1458 ((or opascal-tab-always-indents
1459 (save-excursion (skip-chars-backward opascal-space-chars) (bolp)))
1460 ;; Otherwise, if we are configured always to indent (regardless of the
1461 ;; point's position in the line) or we are before the first non-space
1462 ;; character on the line, indent the line.
1463 (opascal-indent-line))
1464 (t
1465 ;; Otherwise, insert a tab character.
1466 (insert "\t"))))
1467
1468
1469 (defun opascal-is-directory (path)
1470 ;; True if the specified path is an existing directory.
1471 (let ((attributes (file-attributes path)))
1472 (and attributes (car attributes))))
1473
1474 (defun opascal-is-file (path)
1475 ;; True if the specified file exists as a file.
1476 (let ((attributes (file-attributes path)))
1477 (and attributes (null (car attributes)))))
1478
1479 (defun opascal-search-directory (unit dir &optional recurse)
1480 ;; Searches for the unit in the specified directory. If recurse is true, then
1481 ;; the directory is recursively searched. File name comparison is done in a
1482 ;; case insensitive manner.
1483 (when (opascal-is-directory dir)
1484 (let ((files (directory-files dir))
1485 (unit-file (downcase unit)))
1486 (catch 'done
1487 ;; Search for the file.
1488 (dolist (file files)
1489 (let ((path (concat dir "/" file)))
1490 (if (and (string= unit-file (downcase file))
1491 (opascal-is-file path))
1492 (throw 'done path))))
1493
1494 ;; Not found. Search subdirectories.
1495 (when recurse
1496 (dolist (subdir files)
1497 (unless (member subdir '("." ".."))
1498 (let ((path (opascal-search-directory
1499 unit (concat dir "/" subdir) recurse)))
1500 (if path (throw 'done path))))))
1501
1502 ;; Not found.
1503 nil))))
1504
1505
1506 (defun opascal-find-unit-in-directory (unit dir)
1507 ;; Searches for the unit in the specified directory. If the directory ends
1508 ;; in \"...\", then it is recursively searched.
1509 (let ((dir-name dir)
1510 (recurse nil))
1511 ;; Check if we need to recursively search the directory.
1512 (if (string-match "^\\(.+\\)\\.\\.\\.$" dir-name)
1513 (setq dir-name (match-string 1 dir-name)
1514 recurse t))
1515 ;; Ensure the trailing slash is removed.
1516 (if (string-match "^\\(.+\\)[\\\\/]$" dir-name)
1517 (setq dir-name (match-string 1 dir-name)))
1518 (opascal-search-directory unit dir-name recurse)))
1519
1520 (defun opascal-find-unit-file (unit)
1521 ;; Finds the specified opascal source file according to `opascal-search-path'.
1522 ;; If found, the full path is returned, otherwise nil is returned.
1523 (catch 'done
1524 (cond ((null opascal-search-path)
1525 (opascal-find-unit-in-directory unit "."))
1526
1527 ((stringp opascal-search-path)
1528 (opascal-find-unit-in-directory unit opascal-search-path))
1529
1530 ((dolist (dir opascal-search-path)
1531 (let ((file (opascal-find-unit-in-directory unit dir)))
1532 (if file (throw 'done file))))))
1533 nil))
1534
1535 (defun opascal-find-unit (unit)
1536 "Find the specified OPascal source file according to `opascal-search-path'.
1537 If no extension is specified, .pas is assumed. Creates a buffer for the unit."
1538 (interactive "sOPascal unit name: ")
1539 (let* ((unit-file (if (string-match "^\\(.*\\)\\.[a-z]+$" unit)
1540 unit
1541 (concat unit ".pas")))
1542 (file (opascal-find-unit-file unit-file)))
1543 (if (null file)
1544 (error "unit not found: %s" unit-file)
1545 (find-file file)
1546 (if (not (derived-mode-p 'opascal-mode))
1547 (opascal-mode)))
1548 file))
1549
1550 (defun opascal-find-current-def ()
1551 "Find the definition of the identifier under the current point."
1552 (interactive)
1553 (error "opascal-find-current-def: not implemented yet"))
1554
1555 (defun opascal-find-current-xdef ()
1556 "Find the definition of the identifier under the current point, searching
1557 in external units if necessary (as listed in the current unit's use clause).
1558 The set of directories to search for a unit is specified by the global variable
1559 `opascal-search-path'."
1560 (interactive)
1561 (error "opascal-find-current-xdef: not implemented yet"))
1562
1563 (defun opascal-find-current-body ()
1564 "Find the body of the identifier under the current point, assuming
1565 it is a routine."
1566 (interactive)
1567 (error "opascal-find-current-body: not implemented yet"))
1568
1569 (defun opascal-fill-comment ()
1570 "Fill the text of the current comment, according to `fill-column'.
1571 An error is raised if not in a comment."
1572 (interactive)
1573 (save-excursion
1574 (save-restriction
1575 (let* ((comment (opascal-current-token))
1576 (comment-kind (opascal-token-kind comment)))
1577 (if (not (opascal-is comment-kind opascal-comments))
1578 (error "Not in a comment")
1579 (let* ((start-comment (opascal-comment-block-start comment))
1580 (end-comment (opascal-comment-block-end comment))
1581 ;; FIXME: Don't abuse global variables like `comment-end/start'.
1582 (comment-start (opascal-token-start start-comment))
1583 (comment-end (opascal-token-end end-comment))
1584 (content-start (opascal-comment-content-start start-comment))
1585 (content-indent (opascal-column-of content-start))
1586 (content-prefix (make-string content-indent ?\s))
1587 (content-prefix-re opascal-leading-spaces-re)
1588 (p nil)
1589 (marked-point (point-marker))) ; Maintain our position reliably.
1590 (when (eq 'comment-single-line comment-kind)
1591 ;; // style comments need more work.
1592 (setq content-prefix
1593 (let ((comment-indent (opascal-column-of comment-start)))
1594 (concat (make-string comment-indent ?\s) "//"
1595 (make-string (- content-indent comment-indent 2)
1596 ?\s)))
1597 content-prefix-re (concat opascal-leading-spaces-re
1598 "//"
1599 opascal-spaces-re)
1600 comment-end (if (opascal-is-literal-end comment-end)
1601 ;; Don't include the trailing newline.
1602 (1- comment-end)
1603 comment-end)))
1604
1605 ;; Advance our marked point after inserted spaces.
1606 (set-marker-insertion-type marked-point t)
1607
1608 ;; Ensure we can modify the buffer
1609 (goto-char content-start)
1610 (insert " ")
1611 (delete-char -1)
1612
1613 (narrow-to-region content-start comment-end)
1614
1615 ;; Strip off the comment prefixes
1616 (setq p (point-min))
1617 (while (when (< p (point-max))
1618 (goto-char p)
1619 (re-search-forward content-prefix-re nil t))
1620 (replace-match "" nil nil)
1621 (setq p (1+ (point))))
1622
1623 ;; add an extra line to prevent the fill from doing it for us.
1624 (goto-char (point-max))
1625 (insert "\n")
1626
1627 ;; Fill the comment contents.
1628 (let ((fill-column (- fill-column content-indent)))
1629 (fill-region (point-min) (point-max)))
1630
1631 (goto-char (point-max))
1632 (delete-char -1)
1633
1634 ;; Restore comment prefixes.
1635 (goto-char (point-min))
1636 (end-of-line) ; Don't reset the first line.
1637 (setq p (point))
1638 (while (when (< p (point-max))
1639 (goto-char p)
1640 (re-search-forward "^" nil t))
1641 (replace-match content-prefix nil nil)
1642 (setq p (1+ (point))))
1643
1644 (setq comment-end (point-max))
1645 (widen)
1646
1647 ;; Restore our position
1648 (goto-char marked-point)
1649 (set-marker marked-point nil)))))))
1650
1651 (defun opascal-new-comment-line ()
1652 "If in a // comment, do a newline, indented such that one is still in the
1653 comment block. If not in a // comment, just does a normal newline."
1654 (interactive)
1655 (let ((comment (opascal-current-token)))
1656 (if (not (eq 'comment-single-line (opascal-token-kind comment)))
1657 ;; Not in a // comment. Just do the normal newline.
1658 (newline)
1659 (let* ((start-comment (opascal-comment-block-start comment))
1660 (comment-start (opascal-token-start start-comment))
1661 (content-start (opascal-comment-content-start start-comment))
1662 (prefix
1663 (concat (make-string (opascal-column-of comment-start) ?\s) "//"
1664 (make-string (- content-start comment-start 2) ?\s))))
1665 (delete-horizontal-space)
1666 (insert "\n" prefix)))))
1667
1668 (defun opascal-match-token (token limit)
1669 ;; Sets the match region used by (match-string 0) and friends to the token's
1670 ;; region. Sets the current point to the end of the token (or limit).
1671 (set-match-data nil)
1672 (if token
1673 (let ((end (min (opascal-token-end token) limit)))
1674 (set-match-data (list (opascal-token-start token) end))
1675 (goto-char end)
1676 token)))
1677
1678 (defconst opascal-font-lock-keywords
1679 `(("\\_<\\(function\\|pro\\(cedure\\|gram\\)\\)[ \t]+\\([[:alpha:]][[:alnum:]_]*\\)"
1680 (1 font-lock-keyword-face) (3 font-lock-function-name-face))
1681 ,(concat "\\_<" (regexp-opt (mapcar #'symbol-name opascal-keywords))
1682 "\\_>")))
1683
1684 (defconst opascal-font-lock-defaults
1685 '(opascal-font-lock-keywords
1686 nil ; Syntactic fontification does apply.
1687 nil ; Don't care about case since we don't use regexps to find tokens.
1688 nil ; Syntax alists don't apply.
1689 nil ; Syntax begin movement doesn't apply.
1690 )
1691 "OPascal mode font-lock defaults. Syntactic fontification is ignored.")
1692
1693 (defconst opascal--syntax-propertize
1694 (syntax-propertize-rules
1695 ;; The syntax-table settings are too coarse and end up treating /* and (/
1696 ;; as comment starters. Fix it here by removing the "2" from the syntax
1697 ;; of the second char of such sequences.
1698 ("/\\(\\*\\)" (1 ". 3b"))
1699 ("(\\(\\/\\)" (1 (prog1 ". 1c" (forward-char -1) nil)))
1700 ;; Pascal uses '' and "" rather than \' and \" to escape quotes.
1701 ("''\\|\"\"" (0 (if (save-excursion
1702 (nth 3 (syntax-ppss (match-beginning 0))))
1703 (string-to-syntax ".")
1704 ;; In case of 3 or more quotes in a row, only advance
1705 ;; one quote at a time.
1706 (forward-char -1)
1707 nil)))))
1708
1709 (defvar opascal-debug-mode-map
1710 (let ((kmap (make-sparse-keymap)))
1711 (dolist (binding '(("n" opascal-debug-goto-next-token)
1712 ("p" opascal-debug-goto-previous-token)
1713 ("t" opascal-debug-show-current-token)
1714 ("T" opascal-debug-tokenize-buffer)
1715 ("W" opascal-debug-tokenize-window)
1716 ("g" opascal-debug-goto-point)
1717 ("s" opascal-debug-show-current-string)))
1718 (define-key kmap (car binding) (cadr binding)))
1719 kmap)
1720 "Keystrokes for OPascal mode debug commands.")
1721
1722 (defvar opascal-mode-map
1723 (let ((kmap (make-sparse-keymap)))
1724 (dolist (binding
1725 (list ;; '("\C-cd" opascal-find-current-def)
1726 ;; '("\C-cx" opascal-find-current-xdef)
1727 ;; '("\C-cb" opascal-find-current-body)
1728 '("\C-cu" opascal-find-unit)
1729 '("\M-q" opascal-fill-comment)
1730 '("\M-j" opascal-new-comment-line)
1731 ;; Debug bindings:
1732 (list "\C-c\C-d" opascal-debug-mode-map)))
1733 (define-key kmap (car binding) (cadr binding)))
1734 kmap)
1735 "Keymap used in OPascal mode.")
1736
1737 (define-obsolete-variable-alias 'delphi-mode-hook 'opascal-mode-hook "24.4")
1738 ;;;###autoload
1739 (define-obsolete-function-alias 'delphi-mode 'opascal-mode "24.4")
1740 ;;;###autoload
1741 (define-derived-mode opascal-mode prog-mode "OPascal"
1742 "Major mode for editing OPascal code. \\<opascal-mode-map>
1743 \\[opascal-find-unit]\t- Search for a OPascal source file.
1744 \\[opascal-fill-comment]\t- Fill the current comment.
1745 \\[opascal-new-comment-line]\t- If in a // comment, do a new comment line.
1746
1747 \\[indent-region] also works for indenting a whole region.
1748
1749 Customization:
1750
1751 `opascal-indent-level' (default 3)
1752 Indentation of OPascal statements with respect to containing block.
1753 `opascal-compound-block-indent' (default 0)
1754 Extra indentation for blocks in compound statements.
1755 `opascal-case-label-indent' (default 0)
1756 Extra indentation for case statement labels.
1757 `opascal-tab-always-indents' (default `tab-always-indents')
1758 Non-nil means TAB in OPascal mode should always reindent the current line,
1759 regardless of where in the line point is when the TAB command is used.
1760 `opascal-search-path' (default .)
1761 Directories to search when finding external units.
1762 `opascal-verbose' (default nil)
1763 If true then OPascal token processing progress is reported to the user.
1764
1765 Coloring:
1766
1767 `opascal-keyword-face' (default font-lock-keyword-face)
1768 Face used to color OPascal keywords.
1769
1770 Turning on OPascal mode calls the value of the variable `opascal-mode-hook'
1771 with no args, if that value is non-nil."
1772
1773 ;; Buffer locals:
1774 (setq-local indent-line-function #'opascal-indent-line)
1775 (setq-local comment-indent-function #'opascal-indent-line)
1776 (setq-local case-fold-search t)
1777 (setq-local opascal-progress-last-reported-point nil)
1778 (setq-local font-lock-defaults opascal-font-lock-defaults)
1779 (setq-local tab-always-indent opascal-tab-always-indents)
1780 (setq-local syntax-propertize-function opascal--syntax-propertize)
1781
1782 (setq-local comment-start "// ")
1783 (setq-local comment-start-skip "\\(?://\\|(\\*\\|{\\)[ \t]*")
1784 (setq-local comment-end-skip "[ \t]*\\(?:\n\\|\\*)\\|}\\)"))
1785
1786 (provide 'opascal)
1787 ;;; opascal.el ends here