Skip to content
USAMI Kenta edited this page Dec 22, 2019 · 1 revision

Indent and align at the same time (#559 by @antoineB)

It could be good to easily indent this:

$abc = 1;
$abcd = 2;
$abcde = 3;

['abc' => 1,
 'abcd' => 2,
 'abcde' => 3];

Into:

$abc   = 1;
$abcd  = 2;
$abcde = 3;

['abc'   => 1,
 'abcd'  => 2,
 'abcde' => 3];

The following code does this if the caret is before = or => and leverage align-regexp, maybe there is another option using cc-engine indentation mechanism that will work with indent-region.

(defun my-php-indent-align ()
  (interactive)
  (cond ((looking-at "[ \t]*=>")
         (let* ((begin (cadr (syntax-ppss)))
                (end (when begin (condition-case nil (scan-sexps begin 1) ('error nil)))))
           (when end
             (align-regexp begin (scan-sexps begin 1) "\\(\\s-*\\)=>"))))
        ((looking-at "[ \t]*=[$ \ta-zA-Z0-9_'\"\\\\]")
         (let* ((ss (cadr (syntax-ppss)))
                (sp (save-excursion (backward-paragraph 1) (point)))
                (begin (if ss (max ss sp) sp))
                (es (when ss (condition-case nil (scan-sexps ss 1) ('error nil))))
                (ep (save-excursion (forward-paragraph 1) (point)))
                (end (if es (min es ep) ep)))
           (align-regexp begin end "\\(\\s-*\\)=")))
        ((indent-for-tab-command))))