Sort structures in file

2

For example I have file consisting of structures like

name = {
   foo = bar;
   ...
};

So in file there are lots of structures like this.
How can I sort them (I'm using vim but emacs is surely ok too) by name? But having their fields unmodified? I mean

b = {
   bfoo = bar;
   ...
};
a = {
   afoo = bar;
   ...
};

Goes to

a = {
   afoo = bar;
   ...
};
b = {
   bfoo = bar;
   ...
};

Update Structures may also contain same structures.

b = {
   c = {
       cfoo = bar;
       ...
   };
   ...
};

JagaJaga

Posted 2014-11-18T22:33:45.817

Reputation: 23

Question was closed 2014-11-23T15:47:51.623

Answers

3

Following would work with vim. Perhaps easier to wrap into a function.

:%s/$/$
:g/= {/.,/};/join!
:sort
:%s/\$/\r/g

In a nutshell

1. Replace the EOL with a special character (I've chosen $)
2. Search for "= {" and join all lines up until first "};"
3. Sort 
4. Replace the special EOL character back to a real EOL character.

Lieven Keersmaekers

Posted 2014-11-18T22:33:45.817

Reputation: 1 088

Please, check an update. – JagaJaga – 2014-11-19T18:59:37.807

@JagJaga - if the indentation of the root element is fixed, you can alter the search to something like :g/\v^\w \= \{/.,/\v^\};/;/join!. The \v sets very magic so you can use ^ in a search to indicate the start of a line (but now you have to escape the =, { and } characters) – Lieven Keersmaekers – 2014-11-20T06:31:29.803

0

For Emacs, use function sort-regexp-fields - see the Elisp manual, node Sorting.

You can also use function sort-subr, which is even more general, or function sort-paragraphs or sort-pages. For the latter two, the sections to be sorted would need to be separated by one or more blank lines (for paragraphs) or form-feed (^L) characters, and there would need to be no such characters within any section.

Drew

Posted 2014-11-18T22:33:45.817

Reputation: 1 898