Sorting parameter arguments and array keys in Vim

Given this PHP code (for example):

$a = [
  'b' => 2,
  'a' => 4,
  'k' => 5,
  'f' => 1,
  'd' => 3,
];

$b = new Foo(
  b: 2,
  a: 4,
  k: 5,
  f: 1,
  d: 3,
);

You can use vi( and vi[ to visually select the text within the array or parentheses, and then ":sort" to sort the text within the selected range.

Using vi( and vi[ instead of vi) and vi] excludes the lines that around the text to sort.

After running these commands, you should get this:

$a = [
  'a' => 4,
  'b' => 2,
  'd' => 3,
  'f' => 1,
  'k' => 5,
];

$b = new Foo(
  a: 4,
  b: 2,
  d: 3,
  f: 1,
  k: 5,
);

At some point, I'll look into saving this as a macro with a keymap like <leader>sa (sort arguments) and <leader>sk (sort keys).

Tags