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