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