Skip to content

Indent and align at the same time #599

Closed
@antoineB

Description

@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 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))))

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions