Tryer
Tryer

Reputation: 4080

Sort class member functions and variables in ascending order in header file

Given a class declaration thus:

class foo_{
public:
    int t1();
    const std::vector<int> & ureference(); 
private:
    std::vector<std::pair<int, int>> vecofpairs;
    string name;
}

I would like to sort the public functions in ascending order of their names. The following command in vim after appropriate visual selection of the lines:

:'<,'>,!sort -k2

sorts the functions thus:

const std::vector<int> & ureference(); 
int t1();

The sort sorts on the second column which in this case are std::... and t1();. Yet, this is not what I want. I want the sorting to be based on the column before the ( on each line, so that the sorted order is:

int t1();
const std::vector<int> & ureference(); 

Likewise, I'd like to sort the member variables based on the column name immediately preceding ; so that the sorted order is:

string name;
std::vector<std::pair<int, int>> vecofpairs;

Is there any appropriate vim shortcuts to achieve this? Or else, how can sort be used to sort based on field immediately prior to ( or ; ?

Upvotes: 0

Views: 179

Answers (1)

filbranden
filbranden

Reputation: 8898

You can use Vim's built-in :sort command to sort on arbitrary parts of the lines.

The built-in :sort can take a pattern, and then either skip that pattern or match that pattern to decide what to use as a key for sorting.

For example, in your case you can use /.* / as a pattern to skip everything until the last space on the line. (This requires that there's no trailing spaces after the ;.)

To sort the methods:

:3,4sort /.* /

And the members:

:6,7sort /.* /

But perhaps this isn't exactly what you need. Say your methods have arguments (with spaces between them) and let's say you have a & or * next to the method name (int *findmin(int *arr); for example.)

Then you can match the method name with /\k\S*(/, that is a keyword character (so not * or &), followed by non-whitespace, followed by a literal (. You pass :sort a r flag to sort on the pattern match (not skip it), so:

:'<,'>sort /\k\S*(/ r

This last one is using Visual mode to select the block with the methods. When you press : from Visual mode, it will automatically fill in :'<,'> to use the range of lines from the Visual selection in the next command.

Vim regexes are really flexible, so you should be able to go very far with this setup as long as you're comfortable with them. I strongly recommend checking out :help :sort, which has some examples, and probaly read :help pattern.txt in its entirety.

Upvotes: 3

Related Questions