]> code.delx.au - gnu-emacs/blob - lisp/align.el
; Merge from origin/emacs-25
[gnu-emacs] / lisp / align.el
1 ;;; align.el --- align text to a specific column, by regexp -*- lexical-binding:t -*-
2
3 ;; Copyright (C) 1999-2016 Free Software Foundation, Inc.
4
5 ;; Author: John Wiegley <johnw@gnu.org>
6 ;; Maintainer: emacs-devel@gnu.org
7 ;; Keywords: convenience languages lisp
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23
24 ;;; Commentary:
25
26 ;; This mode allows you to align regions in a context-sensitive fashion.
27 ;; The classic use is to align assignments:
28 ;;
29 ;; int a = 1;
30 ;; short foo = 2;
31 ;; double blah = 4;
32 ;;
33 ;; becomes
34 ;;
35 ;; int a = 1;
36 ;; short foo = 2;
37 ;; double blah = 4;
38
39 ;;; Usage:
40
41 ;; There are several variables which define how certain "categories"
42 ;; of syntax are to be treated. These variables go by the name
43 ;; `align-CATEGORY-modes'. For example, "c++" is such a category.
44 ;; There are several rules which apply to c++, but since several other
45 ;; languages have a syntax similar to c++ (e.g., c, java, etc), these
46 ;; modes are treated as belonging to the same category.
47 ;;
48 ;; If you want to add a new mode under a certain category, just
49 ;; customize that list, or add the new mode manually. For example, to
50 ;; make jde-mode a c++ category mode, use this code in your .emacs
51 ;; file:
52 ;;
53 ;; (setq align-c++-modes (cons 'jde-mode align-c++-modes))
54
55 ;; In some programming modes, it's useful to have the aligner run only
56 ;; after indentation is performed. To achieve this, customize or set
57 ;; the variable `align-indent-before-aligning' to t.
58
59 ;;; Module Authors:
60
61 ;; In order to incorporate align's functionality into your own
62 ;; modules, there are only a few steps you have to follow.
63
64 ;; 1. Require or load in the align.el library.
65 ;;
66 ;; 2. Define your alignment and exclusion rules lists, either
67 ;; customizable or not.
68 ;;
69 ;; 3. In your mode function, set the variables
70 ;; `align-mode-rules-list' and `align-mode-exclude-rules-list'
71 ;; to your own rules lists.
72
73 ;; If there is any need to add your mode name to one of the
74 ;; align-?-modes variables (for example, `align-dq-string-modes'), use
75 ;; `add-to-list', or some similar function which checks first to see
76 ;; if the value is already there. Since the user may customize that
77 ;; mode list, and then write your mode name into their init file,
78 ;; causing the symbol already to be present the next time they load
79 ;; your package.
80
81 ;; Example:
82 ;;
83 ;; (require 'align)
84 ;;
85 ;; (defcustom my-align-rules-list
86 ;; '((my-rule
87 ;; (regexp . "Sample")))
88 ;; :type align-rules-list-type
89 ;; :group 'my-package)
90 ;;
91 ;; (put 'my-align-rules-list 'risky-local-variable t)
92 ;;
93 ;; (add-to-list 'align-dq-string-modes 'my-package-mode)
94 ;; (add-to-list 'align-open-comment-modes 'my-package-mode)
95 ;;
96 ;; (defun my-mode ()
97 ;; ...
98 ;; (setq align-mode-rules-list my-align-rules-list))
99 ;;
100 ;; Note that if you need to install your own exclusion rules, then you
101 ;; will also need to reproduce any double-quoted string, or open
102 ;; comment exclusion rules that are defined in the standard
103 ;; `align-exclude-rules-list'. At the moment there is no convenient
104 ;; way to mix both mode-local and global rules lists.
105
106 ;;; History:
107
108 ;; Version 1.0 was created in the earlier part of 1996, using a very
109 ;; simple algorithm that understand only basic regular expressions.
110 ;; Parts of the code were broken up and included in vhdl-mode.el
111 ;; around this time. After several comments from users, and a need to
112 ;; find a more robust, higher performing algorithm, 2.0 was born in late
113 ;; 1998. Many different approaches were taken (mostly due to the
114 ;; complexity of TeX tables), but finally a scheme was discovered
115 ;; which worked fairly well for most common usage cases. Development
116 ;; beyond version 2.8 is not planned, except for problems that users
117 ;; might encounter.
118
119 ;;; Code:
120
121 (defgroup align nil
122 "Align text to a specific column, by regexp."
123 :version "21.1"
124 :group 'fill)
125
126 ;;; User Variables:
127
128 (defcustom align-load-hook nil
129 "Hook that gets run after the aligner has been loaded."
130 :type 'hook
131 :group 'align)
132
133 (defcustom align-indent-before-aligning nil
134 "If non-nil, indent the marked region before aligning it."
135 :type 'boolean
136 :group 'align)
137
138 (defcustom align-default-spacing 1
139 "An integer that represents the default amount of padding to use.
140 If `align-to-tab-stop' is non-nil, this will represent the number of
141 tab stops to use for alignment, rather than the number of spaces.
142 Each alignment rule can optionally override both this variable and
143 `align-to-tab-stop'. See `align-rules-list'."
144 :type 'integer
145 :group 'align)
146
147 (defcustom align-to-tab-stop 'indent-tabs-mode
148 "If non-nil, alignments will always fall on a tab boundary.
149 It may also be a symbol, whose value will be taken."
150 :type '(choice (const nil) symbol)
151 :group 'align)
152
153 (defcustom align-region-heuristic 500
154 "If non-nil, used as a heuristic by `align-current'.
155 Since each alignment rule can possibly have its own set of alignment
156 sections (whenever `align-region-separate' is non-nil, and not a
157 string), this heuristic is used to determine how far before and after
158 point we should search in looking for a region separator. Larger
159 values can mean slower performance in large files, although smaller
160 values may cause unexpected behavior at times."
161 :type 'integer
162 :group 'align)
163
164 (defcustom align-highlight-change-face 'highlight
165 "The face to highlight with if changes are necessary."
166 :type 'face
167 :group 'align)
168
169 (defcustom align-highlight-nochange-face 'secondary-selection
170 "The face to highlight with if no changes are necessary."
171 :type 'face
172 :group 'align)
173
174 (defcustom align-large-region 10000
175 "If an integer, defines what constitutes a \"large\" region.
176 If nil, then no messages will ever be printed to the minibuffer."
177 :type 'integer
178 :group 'align)
179
180 (defcustom align-c++-modes '(c++-mode c-mode java-mode)
181 "A list of modes whose syntax resembles C/C++."
182 :type '(repeat symbol)
183 :group 'align)
184
185 (defcustom align-perl-modes '(perl-mode cperl-mode)
186 "A list of modes where Perl syntax is to be seen."
187 :type '(repeat symbol)
188 :group 'align)
189
190 (defcustom align-lisp-modes
191 '(emacs-lisp-mode lisp-interaction-mode lisp-mode scheme-mode)
192 "A list of modes whose syntax resembles Lisp."
193 :type '(repeat symbol)
194 :group 'align)
195
196 (defcustom align-tex-modes
197 '(tex-mode plain-tex-mode latex-mode slitex-mode)
198 "A list of modes whose syntax resembles TeX (and family)."
199 :type '(repeat symbol)
200 :group 'align)
201
202 (defcustom align-text-modes '(text-mode outline-mode)
203 "A list of modes whose content is plain text."
204 :type '(repeat symbol)
205 :group 'align)
206
207 (defcustom align-dq-string-modes
208 (append align-lisp-modes align-c++-modes align-perl-modes
209 '(python-mode))
210 "A list of modes where double quoted strings should be excluded."
211 :type '(repeat symbol)
212 :group 'align)
213
214 (defcustom align-sq-string-modes
215 (append align-perl-modes '(python-mode))
216 "A list of modes where single quoted strings should be excluded."
217 :type '(repeat symbol)
218 :group 'align)
219
220 (defcustom align-open-comment-modes
221 (append align-lisp-modes align-c++-modes align-perl-modes
222 '(python-mode makefile-mode))
223 "A list of modes with a single-line comment syntax.
224 These are comments as in Lisp, which have a beginning, but end with
225 the line (i.e., `comment-end' is an empty string)."
226 :type '(repeat symbol)
227 :group 'align)
228
229 (defcustom align-region-separate "^\\s-*[{}]?\\s-*$"
230 "Select the method by which alignment sections will be separated.
231 If this is a symbol, that symbol's value will be used.
232
233 For the sake of clarification, consider the following example, which
234 will be referred to in the descriptions below.
235
236 int alpha = 1; /* one */
237 double beta = 2.0;
238 long gamma; /* ten */
239
240 unsigned int delta = 1; /* one */
241 long double epsilon = 3.0;
242 long long omega; /* ten */
243
244 The possible settings for `align-region-separate' are:
245
246 `entire' The entire region being aligned will be considered as a
247 single alignment section. Assuming that comments were not
248 being aligned to a particular column, the example would
249 become:
250
251 int alpha = 1; /* one */
252 double beta = 2.0;
253 long gamma; /* ten */
254
255 unsigned int delta = 1; /* one */
256 long double epsilon;
257 long long chi = 10; /* ten */
258
259 `group' Each contiguous set of lines where a specific alignment
260 occurs is considered a section for that alignment rule.
261 Note that each rule may have any entirely different set
262 of section divisions than another.
263
264 int alpha = 1; /* one */
265 double beta = 2.0;
266 long gamma; /* ten */
267
268 unsigned int delta = 1; /* one */
269 long double epsilon;
270 long long chi = 10; /* ten */
271
272 `largest' When contiguous rule sets overlap, the largest section
273 described will be taken as the alignment section for each
274 rule touched by that section.
275
276 int alpha = 1; /* one */
277 double beta = 2.0;
278 long gamma; /* ten */
279
280 unsigned int delta = 1; /* one */
281 long double epsilon;
282 long long chi = 10; /* ten */
283
284 NOTE: This option is not supported yet, due to algorithmic
285 issues which haven't been satisfactorily resolved. There
286 are ways to do it, but they're both ugly and resource
287 consumptive.
288
289 regexp A regular expression string which defines the section
290 divider. If the mode you're in has a consistent divider
291 between sections, the behavior will be very similar to
292 `largest', and faster. But if the mode does not use clear
293 separators (for example, if you collapse your braces onto
294 the preceding statement in C or Perl), `largest' is
295 probably the better alternative.
296
297 function A function that will be passed the beginning and ending
298 locations of the region in which to look for the section
299 separator. At the very beginning of the attempt to align,
300 both of these parameters will be nil, in which case the
301 function should return non-nil if it wants each rule to
302 define its own section, or nil if it wants the largest
303 section found to be used as the common section for all
304 rules that occur there.
305
306 list A list of markers within the buffer that represent where
307 the section dividers lie. Be certain to use markers! For
308 when the aligning begins, the ensuing contract/expanding of
309 whitespace will throw off any non-marker positions.
310
311 This method is intended for use in Lisp programs, and not
312 by the user."
313 :type '(choice
314 (const :tag "Entire region is one section" entire)
315 (const :tag "Align by contiguous groups" group)
316 ; (const largest)
317 (regexp :tag "Regexp defines section boundaries")
318 (function :tag "Function defines section boundaries"))
319 :group 'align)
320
321 (put 'align-region-separate 'risky-local-variable t)
322
323 (defvar align-rules-list-type
324 '(repeat
325 (cons
326 :tag "Alignment rule"
327 (symbol :tag "Title")
328 (cons :tag "Required attributes"
329 (cons :tag "Regexp"
330 (const :tag "(Regular expression to match)" regexp)
331 (choice :value "\\(\\s-+\\)" regexp function))
332 (repeat
333 :tag "Optional attributes"
334 (choice
335 (cons :tag "Repeat"
336 (const :tag "(Repeat this rule throughout line)"
337 repeat)
338 (boolean :value t))
339 (cons :tag "Paren group"
340 (const :tag "(Parenthesis group to use)" group)
341 (choice :value 2
342 integer (repeat integer)))
343 (cons :tag "Modes"
344 (const :tag "(Modes where this rule applies)" modes)
345 (sexp :value (text-mode)))
346 (cons :tag "Case-fold"
347 (const :tag "(Should case be ignored for this rule)"
348 case-fold)
349 (boolean :value t))
350 (cons :tag "To Tab Stop"
351 (const :tag "(Should rule align to tab stops)"
352 tab-stop)
353 (boolean :value nil))
354 (cons :tag "Valid"
355 (const :tag "(Return non-nil if rule is valid)"
356 valid)
357 (function :value t))
358 (cons :tag "Run If"
359 (const :tag "(Return non-nil if rule should run)"
360 run-if)
361 (function :value t))
362 (cons :tag "Column"
363 (const :tag "(Column to fix alignment at)" column)
364 (choice :value comment-column
365 integer symbol))
366 (cons :tag "Spacing"
367 (const :tag "(Amount of spacing to use)" spacing)
368 (integer :value 1))
369 (cons :tag "Justify"
370 (const :tag "(Should text be right justified)"
371 justify)
372 (boolean :value t))
373 ;; make sure this stays up-to-date with any changes
374 ;; in `align-region-separate'
375 (cons :tag "Separate"
376 (const :tag "(Separation to use for this rule)"
377 separate)
378 (choice :value "^\\s-*$"
379 (const entire)
380 (const group)
381 ; (const largest)
382 regexp function)))))))
383 "The `type' form for any `align-rules-list' variable.")
384
385 (defcustom align-rules-list
386 `((lisp-second-arg
387 (regexp . "\\(^\\s-+[^( \t\n]\\|(\\(\\S-+\\)\\s-+\\)\\S-+\\(\\s-+\\)")
388 (group . 3)
389 (modes . align-lisp-modes)
390 (run-if . ,(function (lambda () current-prefix-arg))))
391
392 (lisp-alist-dot
393 (regexp . "\\(\\s-*\\)\\.\\(\\s-*\\)")
394 (group . (1 2))
395 (modes . align-lisp-modes))
396
397 (open-comment
398 (regexp . ,(function
399 (lambda (end reverse)
400 (funcall (if reverse 're-search-backward
401 're-search-forward)
402 (concat "[^ \t\n\\\\]"
403 (regexp-quote comment-start)
404 "\\(.+\\)$") end t))))
405 (modes . align-open-comment-modes))
406
407 (c-macro-definition
408 (regexp . "^\\s-*#\\s-*define\\s-+\\S-+\\(\\s-+\\)")
409 (modes . align-c++-modes))
410
411 (c-variable-declaration
412 (regexp . ,(concat "[*&0-9A-Za-z_]>?[&*]*\\(\\s-+[*&]*\\)"
413 "[A-Za-z_][0-9A-Za-z:_]*\\s-*\\(\\()\\|"
414 "=[^=\n].*\\|(.*)\\|\\(\\[.*\\]\\)*\\)?"
415 "\\s-*[;,]\\|)\\s-*$\\)"))
416 (group . 1)
417 (modes . align-c++-modes)
418 (justify . t)
419 (valid
420 . ,(function
421 (lambda ()
422 (not (or (save-excursion
423 (goto-char (match-beginning 1))
424 (backward-word 1)
425 (looking-at
426 "\\(goto\\|return\\|new\\|delete\\|throw\\)"))
427 (if (and (boundp 'font-lock-mode) font-lock-mode)
428 (eq (get-text-property (point) 'face)
429 'font-lock-comment-face)
430 (eq (caar (c-guess-basic-syntax)) 'c))))))))
431
432 (c-assignment
433 (regexp . ,(concat "[^-=!^&*+<>/| \t\n]\\(\\s-*[-=!^&*+<>/|]*\\)"
434 "=\\(\\s-*\\)\\([^= \t\n]\\|$\\)"))
435 (group . (1 2))
436 (modes . align-c++-modes)
437 (justify . t)
438 (tab-stop . nil))
439
440 (perl-assignment
441 (regexp . ,(concat "[^=!^&*-+<>/| \t\n]\\(\\s-*\\)=[~>]?"
442 "\\(\\s-*\\)\\([^>= \t\n]\\|$\\)"))
443 (group . (1 2))
444 (modes . align-perl-modes)
445 (tab-stop . nil))
446
447 (python-assignment
448 (regexp . ,(concat "[^=!<> \t\n]\\(\\s-*\\)="
449 "\\(\\s-*\\)\\([^>= \t\n]\\|$\\)"))
450 (group . (1 2))
451 (modes . '(python-mode))
452 (tab-stop . nil))
453
454 (make-assignment
455 (regexp . "^\\s-*\\w+\\(\\s-*\\):?=\\(\\s-*\\)\\([^\t\n \\\\]\\|$\\)")
456 (group . (1 2))
457 (modes . '(makefile-mode))
458 (tab-stop . nil))
459
460 (c-comma-delimiter
461 (regexp . ",\\(\\s-*\\)[^/ \t\n]")
462 (repeat . t)
463 (modes . align-c++-modes)
464 (run-if . ,(function (lambda () current-prefix-arg))))
465 ; (valid
466 ; . ,(function
467 ; (lambda ()
468 ; (memq (caar (c-guess-basic-syntax))
469 ; '(brace-list-intro
470 ; brace-list-entry
471 ; brace-entry-open))))))
472
473 ;; With a prefix argument, comma delimiter will be aligned. Since
474 ;; perl-mode doesn't give us enough syntactic information (and we
475 ;; don't do our own parsing yet), this rule is too destructive to
476 ;; run normally.
477 (basic-comma-delimiter
478 (regexp . ",\\(\\s-*\\)[^# \t\n]")
479 (repeat . t)
480 (modes . (append align-perl-modes '(python-mode)))
481 (run-if . ,(function (lambda () current-prefix-arg))))
482
483 (c++-comment
484 (regexp . "\\(\\s-*\\)\\(//.*\\|/\\*.*\\*/\\s-*\\)$")
485 (modes . align-c++-modes)
486 (column . comment-column)
487 (valid . ,(function
488 (lambda ()
489 (save-excursion
490 (goto-char (match-beginning 1))
491 (not (bolp)))))))
492
493 (c-chain-logic
494 (regexp . "\\(\\s-*\\)\\(&&\\|||\\|\\<and\\>\\|\\<or\\>\\)")
495 (modes . align-c++-modes)
496 (valid . ,(function
497 (lambda ()
498 (save-excursion
499 (goto-char (match-end 2))
500 (looking-at "\\s-*\\(/[*/]\\|$\\)"))))))
501
502 (perl-chain-logic
503 (regexp . "\\(\\s-*\\)\\(&&\\|||\\|\\<and\\>\\|\\<or\\>\\)")
504 (modes . align-perl-modes)
505 (valid . ,(function
506 (lambda ()
507 (save-excursion
508 (goto-char (match-end 2))
509 (looking-at "\\s-*\\(#\\|$\\)"))))))
510
511 (python-chain-logic
512 (regexp . "\\(\\s-*\\)\\(\\<and\\>\\|\\<or\\>\\)")
513 (modes . '(python-mode))
514 (valid . ,(function
515 (lambda ()
516 (save-excursion
517 (goto-char (match-end 2))
518 (looking-at "\\s-*\\(#\\|$\\|\\\\\\)"))))))
519
520 (c-macro-line-continuation
521 (regexp . "\\(\\s-*\\)\\\\$")
522 (modes . align-c++-modes)
523 (column . c-backslash-column))
524 ; (valid
525 ; . ,(function
526 ; (lambda ()
527 ; (memq (caar (c-guess-basic-syntax))
528 ; '(cpp-macro cpp-macro-cont))))))
529
530 (basic-line-continuation
531 (regexp . "\\(\\s-*\\)\\\\$")
532 (modes . '(python-mode makefile-mode)))
533
534 (tex-record-separator
535 (regexp . ,(function
536 (lambda (end reverse)
537 (align-match-tex-pattern "&" end reverse))))
538 (group . (1 2))
539 (modes . align-tex-modes)
540 (repeat . t))
541
542 (tex-tabbing-separator
543 (regexp . ,(function
544 (lambda (end reverse)
545 (align-match-tex-pattern "\\\\[=>]" end reverse))))
546 (group . (1 2))
547 (modes . align-tex-modes)
548 (repeat . t)
549 (run-if . ,(function
550 (lambda ()
551 (eq major-mode 'latex-mode)))))
552
553 (tex-record-break
554 (regexp . "\\(\\s-*\\)\\\\\\\\")
555 (modes . align-tex-modes))
556
557 ;; With a numeric prefix argument, or C-u, space delimited text
558 ;; tables will be aligned.
559 (text-column
560 (regexp . "\\(^\\|\\S-\\)\\([ \t]+\\)\\(\\S-\\|$\\)")
561 (group . 2)
562 (modes . align-text-modes)
563 (repeat . t)
564 (run-if . ,(function
565 (lambda ()
566 (and current-prefix-arg
567 (not (eq '- current-prefix-arg)))))))
568
569 ;; With a negative prefix argument, lists of dollar figures will
570 ;; be aligned.
571 (text-dollar-figure
572 (regexp . "\\$?\\(\\s-+[0-9]+\\)\\.")
573 (modes . align-text-modes)
574 (justify . t)
575 (run-if . ,(function
576 (lambda ()
577 (eq '- current-prefix-arg)))))
578
579 (css-declaration
580 (regexp . "^\\s-*\\w+:\\(\\s-*\\).*;")
581 (group . (1))
582 (modes . '(css-mode html-mode))))
583 "A list describing all of the available alignment rules.
584 The format is:
585
586 ((TITLE
587 (ATTRIBUTE . VALUE) ...)
588 ...)
589
590 The following attributes are meaningful:
591
592 `regexp' This required attribute must be either a string describing
593 a regular expression, or a function (described below).
594 For every line within the section that this regular
595 expression matches, the given rule will be applied to that
596 line. The exclusion rules denote which part(s) of the
597 line should not be modified; the alignment rules cause the
598 identified whitespace group to be contracted/expanded such
599 that the \"alignment character\" (the character
600 immediately following the identified parenthesis group),
601 occurs in the same column for every line within the
602 alignment section (see `align-region-separate' for a
603 description of how the region is broken up into alignment
604 sections).
605
606 The `regexp' attribute describes how the text should be
607 treated. Within this regexp, there must be at least one
608 group of characters (typically whitespace) identified by
609 the special opening and closing parens used in regexp
610 expressions (`\\\\(' and `\\\\)') (see the Emacs manual on
611 the syntax of regular expressions for more info).
612
613 If `regexp' is a function, it will be called as a
614 replacement for `re-search-forward'. This means that it
615 should return nil if nothing is found to match the rule,
616 or it should set the match data appropriately, move point
617 to the end of the match, and return the value of point.
618
619 `group' For exclusion rules, the group identifies the range of
620 characters that should be ignored. For alignment rules,
621 these are the characters that will be deleted/expanded for
622 the purposes of alignment. The \"alignment character\" is
623 always the first character immediately following this
624 parenthesis group. This attribute may also be a list of
625 integers, in which case multiple alignment characters will
626 be aligned, with the list of integers identifying the
627 whitespace groups which precede them. The default for
628 this attribute is 1.
629
630 `modes' The `modes' attribute, if set, should name a list of
631 major modes -- or evaluate to such a value -- in which the
632 rule is valid. If not set, the rule will apply to all
633 modes.
634
635 `case-fold' If `regexp' is an ordinary regular expression string
636 containing alphabetic character, sometimes you may want
637 the search to proceed case-insensitively (for languages
638 that ignore case, such as Pascal for example). In that
639 case, set `case-fold' to a non-nil value, and the regular
640 expression search will ignore case. If `regexp' is set to
641 a function, that function must handle the job of ignoring
642 case by itself.
643
644 `tab-stop' If the `tab-stop' attribute is set, and non-nil, the
645 alignment character will always fall on a tab stop
646 (whether it uses tabs to get there or not depends on the
647 value of `indent-tabs-mode'). If the `tab-stop' attribute
648 is set to nil, tab stops will never be used. Otherwise,
649 the value of `align-to-tab-stop' determines whether or not
650 to align to a tab stop. The `tab-stop' attribute may also
651 be a list of t or nil values, corresponding to the number
652 of parenthesis groups specified by the `group' attribute.
653
654 `repeat' If the `repeat' attribute is present, and non-nil, the
655 rule will be applied to the line continuously until no
656 further matches are found.
657
658 `valid' If the `valid' attribute is set, it will be used to
659 determine whether the rule should be invoked. This form
660 is evaluated after the regular expression match has been
661 performed, so that it is possible to use the results of
662 that match to determine whether the alignment should be
663 performed. The buffer should not be modified during the
664 evaluation of this form.
665
666 `run-if' Like `valid', the `run-if' attribute tests whether the
667 rule should be run at all -- even before any searches are
668 done to determine if the rule applies to the alignment
669 region. This can save time, since `run-if' will only be
670 run once for each rule. If it returns nil, the rule will
671 not be attempted.
672
673 `column' For alignment rules, if the `column' attribute is set --
674 which must be an integer, or a symbol whose value is an
675 integer -- it will be used as the column in which to align
676 the alignment character. If the text on a particular line
677 happens to overrun that column, a single space character,
678 or tab stop (see `align-to-tab-stop') will be added
679 between the last text character and the alignment
680 character.
681
682 `spacing' Alignment rules may also override the amount of spacing
683 that would normally be used by providing a `spacing'
684 attribute. This must be an integer, or a list of integers
685 corresponding to the number of parenthesis groups matched
686 by the `group' attribute. If a list of value is used, and
687 any of those values is nil, `align-default-spacing' will
688 be used for that subgroup. See `align-default-spacing'
689 for more details on spacing, tab stops, and how to
690 indicate how much spacing should be used. If TAB-STOP is
691 present, it will override the value of `align-to-tab-stop'
692 for that rule.
693
694 `justify' It is possible with `regexp' and `group' to identify a
695 character group that contains more than just whitespace
696 characters. By default, any non-whitespace characters in
697 that group will also be deleted while aligning the
698 alignment character. However, if the `justify' attribute
699 is set to a non-nil value, only the initial whitespace
700 characters within that group will be deleted. This has
701 the effect of right-justifying the characters that remain,
702 and can be used for outdenting or just plain old right-
703 justification.
704
705 `separate' Each rule can define its own section separator, which
706 describes how to identify the separation of \"sections\"
707 within the region to be aligned. Setting the `separate'
708 attribute overrides the value of `align-region-separate'
709 (see the documentation of that variable for possible
710 values), and any separation argument passed to `align'."
711 :type align-rules-list-type
712 :group 'align)
713
714 (put 'align-rules-list 'risky-local-variable t)
715
716 (defvar align-exclude-rules-list-type
717 '(repeat
718 (cons
719 :tag "Exclusion rule"
720 (symbol :tag "Title")
721 (cons :tag "Required attributes"
722 (cons :tag "Regexp"
723 (const :tag "(Regular expression to match)" regexp)
724 (choice :value "\\(\\s-+\\)" regexp function))
725 (repeat
726 :tag "Optional attributes"
727 (choice
728 (cons :tag "Repeat"
729 (const :tag "(Repeat this rule throughout line)"
730 repeat)
731 (boolean :value t))
732 (cons :tag "Paren group"
733 (const :tag "(Parenthesis group to use)" group)
734 (choice :value 2
735 integer (repeat integer)))
736 (cons :tag "Modes"
737 (const :tag "(Modes where this rule applies)" modes)
738 (sexp :value (text-mode)))
739 (cons :tag "Case-fold"
740 (const :tag "(Should case be ignored for this rule)"
741 case-fold)
742 (boolean :value t)))))))
743 "The `type' form for any `align-exclude-rules-list' variable.")
744
745 (defcustom align-exclude-rules-list
746 `((exc-dq-string
747 (regexp . "\"\\([^\"\n]+\\)\"")
748 (repeat . t)
749 (modes . align-dq-string-modes))
750
751 (exc-sq-string
752 (regexp . "'\\([^'\n]+\\)'")
753 (repeat . t)
754 (modes . align-sq-string-modes))
755
756 (exc-open-comment
757 (regexp
758 . ,(function
759 (lambda (end reverse)
760 (funcall (if reverse 're-search-backward
761 're-search-forward)
762 (concat "[^ \t\n\\\\]"
763 (regexp-quote comment-start)
764 "\\(.+\\)$") end t))))
765 (modes . align-open-comment-modes))
766
767 (exc-c-comment
768 (regexp . "/\\*\\(.+\\)\\*/")
769 (repeat . t)
770 (modes . align-c++-modes))
771
772 (exc-c-func-params
773 (regexp . "(\\([^)\n]+\\))")
774 (repeat . t)
775 (modes . align-c++-modes))
776
777 (exc-c-macro
778 (regexp . "^\\s-*#\\s-*\\(if\\w*\\|endif\\)\\(.*\\)$")
779 (group . 2)
780 (modes . align-c++-modes)))
781 "A list describing text that should be excluded from alignment.
782 See the documentation for `align-rules-list' for more info."
783 :type align-exclude-rules-list-type
784 :group 'align)
785
786 (put 'align-exclude-rules-list 'risky-local-variable t)
787
788 ;;; Internal Variables:
789
790 (defvar align-mode-rules-list nil
791 "Alignment rules specific to the current major mode.
792 See the variable `align-rules-list' for more details.")
793
794 (make-variable-buffer-local 'align-mode-rules-list)
795
796 (defvar align-mode-exclude-rules-list nil
797 "Alignment exclusion rules specific to the current major mode.
798 See the variable `align-exclude-rules-list' for more details.")
799
800 (make-variable-buffer-local 'align-mode-exclude-rules-list)
801
802 (defvar align-highlight-overlays nil
803 "The current overlays highlighting the text matched by a rule.")
804
805 (defvar align-regexp-history nil
806 "Input history for the full user-entered regex in `align-regexp'")
807
808 ;; Sample extension rule set, for vhdl-mode. This should properly be
809 ;; in vhdl-mode.el itself.
810
811 (defcustom align-vhdl-rules-list
812 `((vhdl-declaration
813 (regexp . "\\(signal\\|variable\\|constant\\)\\(\\s-+\\)\\S-")
814 (group . 2))
815
816 (vhdl-case
817 (regexp . "\\(others\\|[^ \t\n=<]\\)\\(\\s-*\\)=>\\(\\s-*\\)\\S-")
818 (group . (2 3))
819 (valid
820 . ,(function
821 (lambda ()
822 (not (string= (downcase (match-string 1))
823 "others"))))))
824
825 (vhdl-colon
826 (regexp . "[^ \t\n:]\\(\\s-*\\):\\(\\s-*\\)[^=\n]")
827 (group . (1 2)))
828
829 (direction
830 (regexp . ":\\s-*\\(in\\|out\\|inout\\|buffer\\)\\(\\s-*\\)")
831 (group . 2))
832
833 (sig-assign
834 (regexp . "[^ \t\n=<]\\(\\s-*\\)<=\\(\\s-*\\)\\S-")
835 (group . (1 2)))
836
837 (var-assign
838 (regexp . "[^ \t\n:]\\(\\s-*\\):="))
839
840 (use-entity
841 (regexp . "\\(\\s-+\\)use\\s-+entity")))
842 "Alignment rules for `vhdl-mode'. See `align-rules-list' for more info."
843 :type align-rules-list-type
844 :group 'align)
845
846 (put 'align-vhdl-rules-list 'risky-local-variable t)
847
848 (defun align-set-vhdl-rules ()
849 "Setup the `align-mode-rules-list' variable for `vhdl-mode'."
850 (setq align-mode-rules-list align-vhdl-rules-list))
851
852 (add-hook 'vhdl-mode-hook 'align-set-vhdl-rules)
853
854 (add-to-list 'align-dq-string-modes 'vhdl-mode)
855 (add-to-list 'align-open-comment-modes 'vhdl-mode)
856
857 ;;; User Functions:
858
859 ;;;###autoload
860 (defun align (beg end &optional separate rules exclude-rules)
861 "Attempt to align a region based on a set of alignment rules.
862 BEG and END mark the region. If BEG and END are specifically set to
863 nil (this can only be done programmatically), the beginning and end of
864 the current alignment section will be calculated based on the location
865 of point, and the value of `align-region-separate' (or possibly each
866 rule's `separate' attribute).
867
868 If SEPARATE is non-nil, it overrides the value of
869 `align-region-separate' for all rules, except those that have their
870 `separate' attribute set.
871
872 RULES and EXCLUDE-RULES, if either is non-nil, will replace the
873 default rule lists defined in `align-rules-list' and
874 `align-exclude-rules-list'. See `align-rules-list' for more details
875 on the format of these lists."
876 (interactive "r")
877 (let ((separator
878 (or separate
879 (if (and (symbolp align-region-separate)
880 (boundp align-region-separate))
881 (symbol-value align-region-separate)
882 align-region-separate)
883 'entire)))
884 (if (not (or ;(eq separator 'largest)
885 (and (functionp separator)
886 (not (funcall separator nil nil)))))
887 (align-region beg end separator
888 (or rules align-mode-rules-list align-rules-list)
889 (or exclude-rules align-mode-exclude-rules-list
890 align-exclude-rules-list))
891 (let ((sec-first end)
892 (sec-last beg))
893 (align-region beg end
894 separator
895 nil ; rules
896 (or exclude-rules
897 align-mode-exclude-rules-list
898 align-exclude-rules-list)
899 (lambda (b e mode)
900 (when (consp mode)
901 (setq sec-first (min sec-first b)
902 sec-last (max sec-last e)))))
903 (if (< sec-first sec-last)
904 (align-region sec-first sec-last 'entire
905 (or rules align-mode-rules-list align-rules-list)
906 (or exclude-rules align-mode-exclude-rules-list
907 align-exclude-rules-list)))))))
908
909 ;;;###autoload
910 (defun align-regexp (beg end regexp &optional group spacing repeat)
911 "Align the current region using an ad-hoc rule read from the minibuffer.
912 BEG and END mark the limits of the region. Interactively, this function
913 prompts for the regular expression REGEXP to align with.
914
915 For example, let's say you had a list of phone numbers, and wanted to
916 align them so that the opening parentheses would line up:
917
918 Fred (123) 456-7890
919 Alice (123) 456-7890
920 Mary-Anne (123) 456-7890
921 Joe (123) 456-7890
922
923 There is no predefined rule to handle this, but you could easily do it
924 using a REGEXP like \"(\". Interactively, all you would have to do is
925 to mark the region, call `align-regexp' and enter that regular expression.
926
927 REGEXP must contain at least one parenthesized subexpression, typically
928 whitespace of the form \"\\\\(\\\\s-*\\\\)\". In normal interactive use,
929 this is automatically added to the start of your regular expression after
930 you enter it. You only need to supply the characters to be lined up, and
931 any preceding whitespace is replaced.
932
933 If you specify a prefix argument (or use this function non-interactively),
934 you must enter the full regular expression, including the subexpression.
935 The function also then prompts for which subexpression parenthesis GROUP
936 \(default 1) within REGEXP to modify, the amount of SPACING (default
937 `align-default-spacing') to use, and whether or not to REPEAT the rule
938 throughout the line.
939
940 See `align-rules-list' for more information about these options.
941
942 The non-interactive form of the previous example would look something like:
943 (align-regexp (point-min) (point-max) \"\\\\(\\\\s-*\\\\)(\")
944
945 This function is a nothing more than a small wrapper that helps you
946 construct a rule to pass to `align-region', which does the real work."
947 (interactive
948 (append
949 (list (region-beginning) (region-end))
950 (if current-prefix-arg
951 (list (read-string "Complex align using regexp: "
952 "\\(\\s-*\\)" 'align-regexp-history)
953 (string-to-number
954 (read-string
955 "Parenthesis group to modify (justify if negative): " "1"))
956 (string-to-number
957 (read-string "Amount of spacing (or column if negative): "
958 (number-to-string align-default-spacing)))
959 (y-or-n-p "Repeat throughout line? "))
960 (list (concat "\\(\\s-*\\)"
961 (read-string "Align regexp: "))
962 1 align-default-spacing nil))))
963 (or group (setq group 1))
964 (or spacing (setq spacing align-default-spacing))
965 (let ((rule
966 (list (list nil (cons 'regexp regexp)
967 (cons 'group (abs group))
968 (if (< group 0)
969 (cons 'justify t)
970 (cons 'bogus nil))
971 (if (>= spacing 0)
972 (cons 'spacing spacing)
973 (cons 'column (abs spacing)))
974 (cons 'repeat repeat)))))
975 (align-region beg end 'entire rule nil nil)))
976
977 ;;;###autoload
978 (defun align-entire (beg end &optional rules exclude-rules)
979 "Align the selected region as if it were one alignment section.
980 BEG and END mark the extent of the region. If RULES or EXCLUDE-RULES
981 is set to a list of rules (see `align-rules-list'), it can be used to
982 override the default alignment rules that would have been used to
983 align that section."
984 (interactive "r")
985 (align beg end 'entire rules exclude-rules))
986
987 ;;;###autoload
988 (defun align-current (&optional rules exclude-rules)
989 "Call `align' on the current alignment section.
990 This function assumes you want to align only the current section, and
991 so saves you from having to specify the region. If RULES or
992 EXCLUDE-RULES is set to a list of rules (see `align-rules-list'), it
993 can be used to override the default alignment rules that would have
994 been used to align that section."
995 (interactive)
996 (align nil nil nil rules exclude-rules))
997
998 ;;;###autoload
999 (defun align-highlight-rule (beg end title &optional rules exclude-rules)
1000 "Highlight the whitespace which a given rule would have modified.
1001 BEG and END mark the extent of the region. TITLE identifies the rule
1002 that should be highlighted. If RULES or EXCLUDE-RULES is set to a
1003 list of rules (see `align-rules-list'), it can be used to override the
1004 default alignment rules that would have been used to identify the text
1005 to be colored."
1006 (interactive
1007 (list (region-beginning) (region-end)
1008 (completing-read
1009 "Title of rule to highlight: "
1010 (mapcar
1011 (function
1012 (lambda (rule)
1013 (list (symbol-name (car rule)))))
1014 (append (or align-mode-rules-list align-rules-list)
1015 (or align-mode-exclude-rules-list
1016 align-exclude-rules-list))) nil t)))
1017 (let ((ex-rule (assq (intern title)
1018 (or align-mode-exclude-rules-list
1019 align-exclude-rules-list)))
1020 face)
1021 (align-unhighlight-rule)
1022 (align-region
1023 beg end 'entire
1024 (or rules (if ex-rule
1025 (or exclude-rules align-mode-exclude-rules-list
1026 align-exclude-rules-list)
1027 (or align-mode-rules-list align-rules-list)))
1028 (unless ex-rule (or exclude-rules align-mode-exclude-rules-list
1029 align-exclude-rules-list))
1030 (function
1031 (lambda (b e mode)
1032 (if (and mode (listp mode))
1033 (if (equal (symbol-name (car mode)) title)
1034 (setq face (cons align-highlight-change-face
1035 align-highlight-nochange-face))
1036 (setq face nil))
1037 (when face
1038 (let ((overlay (make-overlay b e)))
1039 (setq align-highlight-overlays
1040 (cons overlay align-highlight-overlays))
1041 (overlay-put overlay 'face
1042 (if mode
1043 (car face)
1044 (cdr face)))))))))))
1045
1046 ;;;###autoload
1047 (defun align-unhighlight-rule ()
1048 "Remove any highlighting that was added by `align-highlight-rule'."
1049 (interactive)
1050 (while align-highlight-overlays
1051 (delete-overlay (car align-highlight-overlays))
1052 (setq align-highlight-overlays
1053 (cdr align-highlight-overlays))))
1054
1055 ;;;###autoload
1056 (defun align-newline-and-indent ()
1057 "A replacement function for `newline-and-indent', aligning as it goes."
1058 (interactive)
1059 (let ((separate (or (if (and (symbolp align-region-separate)
1060 (boundp align-region-separate))
1061 (symbol-value align-region-separate)
1062 align-region-separate)
1063 'entire))
1064 (end (point)))
1065 (call-interactively 'newline-and-indent)
1066 (save-excursion
1067 (forward-line -1)
1068 (while (not (or (bobp)
1069 (align-new-section-p (point) end separate)))
1070 (forward-line -1))
1071 (align (point) end))))
1072
1073 ;;; Internal Functions:
1074
1075 (defun align-match-tex-pattern (regexp end &optional reverse)
1076 "Match REGEXP in TeX mode, counting backslashes appropriately.
1077 END denotes the end of the region to be searched, while REVERSE, if
1078 non-nil, indicates that the search should proceed backward from the
1079 current position."
1080 (let (result)
1081 (while
1082 (and (setq result
1083 (funcall
1084 (if reverse 're-search-backward
1085 're-search-forward)
1086 (concat "\\(\\s-*\\)" regexp
1087 "\\(\\s-*\\)") end t))
1088 (let ((pos (match-end 1))
1089 (count 0))
1090 (while (and (> pos (point-min))
1091 (eq (char-before pos) ?\\))
1092 (setq count (1+ count) pos (1- pos)))
1093 (eq (mod count 2) 1))
1094 (goto-char (match-beginning (if reverse 1 2)))))
1095 result))
1096
1097 (defun align-new-section-p (beg end separator)
1098 "Is there a section divider between BEG and END?
1099 SEPARATOR specifies how to look for the section divider. See the
1100 documentation for `align-region-separate' for more details."
1101 (cond ((or (not separator)
1102 (eq separator 'entire))
1103 nil)
1104 ((eq separator 'group)
1105 (let ((amount 2))
1106 (save-excursion
1107 (goto-char end)
1108 (if (bolp)
1109 (setq amount 1)))
1110 (> (count-lines beg end) amount)))
1111 ((stringp separator)
1112 (save-excursion
1113 (goto-char beg)
1114 (re-search-forward separator end t)))
1115 ((functionp separator)
1116 (funcall separator beg end))
1117 ((listp separator)
1118 (let ((seps separator) yes)
1119 (while seps
1120 (if (and (>= (car seps) beg)
1121 (<= (car seps) end))
1122 (setq yes t seps nil)
1123 (setq seps (cdr seps))))
1124 yes))))
1125
1126 (defun align-adjust-col-for-rule (column _rule spacing tab-stop)
1127 "Adjust COLUMN according to the given RULE.
1128 SPACING specifies how much spacing to use.
1129 TAB-STOP specifies whether SPACING refers to tab-stop boundaries."
1130 (unless spacing
1131 (setq spacing align-default-spacing))
1132 (if (<= spacing 0)
1133 column
1134 (if (not tab-stop)
1135 (+ column spacing)
1136 (dotimes (_ spacing)
1137 (setq column (indent-next-tab-stop column)))
1138 column)))
1139
1140 (defsubst align-column (pos)
1141 "Given a position in the buffer, state what column it's in.
1142 POS is the position whose column will be taken. Note that this
1143 function will change the location of point."
1144 (goto-char pos)
1145 (current-column))
1146
1147 (defsubst align-regions (regions props rule func)
1148 "Align the regions specified in REGIONS, a list of cons cells.
1149 PROPS describes formatting features specific to the given regions.
1150 RULE specifies exactly how to perform the alignments.
1151 If FUNC is specified, it will be called with each region that would
1152 have been aligned, rather than modifying the text."
1153 (while regions
1154 (save-excursion
1155 (align-areas (car regions) (car props) rule func))
1156 (setq regions (cdr regions)
1157 props (cdr props))))
1158
1159 (defun align-areas (areas props rule func)
1160 "Given a list of AREAS and formatting PROPS, align according to RULE.
1161 AREAS should be a list of cons cells containing beginning and ending
1162 markers. This function sweeps through all of the beginning markers,
1163 finds out which one starts in the furthermost column, and then deletes
1164 and inserts text such that all of the ending markers occur in the same
1165 column.
1166
1167 If FUNC is non-nil, it will be called for each text region that would
1168 have been aligned. No changes will be made to the buffer."
1169 (let* ((column (cdr (assq 'column rule)))
1170 (fixed (if (symbolp column)
1171 (symbol-value column)
1172 column))
1173 (justify (cdr (assq 'justify rule)))
1174 (col (or fixed 0))
1175 (width 0)
1176 ecol change)
1177
1178 ;; Determine the alignment column.
1179 (let ((a areas))
1180 (while a
1181 (unless fixed
1182 (setq col (max col (align-column (caar a)))))
1183 (unless change
1184 (goto-char (cdar a))
1185 (if ecol
1186 (if (/= ecol (current-column))
1187 (setq change t))
1188 (setq ecol (current-column))))
1189 (when justify
1190 (goto-char (caar a))
1191 (if (and (re-search-forward "\\s-*" (cdar a) t)
1192 (/= (point) (cdar a)))
1193 (let ((bcol (current-column)))
1194 (setcdr (car a) (cons (point-marker) (cdar a)))
1195 (goto-char (cdr (cdar a)))
1196 (setq width (max width (- (current-column) bcol))))))
1197 (setq a (cdr a))))
1198
1199 (unless fixed
1200 (setq col (+ (align-adjust-col-for-rule
1201 col rule (car props) (cdr props)) width)))
1202
1203 ;; Make all ending positions to occur in the goal column. Since
1204 ;; the whitespace to be modified was already deleted by
1205 ;; `align-region', all we have to do here is indent.
1206
1207 (unless change
1208 (setq change (and ecol (/= col ecol))))
1209
1210 (when (or func change)
1211 (while areas
1212 (let ((area (car areas))
1213 (gocol col) cur)
1214 (when area
1215 (if func
1216 (funcall func
1217 (marker-position (car area))
1218 (marker-position (cdr area))
1219 change)
1220 (if (not (and justify
1221 (consp (cdr area))))
1222 (goto-char (cdr area))
1223 (goto-char (cddr area))
1224 (let ((ecol (current-column)))
1225 (goto-char (cadr area))
1226 (setq gocol (- col (- ecol (current-column))))))
1227 (setq cur (current-column))
1228 (cond ((< gocol 0) t) ; don't do anything
1229 ((= cur gocol) t) ; don't need to
1230 ((< cur gocol) ; just add space
1231 ;; FIXME: It is stated above that "...the
1232 ;; whitespace to be modified was already
1233 ;; deleted by `align-region', all we have
1234 ;; to do here is indent." However, this
1235 ;; doesn't seem to be true, so we first
1236 ;; delete the whitespace to avoid tabs
1237 ;; after spaces.
1238 (delete-horizontal-space t)
1239 (indent-to gocol))
1240 (t
1241 ;; This code works around an oddity in the
1242 ;; FORCE argument of `move-to-column', which
1243 ;; tends to screw up markers if there is any
1244 ;; tabbing.
1245 (let ((endcol (align-column
1246 (if (and justify
1247 (consp (cdr area)))
1248 (cadr area)
1249 (cdr area))))
1250 (abuts (<= gocol
1251 (align-column (car area)))))
1252 (if abuts
1253 (goto-char (car area))
1254 (move-to-column gocol t))
1255 (let ((here (point)))
1256 (move-to-column endcol t)
1257 (delete-region here (point))
1258 (if abuts
1259 (indent-to (align-adjust-col-for-rule
1260 (current-column) rule
1261 (car props) (cdr props)))))))))))
1262 (setq areas (cdr areas))))))
1263
1264 (defmacro align--set-marker (marker-var pos &optional type)
1265 "If MARKER-VAR is a marker, move it to position POS.
1266 Otherwise, create a new marker at position POS, with type TYPE."
1267 `(if (markerp ,marker-var)
1268 (move-marker ,marker-var ,pos)
1269 (setq ,marker-var (copy-marker ,pos ,type))))
1270
1271 (defun align-region (beg end separate rules exclude-rules
1272 &optional func)
1273 "Align a region based on a given set of alignment rules.
1274 BEG and END specify the region to be aligned. Either may be nil, in
1275 which case the range will stop at the nearest section division (see
1276 `align-region-separate', and `align-region-heuristic' for more
1277 information').
1278
1279 The region will be divided into separate alignment sections based on
1280 the value of SEPARATE.
1281
1282 RULES and EXCLUDE-RULES are a pair of lists describing how to align
1283 the region, and which text areas within it should be excluded from
1284 alignment. See the `align-rules-list' for more information on the
1285 required format of these two lists.
1286
1287 If FUNC is specified, no text will be modified. What `align-region'
1288 will do with the rules is to search for the alignment areas, as it
1289 regularly would, taking account for exclusions, and then call FUNC,
1290 first with the beginning and ending of the region to be aligned
1291 according to that rule (this can be different for each rule, if BEG
1292 and END were nil), and then with the beginning and ending of each
1293 text region that the rule would have applied to.
1294
1295 The signature of FUNC should thus be:
1296
1297 (defun my-align-function (beg end mode)
1298 \"If MODE is a rule (a list), return t if BEG to END are to be searched.
1299 Otherwise BEG to END will be a region of text that matches the rule's
1300 definition, and MODE will be non-nil if any changes are necessary.\"
1301 (unless (and mode (listp mode))
1302 (message \"Would have aligned from %d to %d...\" beg end)))
1303
1304 This feature (of passing a FUNC) is used internally to locate the
1305 position of exclusion areas, but could also be used for any other
1306 purpose where you might want to know where the regions that the
1307 aligner would have dealt with are."
1308 (let ((end-mark (and end (copy-marker end t)))
1309 (real-beg beg)
1310 (report (and (not func) align-large-region beg end
1311 (>= (- end beg) align-large-region)))
1312 (rule-index 1)
1313 (rule-count (length rules))
1314 markers)
1315 (if (and align-indent-before-aligning real-beg end-mark)
1316 (indent-region real-beg end-mark nil))
1317 (while rules
1318 (let* ((rule (car rules))
1319 (run-if (assq 'run-if rule))
1320 (modes (assq 'modes rule)))
1321 ;; unless the `run-if' form tells us not to, look for the
1322 ;; rule..
1323 (unless (or (and modes (not (memq major-mode
1324 (eval (cdr modes)))))
1325 (and run-if (not (funcall (cdr run-if)))))
1326 (let* ((case-fold-search case-fold-search)
1327 (case-fold (assq 'case-fold rule))
1328 (regexp (cdr (assq 'regexp rule)))
1329 (regfunc (and (functionp regexp) regexp))
1330 (rulesep (assq 'separate rule))
1331 (thissep (if rulesep (cdr rulesep) separate))
1332 same (eol 0)
1333 search-start
1334 groups group-c
1335 spacing spacing-c
1336 tab-stop tab-stop-c
1337 repeat repeat-c
1338 valid valid-c
1339 first
1340 regions index
1341 last-point
1342 save-match-data
1343 exclude-p
1344 align-props)
1345 (save-excursion
1346 ;; if beg and end were not given, figure out what the
1347 ;; current alignment region should be. Depending on the
1348 ;; value of `align-region-separate' it's possible for
1349 ;; each rule to have its own definition of what that
1350 ;; current alignment section is.
1351 (if real-beg
1352 (goto-char beg)
1353 (if (or (not thissep) (eq thissep 'entire))
1354 (error "Cannot determine alignment region for `%s'"
1355 (symbol-name (cdr (assq 'title rule)))))
1356 (beginning-of-line)
1357 (while (and (not (eobp))
1358 (looking-at "^\\s-*$"))
1359 (forward-line))
1360 (let* ((here (point))
1361 (start here))
1362 (while (and here
1363 (let ((terminus
1364 (and align-region-heuristic
1365 (- (point)
1366 align-region-heuristic))))
1367 (if regfunc
1368 (funcall regfunc terminus t)
1369 (re-search-backward regexp
1370 terminus t))))
1371 (if (align-new-section-p (point) here thissep)
1372 (setq beg here
1373 here nil)
1374 (setq here (point))))
1375 (if (not here)
1376 (goto-char beg))
1377 (beginning-of-line)
1378 (setq beg (point))
1379 (goto-char start)
1380 (setq here (point))
1381 (while (and here
1382 (let ((terminus
1383 (and align-region-heuristic
1384 (+ (point)
1385 align-region-heuristic))))
1386 (if regfunc
1387 (funcall regfunc terminus nil)
1388 (re-search-forward regexp terminus t))))
1389 (if (align-new-section-p here (point) thissep)
1390 (setq end here
1391 here nil)
1392 (setq here (point))))
1393 (if (not here)
1394 (goto-char end))
1395 (forward-line)
1396 (setq end (point))
1397 (align--set-marker end-mark end t)
1398 (goto-char beg)))
1399
1400 ;; If we have a region to align, and `func' is set and
1401 ;; reports back that the region is ok, then align it.
1402 (when (or (not func)
1403 (funcall func beg end rule))
1404 (let (rule-beg exclude-areas)
1405 ;; determine first of all where the exclusions
1406 ;; lie in this region
1407 (when exclude-rules
1408 (align-region
1409 beg end 'entire
1410 exclude-rules nil
1411 (lambda (b e mode)
1412 (or (and mode (listp mode))
1413 (setq exclude-areas
1414 (cons (cons b e)
1415 exclude-areas)))))
1416 (setq exclude-areas
1417 (nreverse
1418 (sort exclude-areas #'car-less-than-car))))
1419
1420 ;; set `case-fold-search' according to the
1421 ;; (optional) `case-fold' property
1422 (and case-fold
1423 (setq case-fold-search (cdr case-fold)))
1424
1425 ;; while we can find the rule in the alignment
1426 ;; region..
1427 (while (and (< (point) end-mark)
1428 (setq search-start (point))
1429 (if regfunc
1430 (funcall regfunc end-mark nil)
1431 (re-search-forward regexp
1432 end-mark t)))
1433
1434 ;; give the user some indication of where we
1435 ;; are, if it's a very large region being
1436 ;; aligned
1437 (if report
1438 (let ((symbol (car rule)))
1439 (if (and symbol (symbolp symbol))
1440 (message
1441 "Aligning `%s' (rule %d of %d) %d%%..."
1442 (symbol-name symbol) rule-index rule-count
1443 (floor (* (- (point) real-beg) 100.0)
1444 (- end-mark real-beg)))
1445 (message
1446 "Aligning %d%%..."
1447 (floor (* (- (point) real-beg) 100.0)
1448 (- end-mark real-beg))))))
1449
1450 ;; if the search ended us on the beginning of
1451 ;; the next line, move back to the end of the
1452 ;; previous line.
1453 (if (and (bolp) (> (point) search-start))
1454 (forward-char -1))
1455
1456 ;; lookup the `group' attribute the first time
1457 ;; that we need it
1458 (unless group-c
1459 (setq groups (or (cdr (assq 'group rule)) 1))
1460 (unless (listp groups)
1461 (setq groups (list groups)))
1462 (setq first (car groups)))
1463
1464 (unless spacing-c
1465 (setq spacing (cdr (assq 'spacing rule))
1466 spacing-c t))
1467
1468 (unless tab-stop-c
1469 (setq tab-stop
1470 (let ((rule-ts (assq 'tab-stop rule)))
1471 (cond (rule-ts
1472 (cdr rule-ts))
1473 ((symbolp align-to-tab-stop)
1474 (symbol-value align-to-tab-stop))
1475 (t
1476 align-to-tab-stop)))
1477 tab-stop-c t))
1478
1479 ;; test whether we have found a match on the same
1480 ;; line as a previous match
1481 (when (> (point) eol)
1482 (setq same nil)
1483 (align--set-marker eol (line-end-position)))
1484
1485 ;; lookup the `repeat' attribute the first time
1486 (or repeat-c
1487 (setq repeat (cdr (assq 'repeat rule))
1488 repeat-c t))
1489
1490 ;; lookup the `valid' attribute the first time
1491 (or valid-c
1492 (setq valid (assq 'valid rule)
1493 valid-c t))
1494
1495 ;; remember the beginning position of this rule
1496 ;; match, and save the match-data, since either
1497 ;; the `valid' form, or the code that searches for
1498 ;; section separation, might alter it
1499 (setq rule-beg (match-beginning first)
1500 save-match-data (match-data))
1501
1502 (or rule-beg
1503 (error "No match for subexpression %s" first))
1504
1505 ;; unless the `valid' attribute is set, and tells
1506 ;; us that the rule is not valid at this point in
1507 ;; the code..
1508 (unless (and valid (not (funcall (cdr valid))))
1509
1510 ;; look to see if this match begins a new
1511 ;; section. If so, we should align what we've
1512 ;; collected so far, and then begin collecting
1513 ;; anew for the next alignment section
1514 (when (and last-point
1515 (align-new-section-p last-point rule-beg
1516 thissep))
1517 (align-regions regions align-props rule func)
1518 (setq regions nil)
1519 (setq align-props nil))
1520 (align--set-marker last-point rule-beg t)
1521
1522 ;; restore the match data
1523 (set-match-data save-match-data)
1524
1525 ;; check whether the region to be aligned
1526 ;; straddles an exclusion area
1527 (let ((excls exclude-areas))
1528 (setq exclude-p nil)
1529 (while excls
1530 (if (and (< (match-beginning (car groups))
1531 (cdar excls))
1532 (> (match-end (car (last groups)))
1533 (caar excls)))
1534 (setq exclude-p t
1535 excls nil)
1536 (setq excls (cdr excls)))))
1537
1538 ;; go through the parenthesis groups
1539 ;; matching whitespace to be contracted or
1540 ;; expanded (or possibly justified, if the
1541 ;; `justify' attribute was set)
1542 (unless exclude-p
1543 (dolist (g groups)
1544 ;; We must use markers, since
1545 ;; `align-areas' may modify the buffer.
1546 ;; Avoid polluting the markers.
1547 (let* ((group-beg (copy-marker
1548 (match-beginning g) t))
1549 (group-end (copy-marker
1550 (match-end g) t))
1551 (region (cons group-beg group-end))
1552 (props (cons (if (listp spacing)
1553 (car spacing)
1554 spacing)
1555 (if (listp tab-stop)
1556 (car tab-stop)
1557 tab-stop))))
1558 (push group-beg markers)
1559 (push group-end markers)
1560 (setq index (if same (1+ index) 0))
1561 (cond
1562 ((nth index regions)
1563 (setcar (nthcdr index regions)
1564 (cons region
1565 (nth index regions))))
1566 (regions
1567 (nconc regions
1568 (list (list region)))
1569 (nconc align-props (list props)))
1570 (t
1571 (setq regions
1572 (list (list region)))
1573 (setq align-props (list props)))))
1574 ;; If any further rule matches are found
1575 ;; before `eol', they are on the same
1576 ;; line as this one; this can only
1577 ;; happen if the `repeat' attribute is
1578 ;; non-nil.
1579 (if (listp spacing)
1580 (setq spacing (cdr spacing)))
1581 (if (listp tab-stop)
1582 (setq tab-stop (cdr tab-stop)))
1583 (setq same t))
1584
1585 ;; if `repeat' has not been set, move to
1586 ;; the next line; don't bother searching
1587 ;; anymore on this one
1588 (if (and (not repeat) (not (bolp)))
1589 (forward-line))
1590
1591 ;; if the search did not change point,
1592 ;; move forward to avoid an infinite loop
1593 (if (= (point) search-start)
1594 (forward-char)))))
1595
1596 ;; when they are no more matches for this rule,
1597 ;; align whatever was left over
1598 (if regions
1599 (align-regions regions align-props rule func))))))))
1600 (setq rules (cdr rules)
1601 rule-index (1+ rule-index)))
1602 ;; This function can use a lot of temporary markers, so instead of
1603 ;; waiting for the next GC we delete them immediately (Bug#10047).
1604 (when end-mark (set-marker end-mark nil))
1605 (dolist (m markers)
1606 (set-marker m nil))
1607
1608 (if report
1609 (message "Aligning...done"))))
1610
1611 ;; Provide:
1612
1613 (provide 'align)
1614
1615 (run-hooks 'align-load-hook)
1616
1617 ;;; align.el ends here