;;; align.el --- align text to a specific column, by regexp;; Copyright (C) 1999, 2000, 2002, 2003, 2004,;; 2005, 2006 Free Software Foundation, Inc.;; Author: John Wiegley <johnw@gnu.org>;; Keywords: convenience languages lisp;; This file is part of GNU Emacs.;; GNU Emacs is free software; you can redistribute it and/or modify;; it under the terms of the GNU General Public License as published by;; the Free Software Foundation; either version 2, or (at your option);; any later version.;; GNU Emacs is distributed in the hope that it will be useful,;; but WITHOUT ANY WARRANTY; without even the implied warranty of;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the;; GNU General Public License for more details.;; You should have received a copy of the GNU General Public License;; along with GNU Emacs; see the file COPYING. If not, write to the;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,;; Boston, MA 02110-1301, USA.;;; Commentary:;; This mode allows you to align regions in a context-sensitive fashion.;; The classic use is to align assignments:;;;; int a = 1;;; short foo = 2;;; double blah = 4;;;;; becomes;;;; int a = 1;;; short foo = 2;;; double blah = 4;;;; Usage:;; There are several variables which define how certain "categories";; of syntax are to be treated. These variables go by the name;; `align-CATEGORY-modes'. For example, "c++" is such a category.;; There are several rules which apply to c++, but since several other;; languages have a syntax similar to c++ (e.g., c, java, etc), these;; modes are treated as belonging to the same category.;;;; If you want to add a new mode under a certain category, just;; customize that list, or add the new mode manually. For example, to;; make jde-mode a c++ category mode, use this code in your .emacs;; file:;;;; (setq align-c++-modes (cons 'jde-mode align-c++-modes));; In some programming modes, it's useful to have the aligner run only;; after indentation is performed. To achieve this, customize or set;; the variable `align-indent-before-aligning' to t.;;; Module Authors:;; In order to incorporate align's functionality into your own;; modules, there are only a few steps you have to follow.;; 1. Require or load in the align.el library.;;;; 2. Define your alignment and exclusion rules lists, either;; customizable or not.;;;; 3. In your mode function, set the variables;; `align-mode-rules-list' and `align-mode-exclude-rules-list';; to your own rules lists.;; If there is any need to add your mode name to one of the;; align-?-modes variables (for example, `align-dq-string-modes'), use;; `add-to-list', or some similar function which checks first to see;; if the value is already there. Since the user may customize that;; mode list, and then write your mode name into their .emacs file,;; causing the symbol already to be present the next time they load;; your package.;; Example:;;;; (require 'align);;;; (defcustom my-align-rules-list;; '((my-rule;; (regexp . "Sample")));; :type align-rules-list-type;; :group 'my-package);;;; (put 'my-align-rules-list 'risky-local-variable t);;;; (add-to-list 'align-dq-string-modes 'my-package-mode);; (add-to-list 'align-open-comment-modes 'my-package-mode);;;; (defun my-mode ();; ...;; (setq align-mode-rules-list my-align-rules-list));;;; Note that if you need to install your own exclusion rules, then you;; will also need to reproduce any double-quoted string, or open;; comment exclusion rules that are defined in the standard;; `align-exclude-rules-list'. At the moment there is no convenient;; way to mix both mode-local and global rules lists.;;; History:;; Version 1.0 was created in the earlier part of 1996, using a very;; simple algorithm that understand only basic regular expressions.;; Parts of the code were broken up and included in vhdl-mode.el;; around this time. After several comments from users, and a need to;; find a more robust, performant algorithm, 2.0 was born in late;; 1998. Many different approaches were taken (mostly due to the;; complexity of TeX tables), but finally a scheme was discovered;; which worked fairly well for most common usage cases. Development;; beyond version 2.8 is not planned, except for problems that users;; might encounter.;;; Code:(defgroupalignnil"Align text to a specific column, by regexp.":version"21.1":group'fill);;; User Variables:(defcustomalign-load-hooknil"*Hook that gets run after the aligner has been loaded.":type'hook:group'align)(defcustomalign-indent-before-aligningnil"*If non-nil, indent the marked region before aligning it.":type'boolean:group'align)(defcustomalign-default-spacing1"*An integer that represents the default amount of padding to use.If `align-to-tab-stop' is non-nil, this will represent the number oftab stops to use for alignment, rather than the number of spaces.Each alignment rule can optionally override both this variable. See`align-mode-alist'.":type'integer:group'align)(defcustomalign-to-tab-stop'indent-tabs-mode"*If non-nil, alignments will always fall on a tab boundary.It may also be a symbol, whose value will be taken.":type'(choice(constnil)symbol):group'align)(defcustomalign-region-heuristic500"*If non-nil, used as a heuristic by `align-current'.Since each alignment rule can possibly have its own set of alignmentsections (whenever `align-region-separate' is non-nil, and not astring), this heuristic is used to determine how far before and afterpoint we should search in looking for a region separator. Largervalues can mean slower perform in large files, although smaller valuesmay cause unexpected behavior at times.":type'integer:group'align)(defcustomalign-highlight-change-face'highlight"*The face to highlight with if changes are necessary.":type'face:group'align)(defcustomalign-highlight-nochange-face'secondary-selection"*The face to highlight with if no changes are necessary.":type'face:group'align)(defcustomalign-large-region10000"*If an integer, defines what constitutes a \"large\" region.If nil,then no messages will ever be printed to the minibuffer.":type'integer:group'align)(defcustomalign-c++-modes'(c++-modec-modejava-mode)"*A list of modes whose syntax resembles C/C++.":type'(repeatsymbol):group'align)(defcustomalign-perl-modes'(perl-modecperl-mode)"*A list of modes where perl syntax is to be seen.":type'(repeatsymbol):group'align)(defcustomalign-lisp-modes'(emacs-lisp-modelisp-interaction-modelisp-modescheme-mode)"*A list of modes whose syntax resembles Lisp.":type'(repeatsymbol):group'align)(defcustomalign-tex-modes'(tex-modeplain-tex-modelatex-modeslitex-mode)"*A list of modes whose syntax resembles TeX (and family).":type'(repeatsymbol):group'align)(defcustomalign-text-modes'(text-modeoutline-mode)"*A list of modes whose content is plain text.":type'(repeatsymbol):group'align)(defcustomalign-dq-string-modes(appendalign-lisp-modesalign-c++-modesalign-perl-modes'(python-mode))"*A list of modes where double quoted strings should be excluded.":type'(repeatsymbol):group'align)(defcustomalign-sq-string-modes(appendalign-perl-modes'(python-mode))"*A list of modes where single quoted strings should be excluded.":type'(repeatsymbol):group'align)(defcustomalign-open-comment-modes(appendalign-lisp-modesalign-c++-modesalign-perl-modes'(python-modemakefile-mode))"*A list of modes with a single-line comment syntax.These are comments as in Lisp, which have a beginning but, end withthe line (i.e., `comment-end' is an empty string).":type'(repeatsymbol):group'align)(defcustomalign-region-separate"^\\s-*[{}]?\\s-*$""*Select the method by which alignment sections will be separated.If this is a symbol, that symbol's value will be used.For the sake of clarification, consider the following example, whichwill be referred to in the descriptions below. int alpha = 1; /* one */ double beta = 2.0; long gamma; /* ten */ unsigned int delta = 1; /* one */ long double epsilon = 3.0; long long omega; /* ten */The possible settings for `align-region-separate' are: `entire' The entire region being aligned will be considered as a single alignment section. Assuming that comments were not being aligned to a particular column, the example would become: int alpha = 1; /* one */ double beta = 2.0; long gamma; /* ten */ unsigned int delta = 1; /* one */ long double epsilon; long long chi = 10; /* ten */ `group' Each contiguous set of lines where a specific alignment occurs is considered a section for that alignment rule. Note that each rule will may have any entirely different set of section divisions than another. int alpha = 1; /* one */ double beta = 2.0; long gamma; /* ten */ unsigned int delta = 1; /* one */ long double epsilon; long long chi = 10; /* ten */ `largest' When contiguous rule sets overlap, the largest section described will be taken as the alignment section for each rule touched by that section. int alpha = 1; /* one */ double beta = 2.0; long gamma; /* ten */ unsigned int delta = 1; /* one */ long double epsilon; long long chi = 10; /* ten */ NOTE: This option is not supported yet, due to algorithmic issues which haven't been satisfactorily resolved. There are ways to do it, but they're both ugly and resource consumptive. regexp A regular expression string which defines the section divider. If the mode you're in has a consistent divider between sections, the behavior will be very similar to `largest', and faster. But if the mode does not use clear separators (for example, if you collapse your braces onto the preceding statement in C or perl), `largest' is probably the better alternative. function A function that will be passed the beginning and ending locations of the region in which to look for the section separator. At the very beginning of the attempt to align, both of these parameters will be nil, in which case the function should return non-nil if it wants each rule to define its own section, or nil if it wants the largest section found to be used as the common section for all rules that occur there. list A list of markers within the buffer that represent where the section dividers lie. Be certain to use markers! For when the aligning begins, the ensuing contract/expanding of whitespace will throw off any non-marker positions. This method is intended for use in Lisp programs, and not by the user.":type'(choice(const:tag"Entire region is one section"entire)(const:tag"Align by contiguous groups"group); (const largest)(regexp:tag"Regexp defines section boundaries")(function:tag"Function defines section boundaries")):group'align)(put'align-region-separate'risky-local-variablet)(defvaralign-rules-list-type'(repeat(cons:tag"Alignment rule"(symbol:tag"Title")(cons:tag"Required attributes"(cons:tag"Regexp"(const:tag"(Regular expression to match)"regexp)(choice:value"\\(\\s-+\\)"regexpfunction))(repeat:tag"Optional attributes"(choice(cons:tag"Repeat"(const:tag"(Repeat this rule throughout line)"repeat)(boolean:valuet))(cons:tag"Paren group"(const:tag"(Parenthesis group to use)"group)(choice:value2integer(repeatinteger)))(cons:tag"Modes"(const:tag"(Modes where this rule applies)"modes)(sexp:value(text-mode)))(cons:tag"Case-fold"(const:tag"(Should case be ignored for this rule)"case-fold)(boolean:valuet))(cons:tag"To Tab Stop"(const:tag"(Should rule align to tab stops)"tab-stop)(boolean:valuenil))(cons:tag"Valid"(const:tag"(Return non-nil if rule is valid)"valid)(function:valuet))(cons:tag"Run If"(const:tag"(Return non-nil if rule should run)"run-if)(function:valuet))(cons:tag"Column"(const:tag"(Column to fix alignment at)"column)(choice:valuecomment-columnintegersymbol))(cons:tag"Spacing"(const:tag"(Amount of spacing to use)"spacing)(integer:value1))(cons:tag"Justify"(const:tag"(Should text be right justified)"justify)(boolean:valuet));; make sure this stays up-to-date with any changes;; in `align-region-separate'(cons:tag"Separate"(const:tag"(Separation to use for this rule)"separate)(choice:value"^\\s-*$"(constentire)(constgroup); (const largest)regexpfunction)))))))"The `type' form for any `align-rules-list' variable.")(defcustomalign-rules-list`((lisp-second-arg(regexp."\\(^\\s-+[^( \t\n]\\|(\\(\\S-+\\)\\s-+\\)\\S-+\\(\\s-+\\)")(group.3)(modes.align-lisp-modes)(run-if.,(function(lambda()current-prefix-arg))))(lisp-alist-dot(regexp."\\(\\s-*\\)\\.\\(\\s-*\\)")(group.(12))(modes.align-lisp-modes))(open-comment(regexp.,(function(lambda(endreverse)(funcall(ifreverse're-search-backward're-search-forward)(concat"[^ \t\n\\\\]"(regexp-quotecomment-start)"\\(.+\\)$")endt))))(modes.align-open-comment-modes))(c-macro-definition(regexp."^\\s-*#\\s-*define\\s-+\\S-+\\(\\s-+\\)")(modes.align-c++-modes))(c-variable-declaration(regexp.,(concat"[*&0-9A-Za-z_]>?[&*]*\\(\\s-+[*&]*\\)""[A-Za-z_][0-9A-Za-z:_]*\\s-*\\(\\()\\|""=[^=\n].*\\|(.*)\\|\\(\\[.*\\]\\)*\\)?""\\s-*[;,]\\|)\\s-*$\\)"))(group.1)(modes.align-c++-modes)(justify.t)(valid.,(function(lambda()(not(or(save-excursion(goto-char(match-beginning1))(backward-word1)(looking-at"\\(goto\\|return\\|new\\|delete\\|throw\\)"))(if(and(boundp'font-lock-mode)font-lock-mode)(eq(get-text-property(point)'face)'font-lock-comment-face)(eq(caar(c-guess-basic-syntax))'c))))))))(c-assignment(regexp.,(concat"[^-=!^&*+<>/| \t\n]\\(\\s-*[-=!^&*+<>/|]*\\)""=\\(\\s-*\\)\\([^= \t\n]\\|$\\)"))(group.(12))(modes.align-c++-modes)(justify.t)(tab-stop.nil))(perl-assignment(regexp.,(concat"[^=!^&*-+<>/| \t\n]\\(\\s-*\\)=[~>]?""\\(\\s-*\\)\\([^>= \t\n]\\|$\\)"))(group.(12))(modes.align-perl-modes)(tab-stop.nil))(python-assignment(regexp.,(concat"[^=!<> \t\n]\\(\\s-*\\)=""\\(\\s-*\\)\\([^>= \t\n]\\|$\\)"))(group.(12))(modes.'(python-mode))(tab-stop.nil))(make-assignment(regexp."^\\s-*\\w+\\(\\s-*\\):?=\\(\\s-*\\)\\([^\t\n \\\\]\\|$\\)")(group.(12))(modes.'(makefile-mode))(tab-stop.nil))(c-comma-delimiter(regexp.",\\(\\s-*\\)[^/ \t\n]")(repeat.t)(modes.align-c++-modes)(run-if.,(function(lambda()current-prefix-arg)))); (valid; . ,(function; (lambda (); (memq (caar (c-guess-basic-syntax)); '(brace-list-intro; brace-list-entry; brace-entry-open))))));; With a prefix argument, comma delimiter will be aligned. Since;; perl-mode doesn't give us enough syntactic information (and we;; don't do our own parsing yet), this rule is too destructive to;; run normally.(basic-comma-delimiter(regexp.",\\(\\s-*\\)[^# \t\n]")(repeat.t)(modes.(appendalign-perl-modes'(python-mode)))(run-if.,(function(lambda()current-prefix-arg))))(c++-comment(regexp."\\(\\s-*\\)\\(//.*\\|/\\*.*\\*/\\s-*\\)$")(modes.align-c++-modes)(column.comment-column)(valid.,(function(lambda()(save-excursion(goto-char(match-beginning1))(not(bolp)))))))(c-chain-logic(regexp."\\(\\s-*\\)\\(&&\\|||\\|\\<and\\>\\|\\<or\\>\\)")(modes.align-c++-modes)(valid.,(function(lambda()(save-excursion(goto-char(match-end2))(looking-at"\\s-*\\(/[*/]\\|$\\)"))))))(perl-chain-logic(regexp."\\(\\s-*\\)\\(&&\\|||\\|\\<and\\>\\|\\<or\\>\\)")(modes.align-perl-modes)(valid.,(function(lambda()(save-excursion(goto-char(match-end2))(looking-at"\\s-*\\(#\\|$\\)"))))))(python-chain-logic(regexp."\\(\\s-*\\)\\(\\<and\\>\\|\\<or\\>\\)")(modes.'(python-mode))(valid.,(function(lambda()(save-excursion(goto-char(match-end2))(looking-at"\\s-*\\(#\\|$\\|\\\\\\)"))))))(c-macro-line-continuation(regexp."\\(\\s-*\\)\\\\$")(modes.align-c++-modes)(column.c-backslash-column)); (valid; . ,(function; (lambda (); (memq (caar (c-guess-basic-syntax)); '(cpp-macro cpp-macro-cont))))))(basic-line-continuation(regexp."\\(\\s-*\\)\\\\$")(modes.'(python-modemakefile-mode)))(tex-record-separator(regexp.,(function(lambda(endreverse)(align-match-tex-pattern"&"endreverse))))(group.(12))(modes.align-tex-modes)(repeat.t))(tex-tabbing-separator(regexp.,(function(lambda(endreverse)(align-match-tex-pattern"\\\\[=>]"endreverse))))(group.(12))(modes.align-tex-modes)(repeat.t)(run-if.,(function(lambda()(eqmajor-mode'latex-mode)))))(tex-record-break(regexp."\\(\\s-*\\)\\\\\\\\")(modes.align-tex-modes));; With a numeric prefix argument, or C-u, space delimited text;; tables will be aligned.(text-column(regexp."\\(^\\|\\S-\\)\\([ \t]+\\)\\(\\S-\\|$\\)")(group.2)(modes.align-text-modes)(repeat.t)(run-if.,(function(lambda()(andcurrent-prefix-arg(not(eq'-current-prefix-arg)))))));; With a negative prefix argument, lists of dollar figures will;; be aligned.(text-dollar-figure(regexp."\\$?\\(\\s-+[0-9]+\\)\\.")(modes.align-text-modes)(justify.t)(run-if.,(function(lambda()(eq'-current-prefix-arg)))))(css-declaration(regexp."^\\s-*\\w+:\\(\\s-*\\).*;")(group.(1))(modes.'(css-modehtml-mode))))"*A list describing all of the available alignment rules.The format is: ((TITLE (ATTRIBUTE . VALUE) ...) ...)The following attributes are meaningful:`regexp' This required attribute must be either a string describing a regular expression, or a function (described below). For every line within the section that this regular expression matches, the given rule will be applied to that line. The exclusion rules denote which part(s) of the line should not be modified; the alignment rules cause the identified whitespace group to be contracted/expanded such that the \"alignment character\" (the character immediately following the identified parenthesis group), occurs in the same column for every line within the alignment section (see `align-region-separate' for a description of how the region is broken up into alignment sections). The `regexp' attribute describes how the text should be treated. Within this regexp, there must be at least one group of characters (typically whitespace) identified by the special opening and closing parens used in regexp expressions (`\\\\(' and `\\\\)') (see the Emacs manual on the syntax of regular expressions for more info). If `regexp' is a function, it will be called as a replacement for `re-search-forward'. This means that it should return nil if nothing is found to match the rule, or it should set the match data appropriately, move point to the end of the match, and return the value of point.`group' For exclusion rules, the group identifies the range of characters that should be ignored. For alignment rules, these are the characters that will be deleted/expanded for the purposes of alignment. The \"alignment character\" is always the first character immediately following this parenthesis group. This attribute may also be a list of integer, in which case multiple alignment characters will be aligned, with the list of integer identifying the whitespace groups which precede them. The default for this attribute is 1.`modes' The `modes' attribute, if set, should name a list of major modes -- or evaluate to such a value -- in which the rule is valid. If not set, the rule will apply to all modes.`case-fold' If `regexp' is an ordinary regular expression string containing alphabetic character, sometimes you may want the search to proceed case-insensitively (for languages that ignore case, such as pascal for example). In that case, set `case-fold' to a non-nil value, and the regular expression search will ignore case. If `regexp' is set to a function, that function must handle the job of ignoring case by itself.`tab-stop' If the `tab-stop' attribute is set, and non-nil, the alignment character will always fall on a tab stop (whether it uses tabs to get there or not depends on the value of `indent-tabs-mode'). If the `tab-stop' attribute is set to nil, tab stops will never be used. Otherwise, the value of `align-to-tab-stop' determines whether or not to align to a tab stop. The `tab-stop' attribute may also be a list of t or nil values, corresponding to the number of parenthesis groups specified by the `group' attribute.`repeat' If the `repeat' attribute is present, and non-nil, the rule will be applied to the line continuously until no further matches are found.`valid' If the `valid' attribute is set, it will be used to determine whether the rule should be invoked. This form is evaluated after the regular expression match has been performed, so that it is possible to use the results of that match to determine whether the alignment should be performed. The buffer should not be modified during the evaluation of this form.`run-if' Like `valid', the `run-if' attribute tests whether the rule should be run at all -- even before any searches are done to determine if the rule applies to the alignment region. This can save time, since `run-if' will only be run once for each rule. If it returns nil, the rule will not be attempted.`column' For alignment rules, if the `column' attribute is set -- which must be an integer, or a symbol whose value is an integer -- it will be used as the column in which to align the alignment character. If the text on a particular line happens to overrun that column, a single space character, or tab stop (see `align-to-tab-stop') will be added between the last text character and the alignment character.`spacing' Alignment rules may also override the amount of spacing that would normally be used by providing a `spacing' attribute. This must be an integer, or a list of integers corresponding to the number of parenthesis groups matched by the `group' attribute. If a list of value is used, and any of those values is nil, `align-default-spacing' will be used for that subgroup. See `align-default-spacing' for more details on spacing, tab stops, and how to indicate how much spacing should be used. If TAB-STOP is present, it will override the value of `align-to-tab-stop' for that rule.`justify' It is possible with `regexp' and `group' to identify a character group that contains more than just whitespace characters. By default, any non-whitespace characters in that group will also be deleted while aligning the alignment character. However, if the `justify' attribute is set to a non-nil value, only the initial whitespace characters within that group will be deleted. This has the effect of right-justifying the characters that remain, and can be used for outdenting or just plain old right- justification.`separate' Each rule can define its own section separator, which describes how to identify the separation of \"sections\" within the region to be aligned. Setting the `separate' attribute overrides the value of `align-region-separate' (see the documentation of that variable for possible values), and any separation argument passed to `align'.":typealign-rules-list-type:group'align)(put'align-rules-list'risky-local-variablet)(defvaralign-exclude-rules-list-type'(repeat(cons:tag"Exclusion rule"(symbol:tag"Title")(cons:tag"Required attributes"(cons:tag"Regexp"(const:tag"(Regular expression to match)"regexp)(choice:value"\\(\\s-+\\)"regexpfunction))(repeat:tag"Optional attributes"(choice(cons:tag"Repeat"(const:tag"(Repeat this rule throughout line)"repeat)(boolean:valuet))(cons:tag"Paren group"(const:tag"(Parenthesis group to use)"group)(choice:value2integer(repeatinteger)))(cons:tag"Modes"(const:tag"(Modes where this rule applies)"modes)(sexp:value(text-mode)))(cons:tag"Case-fold"(const:tag"(Should case be ignored for this rule)"case-fold)(boolean:valuet)))))))"The `type' form for any `align-exclude-rules-list' variable.")(defcustomalign-exclude-rules-list`((exc-dq-string(regexp."\"\\([^\"\n]+\\)\"")(repeat.t)(modes.align-dq-string-modes))(exc-sq-string(regexp."'\\([^'\n]+\\)'")(repeat.t)(modes.align-sq-string-modes))(exc-open-comment(regexp.,(function(lambda(endreverse)(funcall(ifreverse're-search-backward're-search-forward)(concat"[^ \t\n\\\\]"(regexp-quotecomment-start)"\\(.+\\)$")endt))))(modes.align-open-comment-modes))(exc-c-comment(regexp."/\\*\\(.+\\)\\*/")(repeat.t)(modes.align-c++-modes))(exc-c-func-params(regexp."(\\([^)\n]+\\))")(repeat.t)(modes.align-c++-modes))(exc-c-macro(regexp."^\\s-*#\\s-*\\(if\\w*\\|endif\\)\\(.*\\)$")(group.2)(modes.align-c++-modes)))"*A list describing text that should be excluded from alignment.See the documentation for `align-rules-list' for more info.":typealign-exclude-rules-list-type:group'align)(put'align-exclude-rules-list'risky-local-variablet);;; Internal Variables:(defvaralign-mode-rules-listnil"Alignment rules specific to the current major mode.See the variable `align-rules-list' for more details.")(make-variable-buffer-local'align-mode-rules-list)(defvaralign-mode-exclude-rules-listnil"Alignment exclusion rules specific to the current major mode.See the variable `align-exclude-rules-list' for more details.")(make-variable-buffer-local'align-mode-exclude-rules-list)(defvaralign-highlight-overlaysnil"The current overlays highlighting the text matched by a rule.");; Sample extension rule set, for vhdl-mode. This should properly be;; in vhdl-mode.el itself.(defcustomalign-vhdl-rules-list`((vhdl-declaration(regexp."\\(signal\\|variable\\|constant\\)\\(\\s-+\\)\\S-")(group.2))(vhdl-case(regexp."\\(others\\|[^ \t\n=<]\\)\\(\\s-*\\)=>\\(\\s-*\\)\\S-")(group.(23))(valid.,(function(lambda()(not(string=(downcase(match-string1))"others"))))))(vhdl-colon(regexp."[^ \t\n:]\\(\\s-*\\):\\(\\s-*\\)[^=\n]")(group.(12)))(direction(regexp.":\\s-*\\(in\\|out\\|inout\\|buffer\\)\\(\\s-*\\)")(group.2))(sig-assign(regexp."[^ \t\n=<]\\(\\s-*\\)<=\\(\\s-*\\)\\S-")(group.(12)))(var-assign(regexp."[^ \t\n:]\\(\\s-*\\):="))(use-entity(regexp."\\(\\s-+\\)use\\s-+entity")))"*Alignment rules for `vhdl-mode'. See `align-rules-list' for more info.":typealign-rules-list-type:group'align)(put'align-vhdl-rules-list'risky-local-variablet)(defunalign-set-vhdl-rules()"Setup the `align-mode-rules-list' variable for `vhdl-mode'."(setqalign-mode-rules-listalign-vhdl-rules-list))(add-hook'vhdl-mode-hook'align-set-vhdl-rules)(add-to-list'align-dq-string-modes'vhdl-mode)(add-to-list'align-open-comment-modes'vhdl-mode);;; User Functions:;;;###autoload(defunalign(begend&optionalseparaterulesexclude-rules)"Attempt to align a region based on a set of alignment rules.BEG and END mark the region. If BEG and END are specifically set tonil (this can only be done programmatically), the beginning and end ofthe current alignment section will be calculated based on the locationof point, and the value of `align-region-separate' (or possibly eachrule's `separate' attribute).If SEPARATE is non-nil, it overrides the value of`align-region-separate' for all rules, except those that have their`separate' attribute set.RULES and EXCLUDE-RULES, if either is non-nil, will replace thedefault rule lists defined in `align-rules-list' and`align-exclude-rules-list'. See `align-rules-list' for more detailson the format of these lists."(interactive"r")(let((separator(orseparate(if(and(symbolpalign-region-separate)(boundpalign-region-separate))(symbol-valuealign-region-separate)align-region-separate)'entire)))(if(not(or;(eq separator 'largest)(and(functionpseparator)(not(funcallseparatornilnil)))))(align-regionbegendseparator(orrulesalign-mode-rules-listalign-rules-list)(orexclude-rulesalign-mode-exclude-rules-listalign-exclude-rules-list))(let((sec-firstend)(sec-lastbeg))(align-regionbegend(orexclude-rulesalign-mode-exclude-rules-listalign-exclude-rules-list)nilseparator(function(lambda(bemode)(when(andmode(listpmode))(setqsec-first(minsec-firstb)sec-last(maxsec-laste))))))(if(<sec-firstsec-last)(align-regionsec-firstsec-last'entire(orrulesalign-mode-rules-listalign-rules-list)(orexclude-rulesalign-mode-exclude-rules-listalign-exclude-rules-list)))))));;;###autoload(defunalign-regexp(begendregexp&optionalgroupspacingrepeat)"Align the current region using an ad-hoc rule read from the minibuffer.BEG and END mark the limits of the region. This function will promptfor the REGEXP to align with. If no prefix arg was specified, youonly need to supply the characters to be lined up and any precedingwhitespace is replaced. If a prefix arg was specified, the fullregexp with parenthesized whitespace should be supplied; it will alsoprompt for which parenthesis GROUP within REGEXP to modify, the amountof SPACING to use, and whether or not to REPEAT the rule throughoutthe line. See `align-rules-list' for more information about theseoptions.For example, let's say you had a list of phone numbers, and wanted toalign them so that the opening parentheses would line up: Fred (123) 456-7890 Alice (123) 456-7890 Mary-Anne (123) 456-7890 Joe (123) 456-7890There is no predefined rule to handle this, but you could easily do itusing a REGEXP like \"(\". All you would have to do is to mark theregion, call `align-regexp' and type in that regular expression."(interactive(append(list(region-beginning)(region-end))(ifcurrent-prefix-arg(list(read-string"Complex align using regexp: ""\\(\\s-*\\)")(string-to-number(read-string"Parenthesis group to modify (justify if negative): ""1"))(string-to-number(read-string"Amount of spacing (or column if negative): "(number-to-stringalign-default-spacing)))(y-or-n-p"Repeat throughout line? "))(list(concat"\\(\\s-*\\)"(read-string"Align regexp: "))1align-default-spacingnil))))(let((rule(list(listnil(cons'regexpregexp)(cons'group(absgroup))(if(<group0)(cons'justifyt)(cons'bogusnil))(if(>=spacing0)(cons'spacingspacing)(cons'column(absspacing)))(cons'repeatrepeat)))))(align-regionbegend'entirerulenilnil)));;;###autoload(defunalign-entire(begend&optionalrulesexclude-rules)"Align the selected region as if it were one alignment section.BEG and END mark the extent of the region. If RULES or EXCLUDE-RULESis set to a list of rules (see `align-rules-list'), it can be used tooverride the default alignment rules that would have been used toalign that section."(interactive"r")(alignbegend'entirerulesexclude-rules));;;###autoload(defunalign-current(&optionalrulesexclude-rules)"Call `align' on the current alignment section.This function assumes you want to align only the current section, andso saves you from having to specify the region. If RULES orEXCLUDE-RULES is set to a list of rules (see `align-rules-list'), itcan be used to override the default alignment rules that would havebeen used to align that section."(interactive)(alignnilnilnilrulesexclude-rules));;;###autoload(defunalign-highlight-rule(begendtitle&optionalrulesexclude-rules)"Highlight the whitespace which a given rule would have modified.BEG and END mark the extent of the region. TITLE identifies the rulethat should be highlighted. If RULES or EXCLUDE-RULES is set to alist of rules (see `align-rules-list'), it can be used to override thedefault alignment rules that would have been used to identify the textto be colored."(interactive(list(region-beginning)(region-end)(completing-read"Title of rule to highlight: "(mapcar(function(lambda(rule)(list(symbol-name(carrule)))))(append(oralign-mode-rules-listalign-rules-list)(oralign-mode-exclude-rules-listalign-exclude-rules-list)))nilt)))(let((ex-rule(assq(interntitle)(oralign-mode-exclude-rules-listalign-exclude-rules-list)))face)(align-unhighlight-rule)(align-regionbegend'entire(orrules(ifex-rule(orexclude-rulesalign-mode-exclude-rules-listalign-exclude-rules-list)(oralign-mode-rules-listalign-rules-list)))(unlessex-rule(orexclude-rulesalign-mode-exclude-rules-listalign-exclude-rules-list))(function(lambda(bemode)(if(andmode(listpmode))(if(equal(symbol-name(carmode))title)(setqface(consalign-highlight-change-facealign-highlight-nochange-face))(setqfacenil))(whenface(let((overlay(make-overlaybe)))(setqalign-highlight-overlays(consoverlayalign-highlight-overlays))(overlay-putoverlay'face(ifmode(carface)(cdrface)))))))))));;;###autoload(defunalign-unhighlight-rule()"Remove any highlighting that was added by `align-highlight-rule'."(interactive)(whilealign-highlight-overlays(delete-overlay(caralign-highlight-overlays))(setqalign-highlight-overlays(cdralign-highlight-overlays))));;;###autoload(defunalign-newline-and-indent()"A replacement function for `newline-and-indent', aligning as it goes."(interactive)(let((separate(or(if(and(symbolpalign-region-separate)(boundpalign-region-separate))(symbol-valuealign-region-separate)align-region-separate)'entire))(end(point)))(call-interactively'newline-and-indent)(save-excursion(forward-line-1)(while(not(or(bobp)(align-new-section-p(point)endseparate)))(forward-line-1))(align(point)end))));;; Internal Functions:(defunalign-match-tex-pattern(regexpend&optionalreverse)"Match REGEXP in TeX mode, counting backslashes appropriately.END denotes the end of the region to be searched, while REVERSE, ifnon-nil, indicates that the search should proceed backward from thecurrent position."(let(result)(while(and(setqresult(funcall(ifreverse're-search-backward're-search-forward)(concat"\\(\\s-*\\)"regexp"\\(\\s-*\\)")endt))(let((pos(match-end1))(count0))(while(and(>pos(point-min))(eq(char-beforepos)?\\))(setqcount(1+count)pos(1-pos)))(eq(modcount2)1))(goto-char(match-beginning2))))result))(defunalign-new-section-p(begendseparator)"Is there a section divider between BEG and END?SEPARATOR specifies how to look for the section divider. See thedocumentation for `align-region-separate' for more details."(cond((or(notseparator)(eqseparator'entire))nil)((eqseparator'group)(let((amount2))(save-excursion(goto-charend)(if(bolp)(setqamount1)))(>(count-linesbegend)amount)))((stringpseparator)(save-excursion(goto-charbeg)(re-search-forwardseparatorendt)))((functionpseparator)(funcallseparatorbegend))((listpseparator)(let((sepsseparator)yes)(whileseps(if(and(>=(carseps)beg)(<=(carseps)end))(setqyestsepsnil)(setqseps(cdrseps))))yes))))(defunalign-adjust-col-for-rule(columnrulespacingtab-stop)"Adjust COLUMN according to the given RULE.SPACING specifies how much spacing to use.TAB-STOP specifies whether SPACING refers to tab-stop boundaries."(unlessspacing(setqspacingalign-default-spacing))(if(<=spacing0)column(if(nottab-stop)(+columnspacing)(let((stopstab-stop-list))(whilestops(if(and(>(carstops)column)(=(setqspacing(1-spacing))0))(setqcolumn(carstops)stopsnil)(setqstops(cdrstops)))))column)))(defsubstalign-column(pos)"Given a position in the buffer, state what column it's in.POS is the position whose column will be taken. Note that thisfunction will change the location of point."(goto-charpos)(current-column))(defsubstalign-regions(regionspropsrulefunc)"Align the regions specified in REGIONS, a list of cons cells.PROPS describes formatting features specific to the given regions.RULE specifies exactly how to perform the alignments.If FUNC is specified, it will be called with each region that wouldhave been aligned, rather than modifying the text."(whileregions(save-excursion(align-areas(carregions)(carprops)rulefunc))(setqregions(cdrregions)props(cdrprops))))(defunalign-areas(areaspropsrulefunc)"Given a list of AREAS and formatting PROPS, align according to RULE.AREAS should be a list of cons cells containing beginning and endingmarkers. This function sweeps through all of the beginning markers,finds out which one starts in the furthermost column, and then deletesand inserts text such that all of the ending markers occur in the samecolumn.If FUNC is non-nil, it will be called for each text region that wouldhave been aligned. No changes will be made to the buffer."(let*((column(cdr(assq'columnrule)))(fixed(if(symbolpcolumn)(symbol-valuecolumn)column))(justify(cdr(assq'justifyrule)))(col(orfixed0))(width0)ecolchangelook);; Determine the alignment column.(let((aareas))(whilea(unlessfixed(setqcol(maxcol(align-column(caara)))))(unlesschange(goto-char(cdara))(ifecol(if(/=ecol(current-column))(setqchanget))(setqecol(current-column))))(whenjustify(goto-char(caara))(if(and(re-search-forward"\\s-*"(cdara)t)(/=(point)(cdara)))(let((bcol(current-column)))(setcdr(cara)(cons(point-marker)(cdara)))(goto-char(cdr(cdara)))(setqwidth(maxwidth(-(current-column)bcol))))))(setqa(cdra))))(unlessfixed(setqcol(+(align-adjust-col-for-rulecolrule(carprops)(cdrprops))width)));; Make all ending positions to occur in the goal column. Since;; the whitespace to be modified was already deleted by;; `align-region', all we have to do here is indent.(unlesschange(setqchange(andecol(/=colecol))))(when(orfuncchange)(whileareas(let((area(carareas))(gocolcol)cur)(whenarea(iffunc(funcallfunc(cararea)(cdrarea)change)(if(not(andjustify(consp(cdrarea))))(goto-char(cdrarea))(goto-char(cddrarea))(let((ecol(current-column)))(goto-char(cadrarea))(setqgocol(-col(-ecol(current-column))))))(setqcur(current-column))(cond((<gocol0)t); don't do anything((=curgocol)t); don't need to((<curgocol); just add space;; FIXME: It is stated above that "...the;; whitespace to be modified was already;; deleted by `align-region', all we have;; to do here is indent." However, this;; doesn't seem to be true, so we first;; delete the whitespace to avoid tabs;; after spaces.(delete-horizontal-spacet)(indent-togocol))(t;; This code works around an oddity in the;; FORCE argument of `move-to-column', which;; tends to screw up markers if there is any;; tabbing.(let((endcol(align-column(if(andjustify(consp(cdrarea)))(cadrarea)(cdrarea))))(abuts(<=gocol(align-column(cararea)))))(ifabuts(goto-char(cararea))(move-to-columngocolt))(let((here(point)))(move-to-columnendcolt)(delete-regionhere(point))(ifabuts(indent-to(align-adjust-col-for-rule(current-column)rule(carprops)(cdrprops)))))))))))(setqareas(cdrareas))))))(defunalign-region(begendseparaterulesexclude-rules&optionalfunc)"Align a region based on a given set of alignment rules.BEG and END specify the region to be aligned. Either may be nil, inwhich case the range will stop at the nearest section division (see`align-region-separate', and `align-region-heuristic' for moreinformation').The region will be divided into separate alignment sections based onthe value of SEPARATE.RULES and EXCLUDE-RULES are a pair of lists describing how to alignthe region, and which text areas within it should be excluded fromalignment. See the `align-rules-list' for more information on therequired format of these two lists.If FUNC is specified, no text will be modified. What `align-region'will do with the rules is to search for the alignment areas, as itregularly would, taking account for exclusions, and then call FUNC,first with the beginning and ending of the region to be alignedaccording to that rule (this can be different for each rule, if BEGand END were nil), and then with the beginning and ending of eachtext region that the rule would have applied to.The signature of FUNC should thus be: (defun my-align-function (beg end mode) \"If MODE is a rule (a list), return t if BEG to END are to be searched.Otherwise BEG to END will be a region of text that matches the rule'sdefinition, and MODE will be non-nil if any changes are necessary.\" (unless (and mode (listp mode)) (message \"Would have aligned from %d to %d...\" beg end)))This feature (of passing a FUNC) is used internally to locate theposition of exclusion areas, but could also be used for any otherpurpose where you might want to know where the regions that thealigner would have dealt with are."(let((end-mark(andend(copy-markerendt)))(real-begbeg)(real-endend)(report(and(notfunc)align-large-regionbegend(>=(-endbeg)align-large-region)))(rule-index1)(rule-count(lengthrules)))(if(andalign-indent-before-aligningreal-begend-mark)(indent-regionreal-begend-marknil))(whilerules(let*((rule(carrules))(run-if(assq'run-ifrule))(modes(assq'modesrule)));; unless the `run-if' form tells us not to, look for the;; rule..(unless(or(andmodes(not(memqmajor-mode(eval(cdrmodes)))))(andrun-if(not(funcall(cdrrun-if)))))(let*((current-case-foldcase-fold-search)(case-fold(assq'case-foldrule))(regexp(cdr(assq'regexprule)))(regfunc(and(functionpregexp)regexp))(rulesep(assq'separaterule))(thissep(ifrulesep(cdrrulesep)separate))same(eol0)groupgroup-cspacingspacing-ctab-stoptab-stop-crepeatrepeat-cvalidvalid-cpos-listfirstregionsindexlast-pointbesave-match-dataexclude-palign-props)(save-excursion;; if beg and end were not given, figure out what the;; current alignment region should be. Depending on the;; value of `align-region-separate' it's possible for;; each rule to have its own definition of what that;; current alignment section is.(ifreal-beg(goto-charbeg)(if(or(notthissep)(eqthissep'entire))(error"Cannot determine alignment region for '%s'"(symbol-name(cdr(assq'titlerule)))))(beginning-of-line)(while(and(not(eobp))(looking-at"^\\s-*$"))(forward-line))(let*((here(point))(starthere))(while(andhere(let((terminus(andalign-region-heuristic(-(point)align-region-heuristic))))(ifregfunc(funcallregfuncterminust)(re-search-backwardregexpterminust))))(if(align-new-section-p(point)herethissep)(setqbeghereherenil)(setqhere(point))))(if(nothere)(goto-charbeg))(beginning-of-line)(setqbeg(point))(goto-charstart)(setqhere(point))(while(andhere(let((terminus(andalign-region-heuristic(+(point)align-region-heuristic))))(ifregfunc(funcallregfuncterminusnil)(re-search-forwardregexpterminust))))(if(align-new-section-phere(point)thissep)(setqendhereherenil)(setqhere(point))))(if(nothere)(goto-charend))(forward-line)(setqend(point)end-mark(copy-markerendt))(goto-charbeg)));; If we have a region to align, and `func' is set and;; reports back that the region is ok, then align it.(when(or(notfunc)(funcallfuncbegendrule))(unwind-protect(let(exclude-areas);; determine first of all where the exclusions;; lie in this region(whenexclude-rules;; guard against a problem with recursion and;; dynamic binding vs. lexical binding, since;; the call to `align-region' below will;; re-enter this function, and rebind;; `exclude-areas'(set(setqexclude-areas(make-symbol"align-exclude-areas"))nil)(align-regionbegend'entireexclude-rulesnil`(lambda(bemode)(or(andmode(listpmode))(set(quote,exclude-areas)(cons(consbe),exclude-areas)))))(setqexclude-areas(sort(symbol-valueexclude-areas)(function(lambda(lr)(>=(carl)(carr)))))));; set `case-fold-search' according to the;; (optional) `case-fold' property(andcase-fold(setqcase-fold-search(cdrcase-fold)));; while we can find the rule in the alignment;; region..(while(and(<(point)end-mark)(ifregfunc(funcallregfuncend-marknil)(re-search-forwardregexpend-markt)));; give the user some indication of where we;; are, if it's a very large region being;; aligned(ifreport(let((symbol(carrule)))(if(andsymbol(symbolpsymbol))(message"Aligning `%s' (rule %d of %d) %d%%..."(symbol-namesymbol)rule-indexrule-count(/(*(-(point)real-beg)100)(-end-markreal-beg)))(message"Aligning %d%%..."(/(*(-(point)real-beg)100)(-end-markreal-beg))))));; if the search ended us on the beginning of;; the next line, move back to the end of the;; previous line.(if(bolp)(forward-char-1));; lookup the `group' attribute the first time;; that we need it(unlessgroup-c(setqgroup(or(cdr(assq'grouprule))1))(if(listpgroup)(setqfirst(cargroup))(setqfirstgroupgroup(listgroup)))(setqgroup-ct))(unlessspacing-c(setqspacing(cdr(assq'spacingrule))spacing-ct))(unlesstab-stop-c(setqtab-stop(let((rule-ts(assq'tab-stoprule)))(ifrule-ts(cdrrule-ts)(if(symbolpalign-to-tab-stop)(symbol-valuealign-to-tab-stop)align-to-tab-stop)))tab-stop-ct));; test whether we have found a match on the same;; line as a previous match(if(>(point)eol)(setqsamenileol(save-excursion(end-of-line)(point-marker))));; lookup the `repeat' attribute the first time(orrepeat-c(setqrepeat(cdr(assq'repeatrule))repeat-ct));; lookup the `valid' attribute the first time(orvalid-c(setqvalid(assq'validrule)valid-ct));; remember the beginning position of this rule;; match, and save the match-data, since either;; the `valid' form, or the code that searches for;; section separation, might alter it(setqb(match-beginningfirst)save-match-data(match-data));; unless the `valid' attribute is set, and tells;; us that the rule is not valid at this point in;; the code..(unless(andvalid(not(funcall(cdrvalid))));; look to see if this match begins a new;; section. If so, we should align what we've;; collected so far, and then begin collecting;; anew for the next alignment section(if(andlast-point(align-new-section-plast-pointbthissep))(progn(align-regionsregionsalign-propsrulefunc)(setqlast-point(copy-markerbt)regionsnilalign-propsnil))(setqlast-point(copy-markerbt)));; restore the match data(set-match-datasave-match-data);; check whether the region to be aligned;; straddles an exclusion area(let((exclsexclude-areas))(setqexclude-pnil)(whileexcls(if(and(<(match-beginning(cargroup))(cdarexcls))(>(match-end(car(lastgroup)))(caarexcls)))(setqexclude-ptexclsnil)(setqexcls(cdrexcls)))));; go through the list of parenthesis groups;; matching whitespace text to be;; contracted/expanded (or possibly;; justified, if the `justify' attribute was;; set)(unlessexclude-p(let((ggroup))(whileg;; we have to use markers, since;; `align-areas' may modify the buffer(setqb(copy-marker(match-beginning(carg))t)e(copy-marker(match-end(carg))t));; record this text region for alignment(setqindex(ifsame(1+index)0))(let((region(consbe))(props(cons(if(listpspacing)(carspacing)spacing)(if(listptab-stop)(cartab-stop)tab-stop))))(if(nthindexregions)(setcar(nthcdrindexregions)(consregion(nthindexregions)))(ifregions(progn(nconcregions(list(listregion)))(nconcalign-props(listprops)))(setqregions(list(listregion)))(setqalign-props(listprops)))));; if any further rule matches are;; found before `eol', then they are;; on the same line as this one; this;; can only happen if the `repeat';; attribute is non-nil(if(listpspacing)(setqspacing(cdrspacing)))(if(listptab-stop)(setqtab-stop(cdrtab-stop)))(setqsametg(cdrg))));; if `repeat' has not been set, move to;; the next line; don't bother searching;; anymore on this one(if(and(notrepeat)(not(bolp)))(forward-line)))));; when they are no more matches for this rule,;; align whatever was left over(ifregions(align-regionsregionsalign-propsrulefunc)))(setqcase-fold-searchcurrent-case-fold)))))))(setqrules(cdrrules)rule-index(1+rule-index)))(ifreport(message"Aligning...done"))));; Provide:(provide'align)(run-hooks'align-load-hook);;; arch-tag: ef79cccf-1db8-4888-a8a1-d7ce2d1532f7;;; align.el ends here