Skip to main content

Sort lines by length and then alphabet in Xcode

·207 words·1 min

I admit it, I’m a stickler for pretty code. One thing that offends my sense of aesthetics is when the #import block at the top of a .m file is all ragged. Much better to have them sorted by line length. But what about comments? And shouldn’t lines of the same length be sorted alphabetically?

I had a script to do this in Xcode 3, but then Xcode 4 came along and did away with scripts. But that’s because there’s now a way to do it with Automator. Follow these instructions:

http://stackoverflow.com/questions/8103971/sort-lines-in-selection-for-xcode-4

And then set the Shell to /usr/bin/perl and put this code in the Automator “Run Shell Script” action:

my @l;

my $chomped = 0;

sub trim {
    ($trimmed, @drop) = split(q-//-, $_[0]);
    $trimmed =~ s/\s+$//;
    return $trimmed;
}

while (<>) {
    $l[$.] = $_;
}

# Remove the last line if it's just a newline
if (length($l[$#l]) == 1) {
    $chomped = 1;
    pop(@l);
}

@sorted = sort { length trim($a) <=> length trim($b) or lc($a) cmp lc($b) } @l;

print @sorted;

if ($chomped) {
    print "\n";
}

Finally, visit  > System Preferences… > Keyboard > Keyboard Shortcuts > Services and assign your new service a shortcut. (I chose Cmd-Opt-Ctrl-S.) And away you go.